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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
23df3c5413a8c04602af02c45881fda14df504b4 | 2,107 | ts | TypeScript | client/src/utils/Date.ts | Park-Systems-web/Nanoscientific-Symposium | ae4fa3a5090e3497a08a181fe37b63da459b1bd2 | [
"Unlicense"
] | 1 | 2022-02-25T03:09:08.000Z | 2022-02-25T03:09:08.000Z | client/src/utils/Date.ts | Park-Systems-web/Nanoscientific-Symposium | ae4fa3a5090e3497a08a181fe37b63da459b1bd2 | [
"Unlicense"
] | null | null | null | client/src/utils/Date.ts | Park-Systems-web/Nanoscientific-Symposium | ae4fa3a5090e3497a08a181fe37b63da459b1bd2 | [
"Unlicense"
] | null | null | null | export const dateToLocaleString = (
date: string,
timeZone?: string,
format?: string,
) => {
// ex> 2022-01-11 17:30
switch (format) {
case "MMM DD":
return new Date(date)
.toLocaleString("en-GB", {
timeZone,
month: "short",
day: "2-digit",
})
.split(" ")
.reverse()
.join(" ");
// ex> Mon, Jan 17, 2022, 02:00 PM
case "MMM DD YYYY": {
const splitResult = new Date(date)
.toLocaleString("en-US", {
timeZone,
weekday: "long",
year: "numeric",
month: "short",
day: "2-digit",
})
.split(",");
return `${splitResult[1]} (${splitResult[0]}), ${splitResult[2]}`;
}
case "HH:mm":
return new Date(date).toLocaleString("en-GB", {
timeZone,
hour: "2-digit",
minute: "2-digit",
});
default:
return new Date(date).toLocaleString("sv-SE", {
timeZone,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
});
}
};
// duration을 계산하여 hh:mm string을 반환하는 메서드
export const calculateDurationToString = (
startTime: string,
duration: number,
timeZone: string,
) => {
const time = new Date(startTime);
const minute = time.getMinutes();
time.setMinutes(minute + duration);
const timeString = time.toLocaleString("sv-SE", {
timeZone,
hour: "2-digit",
minute: "2-digit",
});
return timeString;
};
// duration 계산 후 Date 객체 반환해주는 메서드
export const calculateDurationToDate = (
startTime: string,
duration: number,
) => {
const time = new Date(startTime);
const minute = time.getMinutes();
time.setMinutes(minute + duration);
return time;
};
//
export const getUserTimezoneDate = (startTime: string, timeZone: string) => {
const newDateString = new Date(startTime).toLocaleString("sv-SE", {
timeZone,
});
return new Date(newDateString);
};
export const isDateValid = (d: Date | null) => {
return d instanceof Date && !Number.isNaN(d.getTime());
};
| 23.153846 | 77 | 0.565259 | 78 | 5 | 0 | 11 | 12 | 0 | 0 | 0 | 10 | 0 | 1 | 11.4 | 607 | 0.026359 | 0.019769 | 0 | 0 | 0.001647 | 0 | 0.357143 | 0.295631 | export const dateToLocaleString = (
date,
timeZone?,
format?,
) => {
// ex> 2022-01-11 17:30
switch (format) {
case "MMM DD":
return new Date(date)
.toLocaleString("en-GB", {
timeZone,
month: "short",
day: "2-digit",
})
.split(" ")
.reverse()
.join(" ");
// ex> Mon, Jan 17, 2022, 02:00 PM
case "MMM DD YYYY": {
const splitResult = new Date(date)
.toLocaleString("en-US", {
timeZone,
weekday: "long",
year: "numeric",
month: "short",
day: "2-digit",
})
.split(",");
return `${splitResult[1]} (${splitResult[0]}), ${splitResult[2]}`;
}
case "HH:mm":
return new Date(date).toLocaleString("en-GB", {
timeZone,
hour: "2-digit",
minute: "2-digit",
});
default:
return new Date(date).toLocaleString("sv-SE", {
timeZone,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
});
}
};
// duration을 계산하여 hh:mm string을 반환하는 메서드
export const calculateDurationToString = (
startTime,
duration,
timeZone,
) => {
const time = new Date(startTime);
const minute = time.getMinutes();
time.setMinutes(minute + duration);
const timeString = time.toLocaleString("sv-SE", {
timeZone,
hour: "2-digit",
minute: "2-digit",
});
return timeString;
};
// duration 계산 후 Date 객체 반환해주는 메서드
export const calculateDurationToDate = (
startTime,
duration,
) => {
const time = new Date(startTime);
const minute = time.getMinutes();
time.setMinutes(minute + duration);
return time;
};
//
export const getUserTimezoneDate = (startTime, timeZone) => {
const newDateString = new Date(startTime).toLocaleString("sv-SE", {
timeZone,
});
return new Date(newDateString);
};
export const isDateValid = (d) => {
return d instanceof Date && !Number.isNaN(d.getTime());
};
|
a50c9cd35f067416051d31d36ef70da95c3eb68a | 2,307 | ts | TypeScript | frontend/src/state/predictions/queries.ts | 007blockchaindeveloper/GuitarUI | a486157c7f65d7157b64034ac27511938407db22 | [
"MIT"
] | 14 | 2022-01-13T05:11:54.000Z | 2022-03-23T03:27:28.000Z | frontend/src/state/predictions/queries.ts | 007blockchaindeveloper/GuitarUI | a486157c7f65d7157b64034ac27511938407db22 | [
"MIT"
] | 2 | 2022-02-11T03:32:35.000Z | 2022-03-02T04:36:51.000Z | frontend/src/state/predictions/queries.ts | 007blockchaindeveloper/GuitarUI | a486157c7f65d7157b64034ac27511938407db22 | [
"MIT"
] | 10 | 2022-02-09T15:14:52.000Z | 2022-03-21T18:43:12.000Z | export interface UserResponse {
id: string
createdAt: string
updatedAt: string
block: string
totalBets: string
totalBetsBull: string
totalBetsBear: string
totalBNB: string
totalBNBBull: string
totalBNBBear: string
totalBetsClaimed: string
totalBNBClaimed: string
winRate: string
averageBNB: string
netBNB: string
bets?: BetResponse[]
}
export interface BetResponse {
id: string
hash: string
amount: string
position: string
claimed: boolean
claimedAt: string
claimedBlock: string
claimedHash: string
claimedBNB: string
claimedNetBNB: string
createdAt: string
updatedAt: string
block: string
user?: UserResponse
round?: RoundResponse
}
export interface HistoricalBetResponse {
id: string
hash: string
amount: string
position: string
claimed: boolean
user?: UserResponse
round: {
id: string
epoch: string
}
}
export interface RoundResponse {
id: string
epoch: string
position: string
failed: boolean
startAt: string
startBlock: string
startHash: string
lockAt: string
lockBlock: string
lockHash: string
lockPrice: string
lockRoundId: string
closeAt: string
closeBlock: string
closeHash: string
closePrice: string
closeRoundId: string
totalBets: string
totalAmount: string
bullBets: string
bullAmount: string
bearBets: string
bearAmount: string
bets?: BetResponse[]
}
export interface TotalWonMarketResponse {
totalBNB: string
totalBNBTreasury: string
}
/**
* Base fields are the all the top-level fields available in the api. Used in multiple queries
*/
export const getRoundBaseFields = () => `
id
epoch
position
failed
startAt
startBlock
startHash
lockAt
lockBlock
lockHash
lockPrice
lockRoundId
closeAt
closeBlock
closeHash
closePrice
closeRoundId
totalBets
totalAmount
bullBets
bullAmount
bearBets
bearAmount
`
export const getBetBaseFields = () => `
id
hash
amount
position
claimed
claimedAt
claimedHash
claimedBlock
claimedBNB
claimedNetBNB
createdAt
updatedAt
`
export const getUserBaseFields = () => `
id
createdAt
updatedAt
block
totalBets
totalBetsBull
totalBetsBear
totalBNB
totalBNBBull
totalBNBBear
totalBetsClaimed
totalBNBClaimed
winRate
averageBNB
netBNB
`
| 16.020833 | 94 | 0.738188 | 133 | 3 | 0 | 0 | 3 | 64 | 0 | 0 | 60 | 5 | 0 | 18.666667 | 647 | 0.004637 | 0.004637 | 0.098918 | 0.007728 | 0 | 0 | 0.857143 | 0.207441 | export interface UserResponse {
id
createdAt
updatedAt
block
totalBets
totalBetsBull
totalBetsBear
totalBNB
totalBNBBull
totalBNBBear
totalBetsClaimed
totalBNBClaimed
winRate
averageBNB
netBNB
bets?
}
export interface BetResponse {
id
hash
amount
position
claimed
claimedAt
claimedBlock
claimedHash
claimedBNB
claimedNetBNB
createdAt
updatedAt
block
user?
round?
}
export interface HistoricalBetResponse {
id
hash
amount
position
claimed
user?
round
}
export interface RoundResponse {
id
epoch
position
failed
startAt
startBlock
startHash
lockAt
lockBlock
lockHash
lockPrice
lockRoundId
closeAt
closeBlock
closeHash
closePrice
closeRoundId
totalBets
totalAmount
bullBets
bullAmount
bearBets
bearAmount
bets?
}
export interface TotalWonMarketResponse {
totalBNB
totalBNBTreasury
}
/**
* Base fields are the all the top-level fields available in the api. Used in multiple queries
*/
export const getRoundBaseFields = () => `
id
epoch
position
failed
startAt
startBlock
startHash
lockAt
lockBlock
lockHash
lockPrice
lockRoundId
closeAt
closeBlock
closeHash
closePrice
closeRoundId
totalBets
totalAmount
bullBets
bullAmount
bearBets
bearAmount
`
export const getBetBaseFields = () => `
id
hash
amount
position
claimed
claimedAt
claimedHash
claimedBlock
claimedBNB
claimedNetBNB
createdAt
updatedAt
`
export const getUserBaseFields = () => `
id
createdAt
updatedAt
block
totalBets
totalBetsBull
totalBetsBear
totalBNB
totalBNBBull
totalBNBBear
totalBetsClaimed
totalBNBClaimed
winRate
averageBNB
netBNB
`
|
3b903ad87b0d61a09599acbe3f67f1d2fc07402f | 2,442 | ts | TypeScript | problemset/create-maximum-number/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/create-maximum-number/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/create-maximum-number/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 单调栈 + 分治
* @desc 时间复杂度 O(K(M+N+k²)) 空间复杂度 O(k)
* @param nums1
* @param nums2
* @param k
* @returns
*/
export function maxNumber(nums1: number[], nums2: number[], k: number): number[] {
const m = nums1.length
const n = nums2.length
const maxSubsequence = new Array(k).fill(0)
const start = Math.max(0, k - n)
const end = Math.min(k, m)
for (let i = start; i <= end; i++) {
const subsequence1 = genMaxSubsequence(nums1, i)
const subsequence2 = genMaxSubsequence(nums2, k - i)
const curMaxSubsequence = merge(subsequence1, subsequence2)
if (compare(curMaxSubsequence, 0, maxSubsequence, 0))
maxSubsequence.splice(0, k, ...curMaxSubsequence)
}
return maxSubsequence
/**
* 从nums中生成k长度的最大子序列
* @param nums
* @param k
* @returns
*/
function genMaxSubsequence(nums: number[], k: number): number[] {
const len = nums.length
const stack = new Array(k).fill(0)
let top = -1
let remain = len - k
for (const num of nums) {
while (top >= 0 && stack[top] < num && remain > 0) {
top--
remain--
}
if (top < k - 1)
stack[++top] = num
else
remain--
}
return stack
}
/**
* 合并两个序列
* @param subsequence1
* @param subsequence2
* @returns
*/
function merge(subsequence1: number[], subsequence2: number[]): number[] {
const l1 = subsequence1.length
const l2 = subsequence2.length
if (l1 === 0) return subsequence2
if (l2 === 0) return subsequence1
const len = l1 + l2
const merged: number[] = []
let idx1 = 0
let idx2 = 0
for (let i = 0; i < len; i++) {
if (compare(subsequence1, idx1, subsequence2, idx2))
merged[i] = subsequence1[idx1++]
else
merged[i] = subsequence2[idx2++]
}
return merged
}
/**
* 比较序列
* @param subsequence1
* @param idx1
* @param subsequence2
* @param idx2
* @returns
*/
function compare(
subsequence1: number[],
idx1: number,
subsequence2: number[],
idx2: number,
): boolean {
const l1 = subsequence1.length
const l2 = subsequence2.length
while (idx1 < l1 && idx2 < l2) {
// 如果当前两个元素不相等,判断第一个序列的元素是否大于第二个序列的元素
if (subsequence1[idx1] !== subsequence2[idx2])
return subsequence1[idx1] - subsequence2[idx2] > 0
idx1++
idx2++
}
// 如果所有匹配元素都一一相等,则判断第一个序列是否还有剩余长度
return l1 - idx1 > 0
}
}
| 23.037736 | 82 | 0.588043 | 65 | 4 | 0 | 11 | 22 | 0 | 3 | 0 | 16 | 0 | 0 | 25.5 | 814 | 0.018428 | 0.027027 | 0 | 0 | 0 | 0 | 0.432432 | 0.301768 | /**
* 单调栈 + 分治
* @desc 时间复杂度 O(K(M+N+k²)) 空间复杂度 O(k)
* @param nums1
* @param nums2
* @param k
* @returns
*/
export function maxNumber(nums1, nums2, k) {
const m = nums1.length
const n = nums2.length
const maxSubsequence = new Array(k).fill(0)
const start = Math.max(0, k - n)
const end = Math.min(k, m)
for (let i = start; i <= end; i++) {
const subsequence1 = genMaxSubsequence(nums1, i)
const subsequence2 = genMaxSubsequence(nums2, k - i)
const curMaxSubsequence = merge(subsequence1, subsequence2)
if (compare(curMaxSubsequence, 0, maxSubsequence, 0))
maxSubsequence.splice(0, k, ...curMaxSubsequence)
}
return maxSubsequence
/**
* 从nums中生成k长度的最大子序列
* @param nums
* @param k
* @returns
*/
/* Example usages of 'genMaxSubsequence' are shown below:
genMaxSubsequence(nums1, i);
genMaxSubsequence(nums2, k - i);
*/
function genMaxSubsequence(nums, k) {
const len = nums.length
const stack = new Array(k).fill(0)
let top = -1
let remain = len - k
for (const num of nums) {
while (top >= 0 && stack[top] < num && remain > 0) {
top--
remain--
}
if (top < k - 1)
stack[++top] = num
else
remain--
}
return stack
}
/**
* 合并两个序列
* @param subsequence1
* @param subsequence2
* @returns
*/
/* Example usages of 'merge' are shown below:
merge(subsequence1, subsequence2);
*/
function merge(subsequence1, subsequence2) {
const l1 = subsequence1.length
const l2 = subsequence2.length
if (l1 === 0) return subsequence2
if (l2 === 0) return subsequence1
const len = l1 + l2
const merged = []
let idx1 = 0
let idx2 = 0
for (let i = 0; i < len; i++) {
if (compare(subsequence1, idx1, subsequence2, idx2))
merged[i] = subsequence1[idx1++]
else
merged[i] = subsequence2[idx2++]
}
return merged
}
/**
* 比较序列
* @param subsequence1
* @param idx1
* @param subsequence2
* @param idx2
* @returns
*/
/* Example usages of 'compare' are shown below:
compare(curMaxSubsequence, 0, maxSubsequence, 0);
compare(subsequence1, idx1, subsequence2, idx2);
*/
function compare(
subsequence1,
idx1,
subsequence2,
idx2,
) {
const l1 = subsequence1.length
const l2 = subsequence2.length
while (idx1 < l1 && idx2 < l2) {
// 如果当前两个元素不相等,判断第一个序列的元素是否大于第二个序列的元素
if (subsequence1[idx1] !== subsequence2[idx2])
return subsequence1[idx1] - subsequence2[idx2] > 0
idx1++
idx2++
}
// 如果所有匹配元素都一一相等,则判断第一个序列是否还有剩余长度
return l1 - idx1 > 0
}
}
|
3ba53ea2403522f5e103fa448a0aeb2b2f2017f8 | 4,881 | ts | TypeScript | components/_utils/numberUtil.ts | kdcloudone/table | 4ecdca64b01a684b3f2064afa0db0b0294669f09 | [
"BSD-3-Clause"
] | 2 | 2022-02-15T06:55:40.000Z | 2022-03-04T11:17:05.000Z | components/_utils/numberUtil.ts | kdcloudone/table | 4ecdca64b01a684b3f2064afa0db0b0294669f09 | [
"BSD-3-Clause"
] | 1 | 2022-03-10T07:35:49.000Z | 2022-03-10T07:35:49.000Z | components/_utils/numberUtil.ts | kdcloudone/table | 4ecdca64b01a684b3f2064afa0db0b0294669f09 | [
"BSD-3-Clause"
] | null | null | null | /**
* 使用定点表示法来格式化一个数
* @param {String|Number} number [必选,数字或者表示数字的字符串,范围为[0,20],超过范围则报错]
* @param {Number} digits [必选,小数点后数字的个数]
* @param {Boolean} isRound [可选,格式化时是否四舍五入,默认为false,即进行四舍五入,为false时直接截取,不满足位数的往后补0]
* @return {String} [结果]
*/
export function toFixed(number: string, digits: number, isRound = false): string {
// 非数字
// if (!/(^-\d+|^\d+)\.?\d*$/gi.test(number)) { // Number.isFinite(number)
// throw new Error('toFixed() number argument must be a valid number')
// }
if (Number.isNaN(Number(number))) {
throw new Error('toFixed() number argument must be a valid number')
}
// 是否为正数
const isPositive = +number >= 0
// 转化为字符串
number += ''
isRound = Boolean(isRound)
// 去掉正负号,统一按照正数来处理,最后再加上符号
number = number.replace(/^(?:-|\+)/gi, '')
// 小数点过大
if (digits > 20 || digits < 0) {
throw new RangeError('toFixed() digits argument must be between 0 and 20')
}
// 如果是简写如.11则整数位补0,变成0.11
if (/^\./gi.test(number)) {
number = '0' + number
}
const numParts = number.split('.')
let result = ''
// 在str后面加n个0
const _paddingZero = function (str: string, n: number): string {
for (let i = 0; i < n; i++) {
str += '0'
}
return str
}
// 在str后面加0,直至str的长度达到n
// 如果超过了n,则直接截取前n个字符串
const _paddingZeroTo = function (str: string, n: number): string {
if (str.length >= n) {
return str.substr(0, n)
} else {
return _paddingZero(str, n - str.length)
}
}
// 直接就是整数
if (numParts.length < 2) {
result = numParts[0] + '.' + _paddingZero('', digits)
} else {
// 为浮点数
// 如果为截取
if (isRound === false) {
result = numParts[0] + '.' + _paddingZeroTo(numParts[1], digits)
// 如果为四舍五入
} else {
// 放大10的N次方倍
let enlarge = numParts[0] + _paddingZeroTo(numParts[1], digits) + '.' + numParts[1].substr(digits)
// 取整
enlarge = Math.round(parseFloat(enlarge)) + ''
// 缩小10的N次方
while (enlarge.length <= digits) {
enlarge = '0' + enlarge
}
result = enlarge.substr(0, enlarge.length - digits) + '.' + enlarge.substr(enlarge.length - digits)
}
}
// 如果最后一位为.,则去除
result = result.replace(/\.$/gi, '').replace(/^\./gi, '0.')
// 加上正负数符号位
result = isPositive ? result : '-' + result
return result
}
/**
* 将已有的数字进行前面补零的方法
* @param {String|Number} number [需要在前面补零的数字]
* @param {Number} lenght [补零后的数字长度]
* 如:supplementZero(1, 4) return '0001'
*/
export function supplementZero(number: string, length = 2): string {
number += ''
if (number.length > length) return number
return (Array(length).join('0') + number).slice(-length)
}
/**
*
* 序列化字符串为数字,只取字符串中的数字、小数点、正负号
* @param {String} strNumber 字符串
*/
export function serialization(strNumber: string): string {
const numberList = strNumber.match(/\d|^-|\./g)
if (!numberList) return ''
// 取出正负号
const sign = numberList[0] === '-' ? '-' : ''
if (sign === '-') {
// 有负号, 去掉数组的负号
numberList.shift()
}
const numberString = numberList.join('')
// .replace('.', 'a').replace(/\./g, '').replace('a', '.')
const res = numberString.replace(/^0{2,}/gi, '0')
if (/^(0[^.])/gi.test(res)) {
return sign + res.slice(1)
}
return sign + res
}
// 根据整数精度和小数精度获取最大值
export function getMaxNumberByPrecision(integerPrecision: number, decimalPrecision: number): number {
const integerString = Array(integerPrecision)
.fill('9')
.reduce((res, value) => (res += value), '')
return decimalPrecision <= 0
? Number(integerString)
: Number(
Array(decimalPrecision)
.fill('9')
.reduce((res, value) => (res += value), integerString + '.'),
)
}
/**
* 判断是否为正则表达式
* @param {string|number} number 待判断的值
*/
export function isExp(number: string | number): boolean {
number = Number(number)
if (isNaN(number) || !isFinite(number)) return false
return /^(?!-0(\.0+)?(e|$))-?(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i.test(number.toString())
}
/**
* 将科学计数法显示的数字格式化为正常浮点数
* 1e-6 => 0.000006
* @param {Number} number 待格式化的科学计数法
* @returns num 格式化后的数值,如果不满足科学计数法的话,则原值返回
*/
export function exponentToFloat(number: string | number): string {
const tempNumber = Number(number)
if (isNaN(tempNumber) || !isFinite(tempNumber)) return number.toString()
const exponentReg = /^(?!-0(\.0+)?(e|$))-?(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i
if (exponentReg.test(tempNumber.toString())) {
// 获取精度, 默认 10
const lenArr = exponentReg.exec(tempNumber.toString())
const len = Number(lenArr && lenArr[6] ? lenArr[6] : 10)
const zeros = /^(\d{1,}(?:,\d{3})*\.(?:0*[1-9]+)?)(0*)?$/.exec(tempNumber.toFixed(len))
if (zeros) {
const res = zeros[1]
return res[res.length - 1] === '.' ? res.substr(0, res.length - 1) : res
} else {
return tempNumber.toFixed(len)
}
}
return tempNumber.toString()
}
| 28.54386 | 105 | 0.595575 | 100 | 10 | 0 | 18 | 18 | 0 | 3 | 0 | 22 | 0 | 0 | 9.9 | 1,789 | 0.015651 | 0.010061 | 0 | 0 | 0 | 0 | 0.478261 | 0.239692 | /**
* 使用定点表示法来格式化一个数
* @param {String|Number} number [必选,数字或者表示数字的字符串,范围为[0,20],超过范围则报错]
* @param {Number} digits [必选,小数点后数字的个数]
* @param {Boolean} isRound [可选,格式化时是否四舍五入,默认为false,即进行四舍五入,为false时直接截取,不满足位数的往后补0]
* @return {String} [结果]
*/
export /* Example usages of 'toFixed' are shown below:
/^(\d{1,}(?:,\d{3})*\.(?:0*[1-9]+)?)(0*)?$/.exec(tempNumber.toFixed(len));
tempNumber.toFixed(len);
*/
function toFixed(number, digits, isRound = false) {
// 非数字
// if (!/(^-\d+|^\d+)\.?\d*$/gi.test(number)) { // Number.isFinite(number)
// throw new Error('toFixed() number argument must be a valid number')
// }
if (Number.isNaN(Number(number))) {
throw new Error('toFixed() number argument must be a valid number')
}
// 是否为正数
const isPositive = +number >= 0
// 转化为字符串
number += ''
isRound = Boolean(isRound)
// 去掉正负号,统一按照正数来处理,最后再加上符号
number = number.replace(/^(?:-|\+)/gi, '')
// 小数点过大
if (digits > 20 || digits < 0) {
throw new RangeError('toFixed() digits argument must be between 0 and 20')
}
// 如果是简写如.11则整数位补0,变成0.11
if (/^\./gi.test(number)) {
number = '0' + number
}
const numParts = number.split('.')
let result = ''
// 在str后面加n个0
/* Example usages of '_paddingZero' are shown below:
_paddingZero(str, n - str.length);
result = numParts[0] + '.' + _paddingZero('', digits);
*/
const _paddingZero = function (str, n) {
for (let i = 0; i < n; i++) {
str += '0'
}
return str
}
// 在str后面加0,直至str的长度达到n
// 如果超过了n,则直接截取前n个字符串
/* Example usages of '_paddingZeroTo' are shown below:
result = numParts[0] + '.' + _paddingZeroTo(numParts[1], digits);
numParts[0] + _paddingZeroTo(numParts[1], digits) + '.' + numParts[1].substr(digits);
*/
const _paddingZeroTo = function (str, n) {
if (str.length >= n) {
return str.substr(0, n)
} else {
return _paddingZero(str, n - str.length)
}
}
// 直接就是整数
if (numParts.length < 2) {
result = numParts[0] + '.' + _paddingZero('', digits)
} else {
// 为浮点数
// 如果为截取
if (isRound === false) {
result = numParts[0] + '.' + _paddingZeroTo(numParts[1], digits)
// 如果为四舍五入
} else {
// 放大10的N次方倍
let enlarge = numParts[0] + _paddingZeroTo(numParts[1], digits) + '.' + numParts[1].substr(digits)
// 取整
enlarge = Math.round(parseFloat(enlarge)) + ''
// 缩小10的N次方
while (enlarge.length <= digits) {
enlarge = '0' + enlarge
}
result = enlarge.substr(0, enlarge.length - digits) + '.' + enlarge.substr(enlarge.length - digits)
}
}
// 如果最后一位为.,则去除
result = result.replace(/\.$/gi, '').replace(/^\./gi, '0.')
// 加上正负数符号位
result = isPositive ? result : '-' + result
return result
}
/**
* 将已有的数字进行前面补零的方法
* @param {String|Number} number [需要在前面补零的数字]
* @param {Number} lenght [补零后的数字长度]
* 如:supplementZero(1, 4) return '0001'
*/
export function supplementZero(number, length = 2) {
number += ''
if (number.length > length) return number
return (Array(length).join('0') + number).slice(-length)
}
/**
*
* 序列化字符串为数字,只取字符串中的数字、小数点、正负号
* @param {String} strNumber 字符串
*/
export function serialization(strNumber) {
const numberList = strNumber.match(/\d|^-|\./g)
if (!numberList) return ''
// 取出正负号
const sign = numberList[0] === '-' ? '-' : ''
if (sign === '-') {
// 有负号, 去掉数组的负号
numberList.shift()
}
const numberString = numberList.join('')
// .replace('.', 'a').replace(/\./g, '').replace('a', '.')
const res = numberString.replace(/^0{2,}/gi, '0')
if (/^(0[^.])/gi.test(res)) {
return sign + res.slice(1)
}
return sign + res
}
// 根据整数精度和小数精度获取最大值
export function getMaxNumberByPrecision(integerPrecision, decimalPrecision) {
const integerString = Array(integerPrecision)
.fill('9')
.reduce((res, value) => (res += value), '')
return decimalPrecision <= 0
? Number(integerString)
: Number(
Array(decimalPrecision)
.fill('9')
.reduce((res, value) => (res += value), integerString + '.'),
)
}
/**
* 判断是否为正则表达式
* @param {string|number} number 待判断的值
*/
export function isExp(number) {
number = Number(number)
if (isNaN(number) || !isFinite(number)) return false
return /^(?!-0(\.0+)?(e|$))-?(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i.test(number.toString())
}
/**
* 将科学计数法显示的数字格式化为正常浮点数
* 1e-6 => 0.000006
* @param {Number} number 待格式化的科学计数法
* @returns num 格式化后的数值,如果不满足科学计数法的话,则原值返回
*/
export function exponentToFloat(number) {
const tempNumber = Number(number)
if (isNaN(tempNumber) || !isFinite(tempNumber)) return number.toString()
const exponentReg = /^(?!-0(\.0+)?(e|$))-?(0|[1-9]\d*)(\.\d+)?(e-?(0|[1-9]\d*))?$/i
if (exponentReg.test(tempNumber.toString())) {
// 获取精度, 默认 10
const lenArr = exponentReg.exec(tempNumber.toString())
const len = Number(lenArr && lenArr[6] ? lenArr[6] : 10)
const zeros = /^(\d{1,}(?:,\d{3})*\.(?:0*[1-9]+)?)(0*)?$/.exec(tempNumber.toFixed(len))
if (zeros) {
const res = zeros[1]
return res[res.length - 1] === '.' ? res.substr(0, res.length - 1) : res
} else {
return tempNumber.toFixed(len)
}
}
return tempNumber.toString()
}
|
361d89bb4743deb2ef0a6d1cd847cd5a2c9cb7db | 7,003 | ts | TypeScript | scheme.wasm.ui/src/worker/messages.ts | PollRobots/scheme | b5ce0b8c9a21cac6f0acc6711426f251a0ff6f04 | [
"MIT"
] | 98 | 2022-01-02T21:19:39.000Z | 2022-03-30T00:21:11.000Z | scheme.wasm.ui/src/worker/messages.ts | PollRobots/scheme | b5ce0b8c9a21cac6f0acc6711426f251a0ff6f04 | [
"MIT"
] | 381 | 2022-01-02T21:18:48.000Z | 2022-03-21T01:17:46.000Z | scheme.wasm.ui/src/worker/messages.ts | PollRobots/scheme | b5ce0b8c9a21cac6f0acc6711426f251a0ff6f04 | [
"MIT"
] | 3 | 2022-01-04T00:22:41.000Z | 2022-03-05T13:50:18.000Z | export interface WorkerMessage {
type: string;
id: number;
}
export function isWorkerMessage(value: any): value is WorkerMessage {
return (
value && typeof value.type === "string" && typeof value.id === "number"
);
}
export interface StatusRequest extends WorkerMessage {
type: "status-req";
}
export function isStatusRequest(value: any): value is StatusRequest {
return isWorkerMessage(value) && value.type === "status-req";
}
export interface StatusResponse extends WorkerMessage {
type: "status-resp";
status: "stopped" | "waiting" | "running" | "partial";
memorySize: number;
debugging: boolean;
}
export function isStatusResponse(value: any): value is StatusResponse {
return (
value &&
value.type === "status-resp" &&
typeof value.id === "number" &&
typeof value.status === "string" &&
(value.status === "stopped" ||
value.status === "waiting" ||
value.status === "running" ||
value.status === "partial") &&
typeof value.memorySize === "number" &&
typeof value.debugging === "boolean"
);
}
export interface ErrorMessage extends WorkerMessage {
type: "error";
err: string;
}
export function isErrorMessage(value: any): value is ErrorMessage {
return value && value.type === "error" && typeof value.err === "string";
}
export interface OutputMessage extends WorkerMessage {
type: "output";
content: string;
}
export function isOutputMessage(value: any): value is OutputMessage {
return (
value &&
value.type === "output" &&
typeof value.id === "number" &&
typeof value.content === "string"
);
}
export interface InputMessage extends WorkerMessage {
type: "input";
content: string;
}
export function isInputMessage(value: any): value is InputMessage {
return (
value &&
value.type === "input" &&
typeof value.id === "number" &&
typeof value.content === "string"
);
}
export interface StartMessage extends WorkerMessage {
type: "start";
}
export function isStartMessage(value: any): value is StartMessage {
return isWorkerMessage(value) && value.type === "start";
}
export interface MemoryMessage extends WorkerMessage {
type: "memory";
memory: ArrayBuffer;
}
export interface StartedMessage extends WorkerMessage {
type: "started";
heap: number;
}
export function isStartedMessage(value: any): value is StartedMessage {
return value && value.type === "started" && typeof value.heap === "number";
}
export function isMemoryMessage(value: any): value is MemoryMessage {
return (
value &&
value.type === "memory" &&
typeof value.memory === "object" &&
value.memory instanceof ArrayBuffer
);
}
export interface PrintRequest extends WorkerMessage {
type: "print-req";
ptr: number;
}
export function isPrintRequest(value: any): value is PrintRequest {
return (
value &&
value.type === "print-req" &&
typeof value.id === "number" &&
typeof value.ptr === "number"
);
}
export interface PrintResponse extends WorkerMessage {
type: "print-resp";
content: string;
}
export function isPrintResponse(value: any): value is PrintResponse {
return (
value &&
value.type === "print-resp" &&
typeof value.id === "number" &&
typeof value.content === "string"
);
}
export interface HeapRequest extends WorkerMessage {
type: "heap-req";
ptr: number;
}
export function isHeapRequest(value: any): value is HeapRequest {
return value && value.type === "heap-req" && typeof value.ptr === "number";
}
export interface HeapResponse extends WorkerMessage {
type: "heap-resp";
ptr: number;
size: number;
free: number;
next: number;
entries: ArrayBuffer;
}
export function isHeapResponse(value: any): value is HeapResponse {
return (
value &&
value.type === "heap-resp" &&
typeof value.ptr === "number" &&
typeof value.size === "number" &&
typeof value.free === "number" &&
typeof value.next === "number" &&
typeof value.entries === "object" &&
value.entries instanceof ArrayBuffer
);
}
export interface GcRequest extends WorkerMessage {
type: "gc-req";
collect: boolean;
}
export function isGcRequest(value: any): value is GcRequest {
return (
value &&
typeof value.id === "number" &&
value.type === "gc-req" &&
typeof value.collect === "boolean"
);
}
export interface GcResponse extends WorkerMessage {
type: "gc-resp";
output: string;
isCollecting: boolean;
collectionCount: number;
collected: number;
notCollected: number;
totalCollected: number;
totalNotCollected: number;
}
export function isGcResponse(value: any): value is GcResponse {
return (
value &&
value.type == "gc-resp" &&
typeof value.id === "number" &&
typeof value.output === "string" &&
typeof value.collectionCount === "number" &&
typeof value.collected === "number" &&
typeof value.notCollected === "number" &&
typeof value.totalCollected === "number" &&
typeof value.totalNotCollected === "number"
);
}
export interface EnableDebug extends WorkerMessage {
type: "enable-debug";
enabled: boolean;
}
export function isEnableDebug(value: any): value is EnableDebug {
return (
value &&
value.type === "enable-debug" &&
typeof value.id === "number" &&
typeof value.enabled === "boolean"
);
}
export interface DebugBreak extends WorkerMessage {
type: "debug-break";
ptr: number;
env: number;
expr: string;
}
export function isDebugBreak(value: any): value is DebugBreak {
return (
value &&
value.type === "debug-break" &&
typeof value.id === "number" &&
typeof value.ptr === "number" &&
typeof value.env === "number" &&
typeof value.expr === "string"
);
}
export interface DebugStep extends WorkerMessage {
type: "debug-step";
resultStep: boolean;
}
export function isDebugStep(value: any): value is DebugStep {
return (
value &&
value.type === "debug-step" &&
typeof value.id === "number" &&
typeof value.resultStep === "boolean"
);
}
export interface EnvRequest extends WorkerMessage {
type: "env-req";
env: number;
}
export function isEnvRequest(value: any): value is EnvRequest {
return (
value &&
value.type === "env-req" &&
typeof value.id === "number" &&
typeof value.env === "number"
);
}
export interface EnvEntry {
name: string;
value: string;
}
export function isEnvEntry(value: any): value is EnvEntry {
return (
value && typeof value.name === "string" && typeof value.value === "string"
);
}
export interface EnvResponse extends WorkerMessage {
type: "env-resp";
ptr: number;
next: number;
entries: EnvEntry[];
}
export function isEnvResponse(value: any): value is EnvResponse {
return (
value &&
value.type === "env-resp" &&
typeof value.id === "number" &&
typeof value.ptr === "number" &&
typeof value.next === "number" &&
Array.isArray(value.entries) &&
(value.entries as any[]).every(isEnvEntry)
);
}
| 23.579125 | 78 | 0.65629 | 255 | 21 | 0 | 21 | 0 | 56 | 1 | 22 | 33 | 21 | 50 | 5.47619 | 1,868 | 0.022484 | 0 | 0.029979 | 0.011242 | 0.026767 | 0.22449 | 0.336735 | 0.232993 | export interface WorkerMessage {
type;
id;
}
export /* Example usages of 'isWorkerMessage' are shown below:
isWorkerMessage(value) && value.type === "status-req";
isWorkerMessage(value) && value.type === "start";
*/
function isWorkerMessage(value): value is WorkerMessage {
return (
value && typeof value.type === "string" && typeof value.id === "number"
);
}
export interface StatusRequest extends WorkerMessage {
type;
}
export function isStatusRequest(value): value is StatusRequest {
return isWorkerMessage(value) && value.type === "status-req";
}
export interface StatusResponse extends WorkerMessage {
type;
status;
memorySize;
debugging;
}
export function isStatusResponse(value): value is StatusResponse {
return (
value &&
value.type === "status-resp" &&
typeof value.id === "number" &&
typeof value.status === "string" &&
(value.status === "stopped" ||
value.status === "waiting" ||
value.status === "running" ||
value.status === "partial") &&
typeof value.memorySize === "number" &&
typeof value.debugging === "boolean"
);
}
export interface ErrorMessage extends WorkerMessage {
type;
err;
}
export function isErrorMessage(value): value is ErrorMessage {
return value && value.type === "error" && typeof value.err === "string";
}
export interface OutputMessage extends WorkerMessage {
type;
content;
}
export function isOutputMessage(value): value is OutputMessage {
return (
value &&
value.type === "output" &&
typeof value.id === "number" &&
typeof value.content === "string"
);
}
export interface InputMessage extends WorkerMessage {
type;
content;
}
export function isInputMessage(value): value is InputMessage {
return (
value &&
value.type === "input" &&
typeof value.id === "number" &&
typeof value.content === "string"
);
}
export interface StartMessage extends WorkerMessage {
type;
}
export function isStartMessage(value): value is StartMessage {
return isWorkerMessage(value) && value.type === "start";
}
export interface MemoryMessage extends WorkerMessage {
type;
memory;
}
export interface StartedMessage extends WorkerMessage {
type;
heap;
}
export function isStartedMessage(value): value is StartedMessage {
return value && value.type === "started" && typeof value.heap === "number";
}
export function isMemoryMessage(value): value is MemoryMessage {
return (
value &&
value.type === "memory" &&
typeof value.memory === "object" &&
value.memory instanceof ArrayBuffer
);
}
export interface PrintRequest extends WorkerMessage {
type;
ptr;
}
export function isPrintRequest(value): value is PrintRequest {
return (
value &&
value.type === "print-req" &&
typeof value.id === "number" &&
typeof value.ptr === "number"
);
}
export interface PrintResponse extends WorkerMessage {
type;
content;
}
export function isPrintResponse(value): value is PrintResponse {
return (
value &&
value.type === "print-resp" &&
typeof value.id === "number" &&
typeof value.content === "string"
);
}
export interface HeapRequest extends WorkerMessage {
type;
ptr;
}
export function isHeapRequest(value): value is HeapRequest {
return value && value.type === "heap-req" && typeof value.ptr === "number";
}
export interface HeapResponse extends WorkerMessage {
type;
ptr;
size;
free;
next;
entries;
}
export function isHeapResponse(value): value is HeapResponse {
return (
value &&
value.type === "heap-resp" &&
typeof value.ptr === "number" &&
typeof value.size === "number" &&
typeof value.free === "number" &&
typeof value.next === "number" &&
typeof value.entries === "object" &&
value.entries instanceof ArrayBuffer
);
}
export interface GcRequest extends WorkerMessage {
type;
collect;
}
export function isGcRequest(value): value is GcRequest {
return (
value &&
typeof value.id === "number" &&
value.type === "gc-req" &&
typeof value.collect === "boolean"
);
}
export interface GcResponse extends WorkerMessage {
type;
output;
isCollecting;
collectionCount;
collected;
notCollected;
totalCollected;
totalNotCollected;
}
export function isGcResponse(value): value is GcResponse {
return (
value &&
value.type == "gc-resp" &&
typeof value.id === "number" &&
typeof value.output === "string" &&
typeof value.collectionCount === "number" &&
typeof value.collected === "number" &&
typeof value.notCollected === "number" &&
typeof value.totalCollected === "number" &&
typeof value.totalNotCollected === "number"
);
}
export interface EnableDebug extends WorkerMessage {
type;
enabled;
}
export function isEnableDebug(value): value is EnableDebug {
return (
value &&
value.type === "enable-debug" &&
typeof value.id === "number" &&
typeof value.enabled === "boolean"
);
}
export interface DebugBreak extends WorkerMessage {
type;
ptr;
env;
expr;
}
export function isDebugBreak(value): value is DebugBreak {
return (
value &&
value.type === "debug-break" &&
typeof value.id === "number" &&
typeof value.ptr === "number" &&
typeof value.env === "number" &&
typeof value.expr === "string"
);
}
export interface DebugStep extends WorkerMessage {
type;
resultStep;
}
export function isDebugStep(value): value is DebugStep {
return (
value &&
value.type === "debug-step" &&
typeof value.id === "number" &&
typeof value.resultStep === "boolean"
);
}
export interface EnvRequest extends WorkerMessage {
type;
env;
}
export function isEnvRequest(value): value is EnvRequest {
return (
value &&
value.type === "env-req" &&
typeof value.id === "number" &&
typeof value.env === "number"
);
}
export interface EnvEntry {
name;
value;
}
export /* Example usages of 'isEnvEntry' are shown below:
value &&
value.type === "env-resp" &&
typeof value.id === "number" &&
typeof value.ptr === "number" &&
typeof value.next === "number" &&
Array.isArray(value.entries) &&
(value.entries as any[]).every(isEnvEntry);
*/
function isEnvEntry(value): value is EnvEntry {
return (
value && typeof value.name === "string" && typeof value.value === "string"
);
}
export interface EnvResponse extends WorkerMessage {
type;
ptr;
next;
entries;
}
export function isEnvResponse(value): value is EnvResponse {
return (
value &&
value.type === "env-resp" &&
typeof value.id === "number" &&
typeof value.ptr === "number" &&
typeof value.next === "number" &&
Array.isArray(value.entries) &&
(value.entries as any[]).every(isEnvEntry)
);
}
|
368c9ed9f5a063927a82043fbb475cd54531d039 | 2,474 | ts | TypeScript | packages/base/src/utils/time-range.ts | marco-miller/theia-trace-extension | 4f84289a0e0c3e77661d0475f5f437d5d5a5a09b | [
"MIT"
] | null | null | null | packages/base/src/utils/time-range.ts | marco-miller/theia-trace-extension | 4f84289a0e0c3e77661d0475f5f437d5d5a5a09b | [
"MIT"
] | 13 | 2022-03-23T18:36:04.000Z | 2022-03-31T19:59:26.000Z | packages/base/src/utils/time-range.ts | marco-miller/theia-trace-extension | 4f84289a0e0c3e77661d0475f5f437d5d5a5a09b | [
"MIT"
] | 1 | 2022-03-29T12:42:39.000Z | 2022-03-29T12:42:39.000Z | export interface TimeRangeString {
start: string;
end: string;
offset?: string;
}
export class TimeRange {
private start: bigint;
private end: bigint;
private offset: bigint | undefined;
/**
* Constructor.
* @param start Range start time
* @param end Range end time
* @param offset Time offset, if this is defined the start and end time should be relative to this value
*/
constructor(start: bigint, end: bigint, offset?: bigint);
/**
* Constructor.
* @param timeRangeString string object returned by this.toString()
*/
constructor(timeRangeString: TimeRangeString);
/**
* Constructor.
* Default TimeRange with 0 for values
*/
constructor();
constructor(a?: TimeRangeString | bigint, b?: bigint, c?: bigint) {
if (typeof a === 'bigint' && typeof b === 'bigint') {
this.start = a;
this.end = b;
this.offset = c;
} else if (typeof a === 'object') {
const timeRangeString: TimeRangeString = a;
const { start, end, offset } = timeRangeString;
this.start = BigInt(start);
this.end = BigInt(end);
this.offset = offset ? BigInt(offset) : undefined;
} else {
this.start = BigInt(0);
this.end = BigInt(0);
this.offset = undefined;
}
}
/**
* Get the range start time.
* If an offset is present the return value is start + offset.
*/
public getStart(): bigint {
if (this.offset !== undefined) {
return this.start + this.offset;
}
return this.start;
}
/**
* Get the range end time.
* If an offset is present the return value is end + offset.
*/
public getEnd(): bigint {
if (this.offset !== undefined) {
return this.end + this.offset;
}
return this.end;
}
/**
* Get range duration
*/
public getDuration(): bigint {
return this.end - this.start;
}
/**
* Return the time offset
*/
public getOffset(): bigint | undefined {
return this.offset;
}
/**
* Create a string object that can be JSON.stringified
*/
public toString(): TimeRangeString {
return {
start: this.start.toString(),
end: this.end.toString(),
offset: this.offset?.toString()
};
}
}
| 26.319149 | 108 | 0.546483 | 55 | 6 | 3 | 7 | 2 | 6 | 1 | 0 | 3 | 2 | 3 | 5 | 575 | 0.022609 | 0.003478 | 0.010435 | 0.003478 | 0.005217 | 0 | 0.125 | 0.23921 | export interface TimeRangeString {
start;
end;
offset?;
}
export class TimeRange {
private start;
private end;
private offset;
/**
* Constructor.
* @param start Range start time
* @param end Range end time
* @param offset Time offset, if this is defined the start and end time should be relative to this value
*/
constructor(start, end, offset?);
/**
* Constructor.
* @param timeRangeString string object returned by this.toString()
*/
constructor(timeRangeString);
/**
* Constructor.
* Default TimeRange with 0 for values
*/
constructor();
constructor(a?, b?, c?) {
if (typeof a === 'bigint' && typeof b === 'bigint') {
this.start = a;
this.end = b;
this.offset = c;
} else if (typeof a === 'object') {
const timeRangeString = a;
const { start, end, offset } = timeRangeString;
this.start = BigInt(start);
this.end = BigInt(end);
this.offset = offset ? BigInt(offset) : undefined;
} else {
this.start = BigInt(0);
this.end = BigInt(0);
this.offset = undefined;
}
}
/**
* Get the range start time.
* If an offset is present the return value is start + offset.
*/
public getStart() {
if (this.offset !== undefined) {
return this.start + this.offset;
}
return this.start;
}
/**
* Get the range end time.
* If an offset is present the return value is end + offset.
*/
public getEnd() {
if (this.offset !== undefined) {
return this.end + this.offset;
}
return this.end;
}
/**
* Get range duration
*/
public getDuration() {
return this.end - this.start;
}
/**
* Return the time offset
*/
public getOffset() {
return this.offset;
}
/**
* Create a string object that can be JSON.stringified
*/
public toString() {
return {
start: this.start.toString(),
end: this.end.toString(),
offset: this.offset?.toString()
};
}
}
|
36a5583ff1ebae98cc1f012e787900282c1af99b | 2,320 | ts | TypeScript | src/wasm-shell/shell-utils.ts | katharosada/wasm-terminal | d95bb287f9b1447208102b2da64aa8c68bddbc93 | [
"MIT"
] | 9 | 2022-01-14T11:48:09.000Z | 2022-01-28T20:45:02.000Z | src/wasm-shell/shell-utils.ts | katharosada/wasm-terminal | d95bb287f9b1447208102b2da64aa8c68bddbc93 | [
"MIT"
] | 1 | 2022-01-15T03:53:23.000Z | 2022-01-15T03:53:23.000Z | src/wasm-shell/shell-utils.ts | katharosada/wasm-terminal | d95bb287f9b1447208102b2da64aa8c68bddbc93 | [
"MIT"
] | null | null | null |
export interface ActiveCharPrompt {
promptPrefix: string;
promise: Promise<any>;
resolve?: (what: string) => any;
reject?: (error: Error) => any;
}
export interface ActivePrompt extends ActiveCharPrompt {
continuationPromptPrefix: string;
}
/**
* Detects all the word boundaries on the given input
*/
export function wordBoundaries(input: string, leftSide: boolean = true) {
let match;
const words = [];
const rx = /\w+/g;
match = rx.exec(input);
while (match) {
if (leftSide) {
words.push(match.index);
} else {
words.push(match.index + match[0].length);
}
match = rx.exec(input);
}
return words;
}
/**
* The closest left (or right) word boundary of the given input at the
* given offset.
*/
export function closestLeftBoundary(input: string, offset: number) {
const found = wordBoundaries(input, true)
.reverse()
.find((x) => x < offset);
return found === undefined ? 0 : found;
}
export function closestRightBoundary(input: string, offset: number) {
const found = wordBoundaries(input, false).find((x) => x > offset);
return found === undefined ? input.length : found;
}
/**
* Checks if there is an incomplete input
*
* An incomplete input is considered:
* - An input that contains unterminated single quotes
* - An input that contains unterminated double quotes
* - An input that ends with "\"
* - An input that has an incomplete boolean shell expression (&& and ||)
* - An incomplete pipe expression (|)
*/
export function isIncompleteInput(input: string) {
// Empty input is not incomplete
if (input.trim() === "") {
return false;
}
// Check for dangling single-quote strings
if ((input.match(/'/g) || []).length % 2 !== 0) {
return true;
}
// Check for dangling double-quote strings
if ((input.match(/"/g) || []).length % 2 !== 0) {
return true;
}
// Check for dangling boolean or pipe operations
if ((input.split(/(\|\||\||&&)/g).pop() as string).trim() === "") {
return true;
}
// Check for tailing slash
if (input.endsWith("\\") && !input.endsWith("\\\\")) {
return true;
}
return false;
}
/**
* Returns true if the expression ends on a tailing whitespace
*/
export function hasTrailingWhitespace(input: string) {
return input.match(/[^\\][ \t]$/m) !== null;
}
| 25.217391 | 73 | 0.643103 | 55 | 7 | 0 | 10 | 5 | 5 | 1 | 3 | 12 | 2 | 1 | 5.428571 | 639 | 0.026604 | 0.007825 | 0.007825 | 0.00313 | 0.001565 | 0.111111 | 0.444444 | 0.260582 |
export interface ActiveCharPrompt {
promptPrefix;
promise;
resolve?;
reject?;
}
export interface ActivePrompt extends ActiveCharPrompt {
continuationPromptPrefix;
}
/**
* Detects all the word boundaries on the given input
*/
export /* Example usages of 'wordBoundaries' are shown below:
wordBoundaries(input, true)
.reverse()
.find((x) => x < offset);
wordBoundaries(input, false).find((x) => x > offset);
*/
function wordBoundaries(input, leftSide = true) {
let match;
const words = [];
const rx = /\w+/g;
match = rx.exec(input);
while (match) {
if (leftSide) {
words.push(match.index);
} else {
words.push(match.index + match[0].length);
}
match = rx.exec(input);
}
return words;
}
/**
* The closest left (or right) word boundary of the given input at the
* given offset.
*/
export function closestLeftBoundary(input, offset) {
const found = wordBoundaries(input, true)
.reverse()
.find((x) => x < offset);
return found === undefined ? 0 : found;
}
export function closestRightBoundary(input, offset) {
const found = wordBoundaries(input, false).find((x) => x > offset);
return found === undefined ? input.length : found;
}
/**
* Checks if there is an incomplete input
*
* An incomplete input is considered:
* - An input that contains unterminated single quotes
* - An input that contains unterminated double quotes
* - An input that ends with "\"
* - An input that has an incomplete boolean shell expression (&& and ||)
* - An incomplete pipe expression (|)
*/
export function isIncompleteInput(input) {
// Empty input is not incomplete
if (input.trim() === "") {
return false;
}
// Check for dangling single-quote strings
if ((input.match(/'/g) || []).length % 2 !== 0) {
return true;
}
// Check for dangling double-quote strings
if ((input.match(/"/g) || []).length % 2 !== 0) {
return true;
}
// Check for dangling boolean or pipe operations
if ((input.split(/(\|\||\||&&)/g).pop() as string).trim() === "") {
return true;
}
// Check for tailing slash
if (input.endsWith("\\") && !input.endsWith("\\\\")) {
return true;
}
return false;
}
/**
* Returns true if the expression ends on a tailing whitespace
*/
export function hasTrailingWhitespace(input) {
return input.match(/[^\\][ \t]$/m) !== null;
}
|
371f8b80f4888b03cf971b38e5963f129483143b | 4,118 | ts | TypeScript | src/func/index.ts | comic-dev/node-caps | 9b3d2f1ffed0bd2238a1ab1cda62bdd2c70d7748 | [
"MIT"
] | 1 | 2022-03-20T23:48:57.000Z | 2022-03-20T23:48:57.000Z | src/func/index.ts | comic-dev/node-caps | 9b3d2f1ffed0bd2238a1ab1cda62bdd2c70d7748 | [
"MIT"
] | null | null | null | src/func/index.ts | comic-dev/node-caps | 9b3d2f1ffed0bd2238a1ab1cda62bdd2c70d7748 | [
"MIT"
] | null | null | null | export default {
def: (str: string) => {
if (!str || typeof str !== "string")
throw new TypeError(
`Parameter str must be typeof String, recieved type "${typeof str}"`
);
const first = str.search(/[a-zA-Z]/);
return (
str.slice(0, first) +
str.slice(first, first + 1).toUpperCase() +
str.slice(first + 1).toLowerCase()
);
},
keep: (str: string): string => {
if (!str || typeof str !== "string")
throw new TypeError(
`Parameter str must be typeof String, recieved type ${typeof str}`
);
const first = str.search(/[a-zA-Z]/);
return (
str.slice(0, first) +
str.slice(first, first + 1).toUpperCase() +
str.slice(first + 1)
);
},
all: (str: string): string => {
if (!str || typeof str !== "string")
throw new TypeError(
`Parameter str must be typeof String, recieved type "${typeof str}"`
);
return str
.split(" ")
.map((s) => {
const first = s.search(/[a-zA-Z]/);
return (
s.slice(0, first) +
s.slice(first, first + 1).toUpperCase() +
s.slice(first + 1)
);
})
.join(" ");
},
array: (str: string[]): string[] => {
if (!str || (typeof str[0] !== "string" && str.length > 1))
throw new TypeError(
`Parameter str must be typeof Array, recieved type "${typeof str}"`
);
try {
return str.map((s) => {
const first = s.search(/[a-zA-Z]/);
return (
s.slice(0, first) +
s.slice(first, first + 1).toUpperCase() +
s.slice(first + 1)
);
});
} catch (err) {
let error = new TypeError(
`Parameter str must be typeof Array, recieved type ${typeof str}`
);
throw error;
}
},
sent: (str: string): string => {
if (!str || typeof str !== "string")
throw new TypeError(
`Parameter str must be typeof String, recieved type "${typeof str}"`
);
return str
.split(".")
.map((s) => {
const first = s.search(/[a-zA-Z]/);
return (
s.slice(0, first) +
s.slice(first, first + 1).toUpperCase() +
s.slice(first + 1)
);
})
.join(".");
},
dash: (str: string): string => {
if (!str || typeof str !== "string")
throw new TypeError(
`Parameter str must be typeof String, recieved type "${typeof str}"`
);
return str
.split("-")
.map((s) => {
const first = s.search(/[a-zA-Z]/);
return (
s.slice(0, first) +
s.slice(first, first + 1).toUpperCase() +
s.slice(first + 1)
);
})
.join(".");
},
reg: (str: string): string => {
if (str.match(/-/) && str.split("-")[1].length < 3)
return str
.split("-")
.map((s, i) => {
const first = s.search(/[a-zA-Z]/);
if (i > 0) return s.toUpperCase();
else
return s.slice(first, first + 1).toUpperCase() + s.slice(first + 1);
})
.join("-");
return str
.split(" ")
.map((s) => {
const first = s.search(/[a-zA-Z]/);
return (
s.slice(0, first) +
s.slice(first, first + 1).toUpperCase() +
s.slice(first + 1)
);
})
.join(" ");
},
perms: (str: string[]): string[] => {
return str.map((v) => {
if (!v || typeof v !== "string")
throw new TypeError(
`Parameter str must be typeof String, recieved type "${typeof str}"`
);
if (v.includes("_")) {
return v
.split(/_/g)
.map((s) => {
return s.charAt(0) + s.slice(1).toLowerCase();
})
.join(" ");
} else {
return v.charAt(0) + v.slice(1).toLowerCase();
}
});
},
} as {
def(str: string): string;
keep(str: string): string;
all(str: string): string;
array(str: string[]): string[];
sent(str: string): string;
dash(str: string): string;
reg(str: string): string;
perms(str: string[]): string[];
};
| 27.637584 | 80 | 0.476445 | 148 | 16 | 8 | 25 | 9 | 0 | 0 | 0 | 31 | 0 | 16 | 10.625 | 1,161 | 0.035314 | 0.007752 | 0 | 0 | 0.013781 | 0 | 0.534483 | 0.275261 | export default {
def: (str) => {
if (!str || typeof str !== "string")
throw new TypeError(
`Parameter str must be typeof String, recieved type "${typeof str}"`
);
const first = str.search(/[a-zA-Z]/);
return (
str.slice(0, first) +
str.slice(first, first + 1).toUpperCase() +
str.slice(first + 1).toLowerCase()
);
},
keep: (str) => {
if (!str || typeof str !== "string")
throw new TypeError(
`Parameter str must be typeof String, recieved type ${typeof str}`
);
const first = str.search(/[a-zA-Z]/);
return (
str.slice(0, first) +
str.slice(first, first + 1).toUpperCase() +
str.slice(first + 1)
);
},
all: (str) => {
if (!str || typeof str !== "string")
throw new TypeError(
`Parameter str must be typeof String, recieved type "${typeof str}"`
);
return str
.split(" ")
.map((s) => {
const first = s.search(/[a-zA-Z]/);
return (
s.slice(0, first) +
s.slice(first, first + 1).toUpperCase() +
s.slice(first + 1)
);
})
.join(" ");
},
array: (str) => {
if (!str || (typeof str[0] !== "string" && str.length > 1))
throw new TypeError(
`Parameter str must be typeof Array, recieved type "${typeof str}"`
);
try {
return str.map((s) => {
const first = s.search(/[a-zA-Z]/);
return (
s.slice(0, first) +
s.slice(first, first + 1).toUpperCase() +
s.slice(first + 1)
);
});
} catch (err) {
let error = new TypeError(
`Parameter str must be typeof Array, recieved type ${typeof str}`
);
throw error;
}
},
sent: (str) => {
if (!str || typeof str !== "string")
throw new TypeError(
`Parameter str must be typeof String, recieved type "${typeof str}"`
);
return str
.split(".")
.map((s) => {
const first = s.search(/[a-zA-Z]/);
return (
s.slice(0, first) +
s.slice(first, first + 1).toUpperCase() +
s.slice(first + 1)
);
})
.join(".");
},
dash: (str) => {
if (!str || typeof str !== "string")
throw new TypeError(
`Parameter str must be typeof String, recieved type "${typeof str}"`
);
return str
.split("-")
.map((s) => {
const first = s.search(/[a-zA-Z]/);
return (
s.slice(0, first) +
s.slice(first, first + 1).toUpperCase() +
s.slice(first + 1)
);
})
.join(".");
},
reg: (str) => {
if (str.match(/-/) && str.split("-")[1].length < 3)
return str
.split("-")
.map((s, i) => {
const first = s.search(/[a-zA-Z]/);
if (i > 0) return s.toUpperCase();
else
return s.slice(first, first + 1).toUpperCase() + s.slice(first + 1);
})
.join("-");
return str
.split(" ")
.map((s) => {
const first = s.search(/[a-zA-Z]/);
return (
s.slice(0, first) +
s.slice(first, first + 1).toUpperCase() +
s.slice(first + 1)
);
})
.join(" ");
},
perms: (str) => {
return str.map((v) => {
if (!v || typeof v !== "string")
throw new TypeError(
`Parameter str must be typeof String, recieved type "${typeof str}"`
);
if (v.includes("_")) {
return v
.split(/_/g)
.map((s) => {
return s.charAt(0) + s.slice(1).toLowerCase();
})
.join(" ");
} else {
return v.charAt(0) + v.slice(1).toLowerCase();
}
});
},
} as {
def(str);
keep(str);
all(str);
array(str);
sent(str);
dash(str);
reg(str);
perms(str);
};
|
379e95e59422554b810520bfadcc80273dbbede4 | 1,378 | ts | TypeScript | diskreet-blockchain/ts/notifications/getStatus.ts | woflydev/general-projects | 4ab637fabd2b8ff563ec1637eccefed780bce163 | [
"MIT"
] | 1 | 2022-03-13T22:46:43.000Z | 2022-03-13T22:46:43.000Z | diskreet-blockchain/ts/notifications/getStatus.ts | woflydev/general-projects | 4ab637fabd2b8ff563ec1637eccefed780bce163 | [
"MIT"
] | null | null | null | diskreet-blockchain/ts/notifications/getStatus.ts | woflydev/general-projects | 4ab637fabd2b8ff563ec1637eccefed780bce163 | [
"MIT"
] | null | null | null | interface Environment {
isAppFocused: boolean;
isAudioNotificationEnabled: boolean;
isAudioNotificationSupported: boolean;
isEnabled: boolean;
numNotifications: number;
userSetting: UserSetting;
}
interface Status {
shouldClearNotifications: boolean;
shouldPlayNotificationSound: boolean;
shouldShowNotifications: boolean;
type: Type;
}
export type UserSetting = 'off' | 'count' | 'name' | 'message';
type Type = 'ok' | 'disabled' | 'appIsFocused' | 'noNotifications' | 'userSetting';
export const getStatus = ({
isAppFocused,
isAudioNotificationEnabled,
isAudioNotificationSupported,
isEnabled,
numNotifications,
userSetting,
}: Environment): Status => {
const type = ((): Type => {
if (!isEnabled) {
return 'disabled';
}
const hasNotifications = numNotifications > 0;
if (!hasNotifications) {
return 'noNotifications';
}
if (isAppFocused) {
return 'appIsFocused';
}
if (userSetting === 'off') {
return 'userSetting';
}
return 'ok';
})();
const shouldPlayNotificationSound = isAudioNotificationSupported && isAudioNotificationEnabled;
const shouldShowNotifications = type === 'ok';
const shouldClearNotifications = type === 'appIsFocused';
return {
shouldClearNotifications,
shouldPlayNotificationSound,
shouldShowNotifications,
type,
};
};
| 22.590164 | 97 | 0.694485 | 50 | 2 | 0 | 1 | 6 | 10 | 0 | 0 | 8 | 4 | 0 | 19.5 | 330 | 0.009091 | 0.018182 | 0.030303 | 0.012121 | 0 | 0 | 0.421053 | 0.269788 | interface Environment {
isAppFocused;
isAudioNotificationEnabled;
isAudioNotificationSupported;
isEnabled;
numNotifications;
userSetting;
}
interface Status {
shouldClearNotifications;
shouldPlayNotificationSound;
shouldShowNotifications;
type;
}
export type UserSetting = 'off' | 'count' | 'name' | 'message';
type Type = 'ok' | 'disabled' | 'appIsFocused' | 'noNotifications' | 'userSetting';
export const getStatus = ({
isAppFocused,
isAudioNotificationEnabled,
isAudioNotificationSupported,
isEnabled,
numNotifications,
userSetting,
}) => {
const type = (() => {
if (!isEnabled) {
return 'disabled';
}
const hasNotifications = numNotifications > 0;
if (!hasNotifications) {
return 'noNotifications';
}
if (isAppFocused) {
return 'appIsFocused';
}
if (userSetting === 'off') {
return 'userSetting';
}
return 'ok';
})();
const shouldPlayNotificationSound = isAudioNotificationSupported && isAudioNotificationEnabled;
const shouldShowNotifications = type === 'ok';
const shouldClearNotifications = type === 'appIsFocused';
return {
shouldClearNotifications,
shouldPlayNotificationSound,
shouldShowNotifications,
type,
};
};
|
37b9eef0d5b8aeb92f34c21c0067af8292e6cd8b | 1,474 | ts | TypeScript | backend/types.ts | Angstboksen/Discordle | 1a3abd0cd16a31146cbdd89de3de4188d4de4248 | [
"MIT"
] | 2 | 2022-02-16T23:04:48.000Z | 2022-02-18T00:18:30.000Z | backend/types.ts | Angstboksen/Discordle | 1a3abd0cd16a31146cbdd89de3de4188d4de4248 | [
"MIT"
] | 5 | 2022-03-06T14:45:09.000Z | 2022-03-06T14:45:12.000Z | backend/types.ts | Angstboksen/Discordle | 1a3abd0cd16a31146cbdd89de3de4188d4de4248 | [
"MIT"
] | null | null | null | export enum MongoTables {
WORDS = "words",
GAMES = "games",
USERS = "users",
RANKS = "ranks"
}
export type ResponseMessage = {
endpoint: string;
status: number;
message: string;
size: number;
data: any;
};
export type LetterObject = {
body: string;
color: LetterBoxColor;
priority: number;
};
export type User = {
_id: string,
username: string,
discord: string,
rank: number,
hasUnfinishedGame: boolean,
}
export type Game = {
user: string,
type: GameType,
solution: string,
board: string[],
isFinished: boolean,
date: Date;
leaderboard?: string[]
_id?: string;
}
export enum LetterBoxColor {
WRONG = "#696969",
INCORRECT_POSITION = "#FFD700",
CORRECT = "#228B22",
DEFAULT = "#FFFFE0"
}
export enum GameType {
INDIVIDUAL = "Individual",
OPEN = "Open"
}
const responseMessages = new Map();
responseMessages.set(200, "200 OK");
responseMessages.set(201, "201 Created");
responseMessages.set(204, "204 No Content");
responseMessages.set(400, "400 Bad Request");
responseMessages.set(401, "401 Unauthorized");
responseMessages.set(403, "403 Forbidden");
responseMessages.set(404, "404 Not Found");
responseMessages.set(500, "500 Internal Server Error");
export const message = (
endpoint: string,
status: number,
data: any
): ResponseMessage => {
return {
endpoint,
status,
message: responseMessages.get(status),
size: data ? data.length : 0,
data,
};
}; | 19.653333 | 55 | 0.663501 | 67 | 1 | 0 | 3 | 2 | 21 | 0 | 2 | 19 | 4 | 0 | 7 | 474 | 0.008439 | 0.004219 | 0.044304 | 0.008439 | 0 | 0.074074 | 0.703704 | 0.215088 | export enum MongoTables {
WORDS = "words",
GAMES = "games",
USERS = "users",
RANKS = "ranks"
}
export type ResponseMessage = {
endpoint;
status;
message;
size;
data;
};
export type LetterObject = {
body;
color;
priority;
};
export type User = {
_id,
username,
discord,
rank,
hasUnfinishedGame,
}
export type Game = {
user,
type,
solution,
board,
isFinished,
date;
leaderboard?
_id?;
}
export enum LetterBoxColor {
WRONG = "#696969",
INCORRECT_POSITION = "#FFD700",
CORRECT = "#228B22",
DEFAULT = "#FFFFE0"
}
export enum GameType {
INDIVIDUAL = "Individual",
OPEN = "Open"
}
const responseMessages = new Map();
responseMessages.set(200, "200 OK");
responseMessages.set(201, "201 Created");
responseMessages.set(204, "204 No Content");
responseMessages.set(400, "400 Bad Request");
responseMessages.set(401, "401 Unauthorized");
responseMessages.set(403, "403 Forbidden");
responseMessages.set(404, "404 Not Found");
responseMessages.set(500, "500 Internal Server Error");
export /* Example usages of 'message' are shown below:
;
*/
const message = (
endpoint,
status,
data
) => {
return {
endpoint,
status,
message: responseMessages.get(status),
size: data ? data.length : 0,
data,
};
}; |
37e2f15983f908beafcbed8c020e7cdce57e11d3 | 8,399 | ts | TypeScript | src/Player.ts | kari0003/poker-player-allwin | b50774cfc171a3e6917d55c537799c0a3a67719f | [
"MIT"
] | null | null | null | src/Player.ts | kari0003/poker-player-allwin | b50774cfc171a3e6917d55c537799c0a3a67719f | [
"MIT"
] | 1 | 2022-03-25T22:48:23.000Z | 2022-03-25T22:48:23.000Z | src/Player.ts | kari0003/poker-player-allwin | b50774cfc171a3e6917d55c537799c0a3a67719f | [
"MIT"
] | null | null | null | export class Player {
public betRequest(gameState: any, betCallback: (bet: number) => void): void {
const myPlayer = gameState.players[gameState.in_action];
const bet = myPlayer ? myPlayer["bet"] : 0;
const raise = this.calculateRaise(gameState);
if (gameState.round === 0 && gameState.bet_index === 0) {
let begin = raise;
const blind = gameState.small_blind || gameState.big_blind;
if (raise < blind) {
begin = blind;
}
betCallback(begin);
} else if (raise < 0) {
betCallback(0);
} else {
betCallback(gameState.current_buy_in - bet + raise);
}
}
public showdown(gameState: any): void {}
public calculateRaise(gameState: any): number {
const minRaise = gameState.minimum_raise;
const myPlayer = gameState.players[gameState.in_action];
const myBet = this.calculateBet(myPlayer, gameState);
if (minRaise && myBet > 0 && minRaise > myBet) {
return minRaise;
} else {
return myBet;
}
}
private calculateBet(myPlayer: any, gameState: any): number {
const communityCards = gameState["community_cards"] || [];
const communityCardsValues: number[] = communityCards.map(this.cardToValue);
const communityCardsValue = communityCardsValues.reduce(
(val, curr) => val + curr,
0
);
const communityCardsDiff = communityCardsValues.reduce(
(val, curr) => val - curr,
0
);
const myCards = myPlayer["hole_cards"] || [];
const myCardsValue = myCards.map(this.cardToValue);
const allCards = this.orderCards([
...communityCardsValues,
...myCardsValue
]);
const tableCards = this.orderCards(communityCardsValues);
const value = this.cardToValue(myCards[0]) + this.cardToValue(myCards[1]);
const diff = Math.abs(
this.cardToValue(myCards[0]) - this.cardToValue(myCards[1])
);
const allValue = value + communityCardsValue;
const alldiff = Math.abs(diff - communityCardsDiff);
if (this.detectFullHouse(allCards) && !this.detectFullHouse(tableCards)) {
return myPlayer.stack;
}
if (this.detectPoker(allCards) && !this.detectPoker(tableCards)) {
return myPlayer.stack;
} else if (this.detectFlush([...communityCards, ...myCards])) {
return 50;
} else if (
this.detectNumberSeries(allCards) &&
!this.detectNumberSeries(tableCards)
) {
return 30;
} else if (this.detectDrill(allCards) && !this.detectDrill(tableCards)) {
return 30;
} else if (this.detectTwoPairs(allCards)) {
if (value < 24 && this.tooHighBet(gameState, myPlayer)) {
return -1;
}
if (diff === 0) {
if (value >= 18 && gameState.minimum_raise <= myPlayer.stack) {
return 30;
} else {
return 0;
}
} else {
return 30;
}
} else if (diff === 0) {
if (
allCards.length === 2 &&
value < 24 &&
this.tooHighBet(gameState, myPlayer)
) {
return -1;
}
if (
value >= 18 &&
gameState.minimum_raise <= myPlayer.stack &&
allCards.length < 7
) {
return 1;
} else {
return 0;
}
} else if (value > 25 && gameState.pot <= myPlayer.stack && !this.tooHighBet(gameState, myPlayer)) {
return 0;
} else {
return -1;
}
}
private tooHighBet(gameState: any, myPlayer: any): boolean {
return (
gameState.minimum_raise > myPlayer.stack / 2 ||
gameState.minimum_raise > 50 ||
gameState.pot > 1500
);
}
private shouldFold(
bets: number[],
allCards: number[],
tableCards: number[],
communityCards: number[],
myCards: number[],
myStack: number
): boolean {
const maxBet = Math.max(...bets);
if (
maxBet > (myStack / 3) * 2 &&
!(this.detectFullHouse(allCards) && !this.detectFullHouse(tableCards)) &&
!(this.detectPoker(allCards) && !this.detectPoker(tableCards)) &&
!this.detectFlush([...communityCards, ...myCards])
) {
return true;
}
return false;
}
private bleoff(gameState: any): boolean {
const player = gameState.players.find(p => p.name === "player");
if (gameState.round === 3 && player.status === "player") {
if (Math.random() < 0.6) {
return true;
}
}
return false;
}
private handleAllIn(
players: any,
bets: number[],
limit: number,
allCards: number[],
tableCards: number[],
community_cards: number[],
myCards: number[]
): boolean {
const player = players.find(p => p.name === "player");
const maxBet = Math.max(...bets);
if (
player.status === "active" &&
maxBet > limit &&
!this.hasGoodStuff(allCards, tableCards, community_cards, myCards)
) {
return false;
}
return true;
}
private hasGoodStuff(
allCards: number[],
tableCards: number[],
communityCards: number[],
myCards: number[]
) {
if (
(this.detectFullHouse(allCards) && !this.detectFullHouse(tableCards)) ||
(this.detectPoker(allCards) && !this.detectPoker(tableCards)) ||
this.detectFlush([...communityCards, ...myCards])
) {
return true;
}
return false;
}
private cardToValue(card: any): number {
switch (card.rank) {
case "A":
return 20;
case "K":
return 15;
case "Q":
return 14;
case "J":
return 12;
default:
return parseInt(card.rank, 10);
}
}
private detectTwoPairs(cards: number[]): boolean {
const mapping = {};
cards.forEach(card => {
mapping[card] = mapping[card] ? mapping[card] + 1 : 1;
});
let found = 0;
for (var x in mapping) {
if (mapping[x] >= 2) {
found++;
}
}
return found >= 2;
}
private detectDrill(cards: number[]): boolean {
const mapping = {};
cards.forEach(card => {
mapping[card] = mapping[card] ? mapping[card] + 1 : 1;
});
let found = false;
for (var x in mapping) {
if (mapping[x] >= 3) {
found = true;
}
}
return found;
}
private detectFullHouse(cards: number[]): boolean {
let double = false;
let triple = false;
let tripleValue = 0;
cards.forEach((card, index) => {
if (cards[index + 1] && card === cards[index + 1]) {
if (!tripleValue && cards[index + 2] && cards[index + 2] == card) {
tripleValue = card;
triple = true;
} else if (card !== tripleValue) {
double = true;
}
}
});
return double && triple;
}
private detectPoker(cards: number[]): boolean {
cards.forEach((card, index) => {
if (
cards[index + 1] &&
cards[index + 2] &&
cards[index + 3] &&
card === cards[index + 1] &&
card === cards[index + 2] &&
card === cards[index + 3]
) {
return true;
}
});
return false;
}
private detectNumberSeries(cards: number[]): boolean {
let hasSeries = false;
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
const unique = cards.filter(onlyUnique);
unique.forEach((card, index) => {
if (
cards[index + 1] &&
cards[index + 2] &&
cards[index + 3] &&
cards[index + 4]
) {
if (
card === cards[index + 1] - 1 &&
card === cards[index + 2] - 2 &&
card === cards[index + 3] - 3 &&
card === cards[index + 4] - 4
) {
hasSeries = true;
}
}
});
return hasSeries;
}
private detectFlush(cardsWithSuite = []) {
const cards = this.orderCards(cardsWithSuite.map(this.cardSuit));
const mapping = {};
cards.forEach(card => {
mapping[card] = mapping[card] ? mapping[card] + 1 : 1;
});
let found = false;
for (var x in mapping) {
if (mapping[x] >= 5) {
found = true;
}
}
return found;
}
private cardSuit(card: any): number {
switch (card.suit) {
case "spades":
return 0;
case "hearts":
return 1;
case "diamonds":
return 2;
case "clubs":
return 3;
}
}
private orderCards(cards = []) {
return cards.sort((a, b) => a - b);
}
}
export default Player;
| 26.003096 | 104 | 0.557447 | 300 | 30 | 0 | 55 | 36 | 0 | 12 | 11 | 39 | 1 | 0 | 9.466667 | 2,370 | 0.035865 | 0.01519 | 0 | 0.000422 | 0 | 0.090909 | 0.322314 | 0.305507 | export class Player {
public betRequest(gameState, betCallback) {
const myPlayer = gameState.players[gameState.in_action];
const bet = myPlayer ? myPlayer["bet"] : 0;
const raise = this.calculateRaise(gameState);
if (gameState.round === 0 && gameState.bet_index === 0) {
let begin = raise;
const blind = gameState.small_blind || gameState.big_blind;
if (raise < blind) {
begin = blind;
}
betCallback(begin);
} else if (raise < 0) {
betCallback(0);
} else {
betCallback(gameState.current_buy_in - bet + raise);
}
}
public showdown(gameState) {}
public calculateRaise(gameState) {
const minRaise = gameState.minimum_raise;
const myPlayer = gameState.players[gameState.in_action];
const myBet = this.calculateBet(myPlayer, gameState);
if (minRaise && myBet > 0 && minRaise > myBet) {
return minRaise;
} else {
return myBet;
}
}
private calculateBet(myPlayer, gameState) {
const communityCards = gameState["community_cards"] || [];
const communityCardsValues = communityCards.map(this.cardToValue);
const communityCardsValue = communityCardsValues.reduce(
(val, curr) => val + curr,
0
);
const communityCardsDiff = communityCardsValues.reduce(
(val, curr) => val - curr,
0
);
const myCards = myPlayer["hole_cards"] || [];
const myCardsValue = myCards.map(this.cardToValue);
const allCards = this.orderCards([
...communityCardsValues,
...myCardsValue
]);
const tableCards = this.orderCards(communityCardsValues);
const value = this.cardToValue(myCards[0]) + this.cardToValue(myCards[1]);
const diff = Math.abs(
this.cardToValue(myCards[0]) - this.cardToValue(myCards[1])
);
const allValue = value + communityCardsValue;
const alldiff = Math.abs(diff - communityCardsDiff);
if (this.detectFullHouse(allCards) && !this.detectFullHouse(tableCards)) {
return myPlayer.stack;
}
if (this.detectPoker(allCards) && !this.detectPoker(tableCards)) {
return myPlayer.stack;
} else if (this.detectFlush([...communityCards, ...myCards])) {
return 50;
} else if (
this.detectNumberSeries(allCards) &&
!this.detectNumberSeries(tableCards)
) {
return 30;
} else if (this.detectDrill(allCards) && !this.detectDrill(tableCards)) {
return 30;
} else if (this.detectTwoPairs(allCards)) {
if (value < 24 && this.tooHighBet(gameState, myPlayer)) {
return -1;
}
if (diff === 0) {
if (value >= 18 && gameState.minimum_raise <= myPlayer.stack) {
return 30;
} else {
return 0;
}
} else {
return 30;
}
} else if (diff === 0) {
if (
allCards.length === 2 &&
value < 24 &&
this.tooHighBet(gameState, myPlayer)
) {
return -1;
}
if (
value >= 18 &&
gameState.minimum_raise <= myPlayer.stack &&
allCards.length < 7
) {
return 1;
} else {
return 0;
}
} else if (value > 25 && gameState.pot <= myPlayer.stack && !this.tooHighBet(gameState, myPlayer)) {
return 0;
} else {
return -1;
}
}
private tooHighBet(gameState, myPlayer) {
return (
gameState.minimum_raise > myPlayer.stack / 2 ||
gameState.minimum_raise > 50 ||
gameState.pot > 1500
);
}
private shouldFold(
bets,
allCards,
tableCards,
communityCards,
myCards,
myStack
) {
const maxBet = Math.max(...bets);
if (
maxBet > (myStack / 3) * 2 &&
!(this.detectFullHouse(allCards) && !this.detectFullHouse(tableCards)) &&
!(this.detectPoker(allCards) && !this.detectPoker(tableCards)) &&
!this.detectFlush([...communityCards, ...myCards])
) {
return true;
}
return false;
}
private bleoff(gameState) {
const player = gameState.players.find(p => p.name === "player");
if (gameState.round === 3 && player.status === "player") {
if (Math.random() < 0.6) {
return true;
}
}
return false;
}
private handleAllIn(
players,
bets,
limit,
allCards,
tableCards,
community_cards,
myCards
) {
const player = players.find(p => p.name === "player");
const maxBet = Math.max(...bets);
if (
player.status === "active" &&
maxBet > limit &&
!this.hasGoodStuff(allCards, tableCards, community_cards, myCards)
) {
return false;
}
return true;
}
private hasGoodStuff(
allCards,
tableCards,
communityCards,
myCards
) {
if (
(this.detectFullHouse(allCards) && !this.detectFullHouse(tableCards)) ||
(this.detectPoker(allCards) && !this.detectPoker(tableCards)) ||
this.detectFlush([...communityCards, ...myCards])
) {
return true;
}
return false;
}
private cardToValue(card) {
switch (card.rank) {
case "A":
return 20;
case "K":
return 15;
case "Q":
return 14;
case "J":
return 12;
default:
return parseInt(card.rank, 10);
}
}
private detectTwoPairs(cards) {
const mapping = {};
cards.forEach(card => {
mapping[card] = mapping[card] ? mapping[card] + 1 : 1;
});
let found = 0;
for (var x in mapping) {
if (mapping[x] >= 2) {
found++;
}
}
return found >= 2;
}
private detectDrill(cards) {
const mapping = {};
cards.forEach(card => {
mapping[card] = mapping[card] ? mapping[card] + 1 : 1;
});
let found = false;
for (var x in mapping) {
if (mapping[x] >= 3) {
found = true;
}
}
return found;
}
private detectFullHouse(cards) {
let double = false;
let triple = false;
let tripleValue = 0;
cards.forEach((card, index) => {
if (cards[index + 1] && card === cards[index + 1]) {
if (!tripleValue && cards[index + 2] && cards[index + 2] == card) {
tripleValue = card;
triple = true;
} else if (card !== tripleValue) {
double = true;
}
}
});
return double && triple;
}
private detectPoker(cards) {
cards.forEach((card, index) => {
if (
cards[index + 1] &&
cards[index + 2] &&
cards[index + 3] &&
card === cards[index + 1] &&
card === cards[index + 2] &&
card === cards[index + 3]
) {
return true;
}
});
return false;
}
private detectNumberSeries(cards) {
let hasSeries = false;
/* Example usages of 'onlyUnique' are shown below:
cards.filter(onlyUnique);
*/
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
const unique = cards.filter(onlyUnique);
unique.forEach((card, index) => {
if (
cards[index + 1] &&
cards[index + 2] &&
cards[index + 3] &&
cards[index + 4]
) {
if (
card === cards[index + 1] - 1 &&
card === cards[index + 2] - 2 &&
card === cards[index + 3] - 3 &&
card === cards[index + 4] - 4
) {
hasSeries = true;
}
}
});
return hasSeries;
}
private detectFlush(cardsWithSuite = []) {
const cards = this.orderCards(cardsWithSuite.map(this.cardSuit));
const mapping = {};
cards.forEach(card => {
mapping[card] = mapping[card] ? mapping[card] + 1 : 1;
});
let found = false;
for (var x in mapping) {
if (mapping[x] >= 5) {
found = true;
}
}
return found;
}
private cardSuit(card) {
switch (card.suit) {
case "spades":
return 0;
case "hearts":
return 1;
case "diamonds":
return 2;
case "clubs":
return 3;
}
}
private orderCards(cards = []) {
return cards.sort((a, b) => a - b);
}
}
export default Player;
|
2f516f8ce46385d35483cc20af39f1c2bfb17dc1 | 1,977 | ts | TypeScript | src/Error.ts | Kenneth-hv/typeparse | f0d8ad2050df19231b7c823b378d5949ae6ab118 | [
"MIT"
] | 1 | 2022-03-29T20:05:35.000Z | 2022-03-29T20:05:35.000Z | src/Error.ts | Kenneth-hv/typeparse | f0d8ad2050df19231b7c823b378d5949ae6ab118 | [
"MIT"
] | null | null | null | src/Error.ts | Kenneth-hv/typeparse | f0d8ad2050df19231b7c823b378d5949ae6ab118 | [
"MIT"
] | null | null | null | /*---------------------------------------------------------------------------------------------
* Copyright (c) Kenneth Herrera. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export type ExpectedType =
| "string"
| "number"
| "bigint"
| "boolean"
| "symbol"
| "undefined"
| "object"
| "function"
| "array"
| "unknown";
export enum TypeParseErrorCode {
NOT_FOUND = "NOT_FOUND",
INVALID_TYPE = "INVALID_TYPE",
UNABLE_TO_PARSE = "UNABLE_TO_PARSE",
}
export interface TypeParseErrorDetails {
expectedType?: ExpectedType;
typeFound?: unknown;
key?: string | string[];
customError?: string;
}
export function typeOf(value: unknown): ExpectedType {
if (Array.isArray(value)) return "array";
return typeof value;
}
export class TypeParseError implements Error {
public readonly code: TypeParseErrorCode;
public readonly name: string;
public readonly message: string;
public constructor(parameters: TypeParseErrorDetails) {
const { expectedType, key, typeFound } = {
...parameters,
typeFound: typeOf(parameters.typeFound),
};
this.name = "TypeParse exception";
if (expectedType === "unknown") {
this.code = TypeParseErrorCode.UNABLE_TO_PARSE;
this.message = `${parameters.customError}`;
} else if (typeFound === "undefined") {
this.code = TypeParseErrorCode.NOT_FOUND;
if (key) {
this.message = `Unable to find a valid [${expectedType}] value at [${key}]`;
} else {
this.message = `Invalid type, expected [${expectedType}] but found [${typeFound}]`;
}
} else {
this.code = TypeParseErrorCode.UNABLE_TO_PARSE;
this.message = `Unable to convert [${typeFound}] to [${expectedType}]`;
}
}
public toString() {
return `TypeParse error: ${this.message}`;
}
}
| 29.507463 | 96 | 0.599899 | 55 | 3 | 0 | 2 | 1 | 7 | 1 | 0 | 7 | 3 | 1 | 7.333333 | 481 | 0.010395 | 0.002079 | 0.014553 | 0.006237 | 0.002079 | 0 | 0.538462 | 0.210452 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Kenneth Herrera. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export type ExpectedType =
| "string"
| "number"
| "bigint"
| "boolean"
| "symbol"
| "undefined"
| "object"
| "function"
| "array"
| "unknown";
export enum TypeParseErrorCode {
NOT_FOUND = "NOT_FOUND",
INVALID_TYPE = "INVALID_TYPE",
UNABLE_TO_PARSE = "UNABLE_TO_PARSE",
}
export interface TypeParseErrorDetails {
expectedType?;
typeFound?;
key?;
customError?;
}
export /* Example usages of 'typeOf' are shown below:
typeOf(parameters.typeFound);
*/
function typeOf(value) {
if (Array.isArray(value)) return "array";
return typeof value;
}
export class TypeParseError implements Error {
public readonly code;
public readonly name;
public readonly message;
public constructor(parameters) {
const { expectedType, key, typeFound } = {
...parameters,
typeFound: typeOf(parameters.typeFound),
};
this.name = "TypeParse exception";
if (expectedType === "unknown") {
this.code = TypeParseErrorCode.UNABLE_TO_PARSE;
this.message = `${parameters.customError}`;
} else if (typeFound === "undefined") {
this.code = TypeParseErrorCode.NOT_FOUND;
if (key) {
this.message = `Unable to find a valid [${expectedType}] value at [${key}]`;
} else {
this.message = `Invalid type, expected [${expectedType}] but found [${typeFound}]`;
}
} else {
this.code = TypeParseErrorCode.UNABLE_TO_PARSE;
this.message = `Unable to convert [${typeFound}] to [${expectedType}]`;
}
}
public toString() {
return `TypeParse error: ${this.message}`;
}
}
|
2fad14f5a85451ec532b2a5c940e6b057eb82307 | 2,560 | ts | TypeScript | src/Plugins/BuiltIn/Components/v1Compat.ts | bridge-core/dash-compiler | e1080da7528c2caa4a39004ce5d70acce0546733 | [
"MIT"
] | 2 | 2022-01-02T16:03:06.000Z | 2022-01-10T19:25:09.000Z | src/Plugins/BuiltIn/Components/v1Compat.ts | bridge-core/dash-compiler | e1080da7528c2caa4a39004ce5d70acce0546733 | [
"MIT"
] | null | null | null | src/Plugins/BuiltIn/Components/v1Compat.ts | bridge-core/dash-compiler | e1080da7528c2caa4a39004ce5d70acce0546733 | [
"MIT"
] | 2 | 2022-01-20T17:07:24.000Z | 2022-02-13T20:01:04.000Z | /**
* A module that emulates bridge. v1's custom component environment
*/
export const v1Compat = (module: any, fileType: string) => ({
register: (componentClass: any) => {
if ((componentClass.type ?? 'entity') !== fileType) return
module.exports = ({ name, schema, template }: any) => {
const component = new componentClass()
name(componentClass.component_name)
schema(
transformV1AutoCompletions(
// v1 custom component auto-completions are always prefixed with the component name.
// That is no longer the case for v2's component auto-completions so we can strip the name here
Object.values(component.onPropose())[0]
)
)
template((componentArgs: any, { create }: any) => {
// - Default location for a v2 create(...) call is already inside of the top-level wrapper object (e.g. 'minecraft:entity')
// - v1 components used to wrap the return object inside of 'minecraft:entity'/'minecraft:block'
// >>> Strip 'minecraft:entity'/'minecraft:block' from onApply(...) return object
create(
component.onApply(componentArgs, 'components')[
`minecraft:${fileType}`
]
)
})
}
},
})
function transformV1AutoCompletions(completions: any): any {
const v2Completions: any = {}
// v1 array schema compatibility
const keys = Object.keys(completions)
if (keys.length === 1 && keys[0].startsWith('$dynamic.list.')) {
return {
type: 'array',
items: transformV1AutoCompletions(Object.values(completions)[0]),
}
}
// v1 object property compatibility
for (const [propertyName, value] of Object.entries(completions)) {
// Skip special properties like '$dynamic_template'/'$versioned_template'
if (propertyName.startsWith('$')) continue
if (typeof value === 'string')
v2Completions[propertyName] = transformV1Value(value)
else if (Array.isArray(value))
v2Completions[propertyName] = { enum: value }
else if (value === 'object')
v2Completions[propertyName] = transformV1AutoCompletions(value)
}
return { type: 'object', properties: v2Completions }
}
/**
* Takes a v1 string auto-completion reference like "$general.boolean"
* and transforms it to a standard JSON schema
*/
function transformV1Value(value: string) {
switch (value) {
case '$general.boolean':
return { type: 'boolean' }
case '$general.number':
return { type: 'integer' }
case '$general.decimal':
return { type: 'number' }
default:
return {
type: [
'number',
'integer',
'string',
'boolean',
'object',
'array',
],
}
}
}
| 29.425287 | 127 | 0.669922 | 62 | 6 | 0 | 8 | 4 | 0 | 2 | 8 | 2 | 0 | 1 | 15.666667 | 735 | 0.019048 | 0.005442 | 0 | 0 | 0.001361 | 0.444444 | 0.111111 | 0.225515 | /**
* A module that emulates bridge. v1's custom component environment
*/
export const v1Compat = (module, fileType) => ({
register: (componentClass) => {
if ((componentClass.type ?? 'entity') !== fileType) return
module.exports = ({ name, schema, template }) => {
const component = new componentClass()
name(componentClass.component_name)
schema(
transformV1AutoCompletions(
// v1 custom component auto-completions are always prefixed with the component name.
// That is no longer the case for v2's component auto-completions so we can strip the name here
Object.values(component.onPropose())[0]
)
)
template((componentArgs, { create }) => {
// - Default location for a v2 create(...) call is already inside of the top-level wrapper object (e.g. 'minecraft:entity')
// - v1 components used to wrap the return object inside of 'minecraft:entity'/'minecraft:block'
// >>> Strip 'minecraft:entity'/'minecraft:block' from onApply(...) return object
create(
component.onApply(componentArgs, 'components')[
`minecraft:${fileType}`
]
)
})
}
},
})
/* Example usages of 'transformV1AutoCompletions' are shown below:
schema(transformV1AutoCompletions(
// v1 custom component auto-completions are always prefixed with the component name.
// That is no longer the case for v2's component auto-completions so we can strip the name here
Object.values(component.onPropose())[0]));
transformV1AutoCompletions(Object.values(completions)[0]);
v2Completions[propertyName] = transformV1AutoCompletions(value);
*/
function transformV1AutoCompletions(completions) {
const v2Completions = {}
// v1 array schema compatibility
const keys = Object.keys(completions)
if (keys.length === 1 && keys[0].startsWith('$dynamic.list.')) {
return {
type: 'array',
items: transformV1AutoCompletions(Object.values(completions)[0]),
}
}
// v1 object property compatibility
for (const [propertyName, value] of Object.entries(completions)) {
// Skip special properties like '$dynamic_template'/'$versioned_template'
if (propertyName.startsWith('$')) continue
if (typeof value === 'string')
v2Completions[propertyName] = transformV1Value(value)
else if (Array.isArray(value))
v2Completions[propertyName] = { enum: value }
else if (value === 'object')
v2Completions[propertyName] = transformV1AutoCompletions(value)
}
return { type: 'object', properties: v2Completions }
}
/**
* Takes a v1 string auto-completion reference like "$general.boolean"
* and transforms it to a standard JSON schema
*/
/* Example usages of 'transformV1Value' are shown below:
v2Completions[propertyName] = transformV1Value(value);
*/
function transformV1Value(value) {
switch (value) {
case '$general.boolean':
return { type: 'boolean' }
case '$general.number':
return { type: 'integer' }
case '$general.decimal':
return { type: 'number' }
default:
return {
type: [
'number',
'integer',
'string',
'boolean',
'object',
'array',
],
}
}
}
|
2ff3f27e2b4402ee1ffda4a023b4018d1cfe18bc | 2,242 | ts | TypeScript | src/utils/files/parsers/parserPMD.ts | I194/PMTools_2.0 | 313dea61275c5f8b875376578a65e08b9c2fd128 | [
"MIT"
] | null | null | null | src/utils/files/parsers/parserPMD.ts | I194/PMTools_2.0 | 313dea61275c5f8b875376578a65e08b9c2fd128 | [
"MIT"
] | 1 | 2022-03-17T12:50:14.000Z | 2022-03-17T12:51:57.000Z | src/utils/files/parsers/parserPMD.ts | I194/PMTools_2.0 | 313dea61275c5f8b875376578a65e08b9c2fd128 | [
"MIT"
] | null | null | null | const parsePMD = (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) and the first one (it's empty)
const lines = data.split(eol).slice(1).filter(line => line.length > 1);
const headLine = lines[0]; // line with specimen name and orientation params - metadata in other words
const metadata = {
name: name, // inner pmd name lay here: headLine.slice(0, 10).trim(),
a: +headLine.slice(12, 20).trim(),
b: +headLine.slice(22, 30).trim(),
s: +headLine.slice(32, 40).trim(),
d: +headLine.slice(42, 50).trim(),
v: +headLine.slice(52, headLine.length).trim().toLowerCase().split('m')[0],
}
const steps = lines.slice(2).map((line, index) => {
// 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 = line.slice(0, 4).trim();
const x = +line.slice(4, 14).trim();
const y = +line.slice(14, 24).trim();
const z = +line.slice(24, 34).trim();
const mag = +line.slice(34, 44).trim();
const Dgeo = +line.slice(44, 50).trim();
const Igeo = +line.slice(50, 56).trim();
const Dstrat = +line.slice(56, 62).trim();
const Istrat = +line.slice(62, 68).trim();
const a95 = +line.slice(68, 74).trim();
const comment = line.slice(74, line.length).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: "PMD",
created: new Date().toISOString(),
};
}
export default parsePMD; | 31.138889 | 104 | 0.589206 | 54 | 3 | 0 | 5 | 21 | 0 | 0 | 0 | 2 | 0 | 0 | 28 | 771 | 0.010376 | 0.027237 | 0 | 0 | 0 | 0 | 0.068966 | 0.283318 | /* Example usages of 'parsePMD' are shown below:
;
*/
const parsePMD = (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) and the first one (it's empty)
const lines = data.split(eol).slice(1).filter(line => line.length > 1);
const headLine = lines[0]; // line with specimen name and orientation params - metadata in other words
const metadata = {
name: name, // inner pmd name lay here: headLine.slice(0, 10).trim(),
a: +headLine.slice(12, 20).trim(),
b: +headLine.slice(22, 30).trim(),
s: +headLine.slice(32, 40).trim(),
d: +headLine.slice(42, 50).trim(),
v: +headLine.slice(52, headLine.length).trim().toLowerCase().split('m')[0],
}
const steps = lines.slice(2).map((line, index) => {
// 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 = line.slice(0, 4).trim();
const x = +line.slice(4, 14).trim();
const y = +line.slice(14, 24).trim();
const z = +line.slice(24, 34).trim();
const mag = +line.slice(34, 44).trim();
const Dgeo = +line.slice(44, 50).trim();
const Igeo = +line.slice(50, 56).trim();
const Dstrat = +line.slice(56, 62).trim();
const Istrat = +line.slice(62, 68).trim();
const a95 = +line.slice(68, 74).trim();
const comment = line.slice(74, line.length).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: "PMD",
created: new Date().toISOString(),
};
}
export default parsePMD; |
2ff7a6cfe05f2b2bec050f0a31283c4f99483f30 | 2,687 | ts | TypeScript | src/structures/CursorPage.ts | guidojw/core | 47ac72d750e8675a685e734d0e404288888640b5 | [
"MIT"
] | 1 | 2022-02-28T02:36:24.000Z | 2022-02-28T02:36:24.000Z | src/structures/CursorPage.ts | guidojw/core | 47ac72d750e8675a685e734d0e404288888640b5 | [
"MIT"
] | 1 | 2022-01-22T15:20:28.000Z | 2022-01-22T15:20:28.000Z | src/structures/CursorPage.ts | guidojw/core | 47ac72d750e8675a685e734d0e404288888640b5 | [
"MIT"
] | 1 | 2022-02-27T14:59:17.000Z | 2022-02-27T14:59:17.000Z | export type CursorPageOptions = {
readonly limit?: 10 | 25 | 50 | 100;
cursor?: string;
readonly sortOrder?: "Asc" | "Desc";
};
type CursorPageResponse<T> = {
data: T[];
previousPageCursor: string | null;
nextPageCursor: string | null;
};
type CursorPageState = {
previous: string | null;
current: string | null;
next: string | null;
};
type CursorPageMethod<T, C> = (
options: CursorPageOptions & C
) => Promise<CursorPageResponse<T>>;
export class CursorPage<T, C> {
options: CursorPageOptions;
cursors: CursorPageState;
data: T[][] = [];
readonly method: CursorPageMethod<T, C>;
readonly methodOptions: C;
private currentPage = 0;
constructor(
options: CursorPageOptions,
methodOptions: C,
response: CursorPageResponse<T>,
method: CursorPageMethod<T, C>
) {
this.options = options;
this.cursors = {
previous: response.previousPageCursor,
current: response.nextPageCursor,
next: response.nextPageCursor
};
this.data[0] = response.data;
this.methodOptions = methodOptions;
this.method = method;
}
async getNextPage(): Promise<T[]> {
if (!this.cursors.next) {
throw new Error(
"Attempted to iterate to next page, but no cursor was presented for the next page"
);
}
this.currentPage++;
if (this.data[this.currentPage]) return this.data[this.currentPage];
this.options.cursor = this.cursors.next;
const result = await this.method({
...this.options,
...this.methodOptions
});
this.cursors = {
previous: result.previousPageCursor,
current: this.cursors.next,
next: result.nextPageCursor
};
this.data[this.currentPage] = result.data;
return result.data;
}
async getPreviousPage(): Promise<T[]> {
if (!this.cursors.previous) {
throw new Error(
"Attempted to iterate to previous page, but no cursor was presented for the next page"
);
}
this.currentPage--;
if (this.data[this.currentPage]) return this.data[this.currentPage];
this.options.cursor = this.cursors.previous;
const result = await this.method({
...this.options,
...this.methodOptions
});
this.cursors = {
previous: result.previousPageCursor,
current: this.cursors.next,
next: result.nextPageCursor
};
this.data[this.currentPage] = result.data;
return result.data;
}
getCurrentPage(): T[] {
return this.data[this.currentPage];
}
}
export function contextCall<T, C>(
context: any,
method: CursorPageMethod<T, C>
): CursorPageMethod<T, C> {
return (options: CursorPageOptions & C) => method.call(context, options);
}
| 25.11215 | 94 | 0.653517 | 93 | 6 | 0 | 7 | 2 | 15 | 0 | 1 | 6 | 5 | 0 | 8.333333 | 724 | 0.017956 | 0.002762 | 0.020718 | 0.006906 | 0 | 0.033333 | 0.2 | 0.231431 | export type CursorPageOptions = {
readonly limit?;
cursor?;
readonly sortOrder?;
};
type CursorPageResponse<T> = {
data;
previousPageCursor;
nextPageCursor;
};
type CursorPageState = {
previous;
current;
next;
};
type CursorPageMethod<T, C> = (
options
) => Promise<CursorPageResponse<T>>;
export class CursorPage<T, C> {
options;
cursors;
data = [];
readonly method;
readonly methodOptions;
private currentPage = 0;
constructor(
options,
methodOptions,
response,
method
) {
this.options = options;
this.cursors = {
previous: response.previousPageCursor,
current: response.nextPageCursor,
next: response.nextPageCursor
};
this.data[0] = response.data;
this.methodOptions = methodOptions;
this.method = method;
}
async getNextPage() {
if (!this.cursors.next) {
throw new Error(
"Attempted to iterate to next page, but no cursor was presented for the next page"
);
}
this.currentPage++;
if (this.data[this.currentPage]) return this.data[this.currentPage];
this.options.cursor = this.cursors.next;
const result = await this.method({
...this.options,
...this.methodOptions
});
this.cursors = {
previous: result.previousPageCursor,
current: this.cursors.next,
next: result.nextPageCursor
};
this.data[this.currentPage] = result.data;
return result.data;
}
async getPreviousPage() {
if (!this.cursors.previous) {
throw new Error(
"Attempted to iterate to previous page, but no cursor was presented for the next page"
);
}
this.currentPage--;
if (this.data[this.currentPage]) return this.data[this.currentPage];
this.options.cursor = this.cursors.previous;
const result = await this.method({
...this.options,
...this.methodOptions
});
this.cursors = {
previous: result.previousPageCursor,
current: this.cursors.next,
next: result.nextPageCursor
};
this.data[this.currentPage] = result.data;
return result.data;
}
getCurrentPage() {
return this.data[this.currentPage];
}
}
export function contextCall<T, C>(
context,
method
) {
return (options) => method.call(context, options);
}
|
2ffda3a2912233347c04fede23a63ee7d46f464a | 1,708 | ts | TypeScript | src/utils/debug-namespace-matcher.ts | warerwang/stalk-opentracing-js | c465ad88f7acce3bde50e72fad4921acdd6116b2 | [
"MIT"
] | null | null | null | src/utils/debug-namespace-matcher.ts | warerwang/stalk-opentracing-js | c465ad88f7acce3bde50e72fad4921acdd6116b2 | [
"MIT"
] | null | null | null | src/utils/debug-namespace-matcher.ts | warerwang/stalk-opentracing-js | c465ad88f7acce3bde50e72fad4921acdd6116b2 | [
"MIT"
] | 1 | 2022-01-24T12:38:14.000Z | 2022-01-24T12:38:14.000Z |
/**
* Stolen from:
* https://github.com/visionmedia/debug/blob/master/src/common.js
*/
export class DebugNamespaceMatcher {
private _matchQuery: string;
private _regexes: {
names: RegExp[],
skips: RegExp[]
};
constructor(matchQuery: string) {
this.updateQuery(matchQuery);
}
updateQuery(matchQuery: string) {
this._matchQuery = matchQuery;
this.setupRegexes();
}
private setupRegexes() {
this._regexes = { names: [], skips: [] };
let i;
const split = (typeof this._matchQuery === 'string' ? this._matchQuery : '').split(/[\s,]+/);
const len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
// ignore empty strings
continue;
}
const namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
this._regexes.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
this._regexes.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
test(name: string) {
if (name[name.length - 1] === '*') {
return true;
}
let i;
let len;
for (i = 0, len = this._regexes.skips.length; i < len; i++) {
if (this._regexes.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = this._regexes.names.length; i < len; i++) {
if (this._regexes.names[i].test(name)) {
return true;
}
}
return false;
}
}
export default DebugNamespaceMatcher;
| 22.473684 | 101 | 0.478923 | 50 | 4 | 0 | 3 | 6 | 2 | 3 | 0 | 4 | 1 | 1 | 8.5 | 447 | 0.01566 | 0.013423 | 0.004474 | 0.002237 | 0.002237 | 0 | 0.266667 | 0.254236 |
/**
* Stolen from:
* https://github.com/visionmedia/debug/blob/master/src/common.js
*/
export class DebugNamespaceMatcher {
private _matchQuery;
private _regexes;
constructor(matchQuery) {
this.updateQuery(matchQuery);
}
updateQuery(matchQuery) {
this._matchQuery = matchQuery;
this.setupRegexes();
}
private setupRegexes() {
this._regexes = { names: [], skips: [] };
let i;
const split = (typeof this._matchQuery === 'string' ? this._matchQuery : '').split(/[\s,]+/);
const len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
// ignore empty strings
continue;
}
const namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
this._regexes.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
} else {
this._regexes.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
test(name) {
if (name[name.length - 1] === '*') {
return true;
}
let i;
let len;
for (i = 0, len = this._regexes.skips.length; i < len; i++) {
if (this._regexes.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = this._regexes.names.length; i < len; i++) {
if (this._regexes.names[i].test(name)) {
return true;
}
}
return false;
}
}
export default DebugNamespaceMatcher;
|
b52d90f0836e6909b76a6c1f1093c6a2b1f2117e | 3,225 | ts | TypeScript | packages/eip712/src/messages/staking.ts | tharsis/evmosjs | d1de2e0ad2ca43a2fb3cd6e9a2079eeef3f1b6b7 | [
"Apache-2.0"
] | 11 | 2022-03-02T22:16:26.000Z | 2022-03-25T14:15:06.000Z | packages/eip712/src/messages/staking.ts | tharsis/evmosjs | d1de2e0ad2ca43a2fb3cd6e9a2079eeef3f1b6b7 | [
"Apache-2.0"
] | 5 | 2022-03-04T13:55:17.000Z | 2022-03-25T17:43:13.000Z | packages/eip712/src/messages/staking.ts | tharsis/evmosjs | d1de2e0ad2ca43a2fb3cd6e9a2079eeef3f1b6b7 | [
"Apache-2.0"
] | 4 | 2022-03-08T23:36:42.000Z | 2022-03-24T12:05:47.000Z | export const MSG_DELEGATE_TYPES = {
MsgValue: [
{ name: 'delegator_address', type: 'string' },
{ name: 'validator_address', type: 'string' },
{ name: 'amount', type: 'TypeAmount' },
],
TypeAmount: [
{ name: 'denom', type: 'string' },
{ name: 'amount', type: 'string' },
],
}
export function createMsgDelegate(
delegatorAddress: string,
validatorAddress: string,
amount: string,
denom: string,
) {
return {
type: 'cosmos-sdk/MsgDelegate',
value: {
amount: {
amount,
denom,
},
delegator_address: delegatorAddress,
validator_address: validatorAddress,
},
}
}
export const MSG_BEGIN_REDELEGATE_TYPES = {
MsgValue: [
{ name: 'delegator_address', type: 'string' },
{ name: 'validator_src_address', type: 'string' },
{ name: 'validator_dst_address', type: 'string' },
{ name: 'amount', type: 'TypeAmount' },
],
TypeAmount: [
{ name: 'denom', type: 'string' },
{ name: 'amount', type: 'string' },
],
}
export function createMsgBeginRedelegate(
delegatorAddress: string,
validatorSrcAddress: string,
validatorDstAddress: string,
amount: string,
denom: string,
) {
return {
type: 'cosmos-sdk/MsgBeginRedelegate',
value: {
amount: {
amount,
denom,
},
delegator_address: delegatorAddress,
validator_src_address: validatorSrcAddress,
validator_dst_address: validatorDstAddress,
},
}
}
export const MSG_UNDELEGATE_TYPES = {
MsgValue: [
{ name: 'delegator_address', type: 'string' },
{ name: 'validator_address', type: 'string' },
{ name: 'amount', type: 'TypeAmount' },
],
TypeAmount: [
{ name: 'denom', type: 'string' },
{ name: 'amount', type: 'string' },
],
}
export function createMsgUndelegate(
delegatorAddress: string,
validatorAddress: string,
amount: string,
denom: string,
) {
return {
type: 'cosmos-sdk/MsgUndelegate',
value: {
amount: {
amount,
denom,
},
delegator_address: delegatorAddress,
validator_address: validatorAddress,
},
}
}
export const MSG_WITHDRAW_DELEGATOR_REWARD_TYPES = {
MsgValue: [
{ name: 'delegator_address', type: 'string' },
{ name: 'validator_address', type: 'string' },
],
}
/* eslint-disable camelcase */
export interface MsgWithdrawDelegatorRewardInterface {
type: string
value: {
delegator_address: string
validator_address: string
}
}
export function createMsgWithdrawDelegatorReward(
delegatorAddress: string,
validatorAddress: string,
) {
return {
type: 'cosmos-sdk/MsgWithdrawDelegationReward',
value: {
delegator_address: delegatorAddress,
validator_address: validatorAddress,
},
}
}
export const MSG_WITHDRAW_VALIDATOR_COMMISSION_TYPES = {
MsgValue: [{ name: 'validator_address', type: 'string' }],
}
export interface MsgWithdrawValidatorCommissionInterface {
type: string
value: {
validator_address: string
}
}
export function createMsgWithdrawValidatorCommission(validatorAddress: string) {
return {
type: 'cosmos-sdk/MsgWithdrawValidatorCommission',
value: {
validator_address: validatorAddress,
},
}
}
| 22.87234 | 80 | 0.651783 | 132 | 5 | 0 | 16 | 5 | 4 | 0 | 0 | 21 | 2 | 0 | 9.4 | 888 | 0.023649 | 0.005631 | 0.004505 | 0.002252 | 0 | 0 | 0.7 | 0.246514 | export const MSG_DELEGATE_TYPES = {
MsgValue: [
{ name: 'delegator_address', type: 'string' },
{ name: 'validator_address', type: 'string' },
{ name: 'amount', type: 'TypeAmount' },
],
TypeAmount: [
{ name: 'denom', type: 'string' },
{ name: 'amount', type: 'string' },
],
}
export function createMsgDelegate(
delegatorAddress,
validatorAddress,
amount,
denom,
) {
return {
type: 'cosmos-sdk/MsgDelegate',
value: {
amount: {
amount,
denom,
},
delegator_address: delegatorAddress,
validator_address: validatorAddress,
},
}
}
export const MSG_BEGIN_REDELEGATE_TYPES = {
MsgValue: [
{ name: 'delegator_address', type: 'string' },
{ name: 'validator_src_address', type: 'string' },
{ name: 'validator_dst_address', type: 'string' },
{ name: 'amount', type: 'TypeAmount' },
],
TypeAmount: [
{ name: 'denom', type: 'string' },
{ name: 'amount', type: 'string' },
],
}
export function createMsgBeginRedelegate(
delegatorAddress,
validatorSrcAddress,
validatorDstAddress,
amount,
denom,
) {
return {
type: 'cosmos-sdk/MsgBeginRedelegate',
value: {
amount: {
amount,
denom,
},
delegator_address: delegatorAddress,
validator_src_address: validatorSrcAddress,
validator_dst_address: validatorDstAddress,
},
}
}
export const MSG_UNDELEGATE_TYPES = {
MsgValue: [
{ name: 'delegator_address', type: 'string' },
{ name: 'validator_address', type: 'string' },
{ name: 'amount', type: 'TypeAmount' },
],
TypeAmount: [
{ name: 'denom', type: 'string' },
{ name: 'amount', type: 'string' },
],
}
export function createMsgUndelegate(
delegatorAddress,
validatorAddress,
amount,
denom,
) {
return {
type: 'cosmos-sdk/MsgUndelegate',
value: {
amount: {
amount,
denom,
},
delegator_address: delegatorAddress,
validator_address: validatorAddress,
},
}
}
export const MSG_WITHDRAW_DELEGATOR_REWARD_TYPES = {
MsgValue: [
{ name: 'delegator_address', type: 'string' },
{ name: 'validator_address', type: 'string' },
],
}
/* eslint-disable camelcase */
export interface MsgWithdrawDelegatorRewardInterface {
type
value
}
export function createMsgWithdrawDelegatorReward(
delegatorAddress,
validatorAddress,
) {
return {
type: 'cosmos-sdk/MsgWithdrawDelegationReward',
value: {
delegator_address: delegatorAddress,
validator_address: validatorAddress,
},
}
}
export const MSG_WITHDRAW_VALIDATOR_COMMISSION_TYPES = {
MsgValue: [{ name: 'validator_address', type: 'string' }],
}
export interface MsgWithdrawValidatorCommissionInterface {
type
value
}
export function createMsgWithdrawValidatorCommission(validatorAddress) {
return {
type: 'cosmos-sdk/MsgWithdrawValidatorCommission',
value: {
validator_address: validatorAddress,
},
}
}
|
b54738c443e9096be67646dd7f26ce561c458c70 | 3,119 | ts | TypeScript | src/.internal/core/util/Timezone.ts | Rostov1991/amcharts5 | 583372a17b16261f057e6e60b0dc4621914528af | [
"Info-ZIP"
] | 1 | 2022-03-15T17:37:56.000Z | 2022-03-15T17:37:56.000Z | src/.internal/core/util/Timezone.ts | Rostov1991/amcharts5 | 583372a17b16261f057e6e60b0dc4621914528af | [
"Info-ZIP"
] | null | null | null | src/.internal/core/util/Timezone.ts | Rostov1991/amcharts5 | 583372a17b16261f057e6e60b0dc4621914528af | [
"Info-ZIP"
] | null | null | null | interface ParsedDate {
year: number,
month: number,
day: number,
hour: number,
minute: number,
second: number,
millisecond: number,
}
function parseDate(timezone: Intl.DateTimeFormat, date: Date): ParsedDate {
let year = 0;
let month = 0;
let day = 1;
let hour = 0;
let minute = 0;
let second = 0;
let millisecond = 0;
timezone.formatToParts(date).forEach((x) => {
switch (x.type) {
case "year":
year = +x.value;
break;
case "month":
month = (+x.value) - 1;
break;
case "day":
day = +x.value;
break;
case "hour":
hour = +x.value;
break;
case "minute":
minute = +x.value;
break;
case "second":
second = +x.value;
break;
case "fractionalSecond" as any:
millisecond = +x.value;
break;
}
});
if (hour === 24) {
hour = 0;
}
return { year, month, day, hour, minute, second, millisecond };
}
function toUTCDate(timezone: Intl.DateTimeFormat, date: Date): number {
const { year, month, day, hour, minute, second, millisecond } = parseDate(timezone, date);
return Date.UTC(year, month, day, hour, minute, second, millisecond);
}
export class Timezone {
private _utc: Intl.DateTimeFormat;
private _dtf: Intl.DateTimeFormat;
public readonly name: string | undefined;
/**
* Use this method to create an instance of this class.
*
* @see {@link https://www.amcharts.com/docs/v5/getting-started/#New_element_syntax} for more info
* @param timezone IANA timezone
* @return Instantiated object
*/
static new<C extends typeof Timezone, T extends InstanceType<C>>(this: C, timezone: string | undefined): T {
return (new this(timezone, true)) as T;
}
constructor(timezone: string | undefined, isReal: boolean) {
if (!isReal) {
throw new Error("You cannot use `new Class()`, instead use `Class.new()`");
}
this.name = timezone;
this._utc = new Intl.DateTimeFormat("UTC", {
hour12: false,
timeZone: "UTC",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
fractionalSecondDigits: 3,
} as any);
this._dtf = new Intl.DateTimeFormat("UTC", {
hour12: false,
timeZone: timezone,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
fractionalSecondDigits: 3,
} as any);
}
convertLocal(date: Date): Date {
const offset = this.offsetUTC(date);
const userOffset = date.getTimezoneOffset();
const output = new Date(date);
output.setUTCMinutes(output.getUTCMinutes() - (offset - userOffset));
return output;
}
offsetUTC(date: Date): number {
const utc = toUTCDate(this._utc, date);
const dtf = toUTCDate(this._dtf, date);
return (utc - dtf) / 60000;
}
parseDate(date: Date): ParsedDate {
return parseDate(this._dtf, date)
}
}
| 24.559055 | 109 | 0.587368 | 102 | 8 | 0 | 12 | 13 | 10 | 3 | 3 | 13 | 2 | 4 | 12.125 | 963 | 0.020768 | 0.013499 | 0.010384 | 0.002077 | 0.004154 | 0.069767 | 0.302326 | 0.264759 | interface ParsedDate {
year,
month,
day,
hour,
minute,
second,
millisecond,
}
/* Example usages of 'parseDate' are shown below:
parseDate(timezone, date);
parseDate(this._dtf, date);
*/
function parseDate(timezone, date) {
let year = 0;
let month = 0;
let day = 1;
let hour = 0;
let minute = 0;
let second = 0;
let millisecond = 0;
timezone.formatToParts(date).forEach((x) => {
switch (x.type) {
case "year":
year = +x.value;
break;
case "month":
month = (+x.value) - 1;
break;
case "day":
day = +x.value;
break;
case "hour":
hour = +x.value;
break;
case "minute":
minute = +x.value;
break;
case "second":
second = +x.value;
break;
case "fractionalSecond" as any:
millisecond = +x.value;
break;
}
});
if (hour === 24) {
hour = 0;
}
return { year, month, day, hour, minute, second, millisecond };
}
/* Example usages of 'toUTCDate' are shown below:
toUTCDate(this._utc, date);
toUTCDate(this._dtf, date);
*/
function toUTCDate(timezone, date) {
const { year, month, day, hour, minute, second, millisecond } = parseDate(timezone, date);
return Date.UTC(year, month, day, hour, minute, second, millisecond);
}
export class Timezone {
private _utc;
private _dtf;
public readonly name;
/**
* Use this method to create an instance of this class.
*
* @see {@link https://www.amcharts.com/docs/v5/getting-started/#New_element_syntax} for more info
* @param timezone IANA timezone
* @return Instantiated object
*/
static new<C extends typeof Timezone, T extends InstanceType<C>>(this, timezone) {
return (new this(timezone, true)) as T;
}
constructor(timezone, isReal) {
if (!isReal) {
throw new Error("You cannot use `new Class()`, instead use `Class.new()`");
}
this.name = timezone;
this._utc = new Intl.DateTimeFormat("UTC", {
hour12: false,
timeZone: "UTC",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
fractionalSecondDigits: 3,
} as any);
this._dtf = new Intl.DateTimeFormat("UTC", {
hour12: false,
timeZone: timezone,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
fractionalSecondDigits: 3,
} as any);
}
convertLocal(date) {
const offset = this.offsetUTC(date);
const userOffset = date.getTimezoneOffset();
const output = new Date(date);
output.setUTCMinutes(output.getUTCMinutes() - (offset - userOffset));
return output;
}
offsetUTC(date) {
const utc = toUTCDate(this._utc, date);
const dtf = toUTCDate(this._dtf, date);
return (utc - dtf) / 60000;
}
parseDate(date) {
return parseDate(this._dtf, date)
}
}
|
b55af90f5ee93aeaec534f7ed73642fd04f79d4a | 2,787 | ts | TypeScript | src/utils/dotUtils.ts | Samedis-care/react-components | 2e44c314189cf792394c39622e14100e81882ffd | [
"Apache-2.0"
] | null | null | null | src/utils/dotUtils.ts | Samedis-care/react-components | 2e44c314189cf792394c39622e14100e81882ffd | [
"Apache-2.0"
] | 1 | 2022-03-15T09:12:45.000Z | 2022-03-15T09:12:45.000Z | src/utils/dotUtils.ts | Samedis-care/react-components | 2e44c314189cf792394c39622e14100e81882ffd | [
"Apache-2.0"
] | null | null | null | /*
utils for object dot notation
what is the dot notation? this is best explained by example:
suppose you have an object:
```js
const a = {
b: {
c: {
d: 1
}
}
}
```
now you want to access the number stored in d, in JS you would just do
`a.b.c.d`, but what about dynamic paths? You'd have to write a['b']['c']['d'],
but this of course is limited to a fixed depth. Here's where dot notation and these
utils come in handy. You can simply access the number by calling `getValueByDot("b.c.d", a)`
The following utils are for the conversion of nested objects to dot-notation based records and vice versa
*/
export const dotToObject = (
field: string,
value: unknown
): Record<string, unknown> => {
const fieldParts = field.split(".").reverse();
for (const fieldPart of fieldParts) {
value = {
[fieldPart]: value,
};
}
return value as Record<string, unknown>;
};
export const getValueByDot = (
field: string,
data: Record<string, unknown>
): unknown => {
const fieldParts = field.split(".");
let value: unknown = data;
for (let i = 0; i < fieldParts.length; ++i) {
if (typeof value !== "object") return undefined;
value = (value as Record<string, unknown>)[fieldParts[i]];
}
return value;
};
export const objectToDots = (
obj: Record<string, unknown>
): Record<string, unknown> => {
const ret: Record<string, unknown> = {};
for (const key in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;
const value = obj[key];
if (typeof value === "object") {
const dots = objectToDots(value as Record<string, unknown>);
Object.entries(dots).forEach(([dot, nestedValue]) => {
ret[key + "." + dot] = nestedValue;
});
} else {
ret[key] = value;
}
}
return ret;
};
export const dotsToObject = (
dots: Record<string, unknown>
): Record<string, unknown> => {
const result: Record<string, unknown> = {};
for (const key in dots) {
if (!Object.prototype.hasOwnProperty.call(dots, key)) continue;
const parts = key.split(".");
let insertion = result;
parts.forEach((part, idx) => {
// set value
if (idx == parts.length - 1) {
insertion[part] = dots[key];
return;
}
// or create nested object
if (!(part in insertion)) {
insertion[part] = {};
}
insertion = insertion[part] as Record<string, unknown>;
});
}
return result;
};
export const dotSet = (
field: string,
value: Record<string, unknown>,
data: unknown
): Record<string, unknown> => {
if (typeof value !== "object") throw new Error("invalid");
const fieldParts = field.split(".");
const ret = { ...value };
ret[fieldParts[0]] =
fieldParts.length > 1
? dotSet(
fieldParts.slice(1).join("."),
ret[fieldParts[0]] as Record<string, unknown>,
data
)
: data;
return ret;
};
| 24.234783 | 105 | 0.642268 | 81 | 7 | 0 | 12 | 17 | 0 | 2 | 0 | 37 | 0 | 8 | 9.428571 | 880 | 0.021591 | 0.019318 | 0 | 0 | 0.009091 | 0 | 1.027778 | 0.281515 | /*
utils for object dot notation
what is the dot notation? this is best explained by example:
suppose you have an object:
```js
const a = {
b: {
c: {
d: 1
}
}
}
```
now you want to access the number stored in d, in JS you would just do
`a.b.c.d`, but what about dynamic paths? You'd have to write a['b']['c']['d'],
but this of course is limited to a fixed depth. Here's where dot notation and these
utils come in handy. You can simply access the number by calling `getValueByDot("b.c.d", a)`
The following utils are for the conversion of nested objects to dot-notation based records and vice versa
*/
export const dotToObject = (
field,
value
) => {
const fieldParts = field.split(".").reverse();
for (const fieldPart of fieldParts) {
value = {
[fieldPart]: value,
};
}
return value as Record<string, unknown>;
};
export const getValueByDot = (
field,
data
) => {
const fieldParts = field.split(".");
let value = data;
for (let i = 0; i < fieldParts.length; ++i) {
if (typeof value !== "object") return undefined;
value = (value as Record<string, unknown>)[fieldParts[i]];
}
return value;
};
export /* Example usages of 'objectToDots' are shown below:
objectToDots(value as Record<string, unknown>);
*/
const objectToDots = (
obj
) => {
const ret = {};
for (const key in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;
const value = obj[key];
if (typeof value === "object") {
const dots = objectToDots(value as Record<string, unknown>);
Object.entries(dots).forEach(([dot, nestedValue]) => {
ret[key + "." + dot] = nestedValue;
});
} else {
ret[key] = value;
}
}
return ret;
};
export const dotsToObject = (
dots
) => {
const result = {};
for (const key in dots) {
if (!Object.prototype.hasOwnProperty.call(dots, key)) continue;
const parts = key.split(".");
let insertion = result;
parts.forEach((part, idx) => {
// set value
if (idx == parts.length - 1) {
insertion[part] = dots[key];
return;
}
// or create nested object
if (!(part in insertion)) {
insertion[part] = {};
}
insertion = insertion[part] as Record<string, unknown>;
});
}
return result;
};
export /* Example usages of 'dotSet' are shown below:
ret[fieldParts[0]] =
fieldParts.length > 1
? dotSet(fieldParts.slice(1).join("."), ret[fieldParts[0]] as Record<string, unknown>, data)
: data;
*/
const dotSet = (
field,
value,
data
) => {
if (typeof value !== "object") throw new Error("invalid");
const fieldParts = field.split(".");
const ret = { ...value };
ret[fieldParts[0]] =
fieldParts.length > 1
? dotSet(
fieldParts.slice(1).join("."),
ret[fieldParts[0]] as Record<string, unknown>,
data
)
: data;
return ret;
};
|
7c6b66273a2e2ae0cf4af96fca68877ec089846c | 1,987 | ts | TypeScript | src/t-getter.ts | a-dev/t-getter | 07027f905cfebe092cceb50b30e67c17eec7bf9c | [
"MIT"
] | 1 | 2022-02-11T18:18:42.000Z | 2022-02-11T18:18:42.000Z | src/t-getter.ts | a-dev/t-getter | 07027f905cfebe092cceb50b30e67c17eec7bf9c | [
"MIT"
] | null | null | null | src/t-getter.ts | a-dev/t-getter | 07027f905cfebe092cceb50b30e67c17eec7bf9c | [
"MIT"
] | null | null | null | type Placeholder = undefined | string | Function
interface Options {
placeholder?: Placeholder
freeze?: boolean
}
type Result = string | number | Function
type TextObject = Record<string, Result | object>
type TextPath = string
type Texts = TextObject[] | []
type TextFnArguments = string[] | number[]
const ALLOWED_TYPES = ['string', 'number']
const ERROR_TEXTS = Object.freeze({
not_set: '[t-getter.js] There is no texts objects'
})
export default function GetText(
texts: Texts,
{ placeholder = undefined, freeze = true }: Options = {}
) {
if (!texts?.length) throw new Error(ERROR_TEXTS.not_set)
texts = texts.map((o) => (freeze ? Object.freeze(o) : o))
let placeholderOpt: any = placeholder
function placeholderFn(options: {
prop: TextPath
args: TextFnArguments
}): undefined | any {
return typeof placeholderOpt == 'function'
? placeholderOpt(options)
: placeholderOpt
}
function checkAllowedTypes(val: any): boolean {
return ALLOWED_TYPES.includes(typeof val)
}
function getTextValue({
index,
prop,
args
}: {
index: number
args: TextFnArguments
prop: TextPath
}): Result {
const path = prop.split('.')
let textObject: any = texts[index]
let i = 0
while (i < path.length) {
let value: TextObject | Result = textObject[path[i]]
if (value == null) break
if (typeof value == 'function') value = value(...args)
textObject = value
i++
}
return textObject
}
function t(prop: TextPath, ...args: TextFnArguments): Result {
if (!texts.length) throw new Error(ERROR_TEXTS.not_set)
let result: any = undefined
let index = 0
while (index < texts.length) {
const value = getTextValue({ index, prop, args })
if (checkAllowedTypes(value)) {
result = value
break
}
index++
}
if (!checkAllowedTypes(result)) return placeholderFn({ prop, args })
return result
}
return t
}
| 23.939759 | 72 | 0.643181 | 70 | 6 | 0 | 8 | 10 | 2 | 3 | 7 | 11 | 7 | 3 | 13.333333 | 524 | 0.026718 | 0.019084 | 0.003817 | 0.013359 | 0.005725 | 0.269231 | 0.423077 | 0.311588 | type Placeholder = undefined | string | Function
interface Options {
placeholder?
freeze?
}
type Result = string | number | Function
type TextObject = Record<string, Result | object>
type TextPath = string
type Texts = TextObject[] | []
type TextFnArguments = string[] | number[]
const ALLOWED_TYPES = ['string', 'number']
const ERROR_TEXTS = Object.freeze({
not_set: '[t-getter.js] There is no texts objects'
})
export default function GetText(
texts,
{ placeholder = undefined, freeze = true } = {}
) {
if (!texts?.length) throw new Error(ERROR_TEXTS.not_set)
texts = texts.map((o) => (freeze ? Object.freeze(o) : o))
let placeholderOpt = placeholder
/* Example usages of 'placeholderFn' are shown below:
placeholderFn({ prop, args });
*/
function placeholderFn(options) {
return typeof placeholderOpt == 'function'
? placeholderOpt(options)
: placeholderOpt
}
/* Example usages of 'checkAllowedTypes' are shown below:
checkAllowedTypes(value);
!checkAllowedTypes(result);
*/
function checkAllowedTypes(val) {
return ALLOWED_TYPES.includes(typeof val)
}
/* Example usages of 'getTextValue' are shown below:
getTextValue({ index, prop, args });
*/
function getTextValue({
index,
prop,
args
}) {
const path = prop.split('.')
let textObject = texts[index]
let i = 0
while (i < path.length) {
let value = textObject[path[i]]
if (value == null) break
if (typeof value == 'function') value = value(...args)
textObject = value
i++
}
return textObject
}
/* Example usages of 't' are shown below:
return t;
*/
function t(prop, ...args) {
if (!texts.length) throw new Error(ERROR_TEXTS.not_set)
let result = undefined
let index = 0
while (index < texts.length) {
const value = getTextValue({ index, prop, args })
if (checkAllowedTypes(value)) {
result = value
break
}
index++
}
if (!checkAllowedTypes(result)) return placeholderFn({ prop, args })
return result
}
return t
}
|
d40facef8515c83b23a6102df87c1e2321f0cb77 | 4,077 | ts | TypeScript | admin/src/utils/util.ts | likeshop-github/likeadmin | 42656382f78a46793a564d0d7549c3446afdaadc | [
"Apache-2.0"
] | 8 | 2022-02-22T02:39:28.000Z | 2022-03-19T10:45:38.000Z | admin/src/utils/util.ts | likeshop-github/likeadmin | 42656382f78a46793a564d0d7549c3446afdaadc | [
"Apache-2.0"
] | null | null | null | admin/src/utils/util.ts | likeshop-github/likeadmin | 42656382f78a46793a564d0d7549c3446afdaadc | [
"Apache-2.0"
] | 1 | 2022-02-22T02:48:55.000Z | 2022-02-22T02:48:55.000Z | /**
* 工具方法
* 请谨慎操作,影响全局
*/
/**
* 深拷贝
* @param {any} target 需要深拷贝的对象
* @returns {Object}
*/
export function deepClone(target: any) {
if (typeof target !== 'object' || target === null) {
return target
}
const cloneResult: any = Array.isArray(target) ? [] : {}
for (const key in target) {
if (Object.prototype.hasOwnProperty.call(target, key)) {
const value = target[key]
if (typeof value === 'object' && value !== null) {
cloneResult[key] = deepClone(value)
} else {
cloneResult[key] = value
}
}
}
return cloneResult
}
/**
* 过滤对象属性
* @param { Object } target
* @param { Array } filters
* @return { Object } 过滤后的对象
*/
export function filterObject(target: any, filters: any[]) {
const _target = deepClone(target)
filters.map(key => delete _target[key])
return _target
}
/**
* 节流
* @param { Function } func
* @param { Number } time
* @param context
* @return { Function }
*/
export function throttle(func: () => any, time = 1000, context?: any): any {
let previous = new Date(0).getTime()
return function (...args: []) {
const now = new Date().getTime()
if (now - previous > time) {
previous = now
return func.apply(context, args)
}
}
}
/**
* Query语法格式化为对象
* @param { String } str
* @return { Object }
*/
export function queryToObject(str: string) {
const params: any = {}
for (const item of str.split('&')) {
params[item.split('=')[0]] = item.split('=')[1]
}
return params
}
/**
* 对象格式化为Query语法
* @param { Object } params
* @return {string} Query语法
*/
export function objectToQuery(params: any) {
let p = ''
if (typeof params === 'object') {
p = '?'
for (const props in params) {
p += `${props}=${params[props]}&`
}
p = p.slice(0, -1)
}
return p
}
/**
* @description 获取不重复的id
* @param length { Number } id的长度
* @return { String } id
*/
export const getNonDuplicateID = (length = 8) => {
let idStr = Date.now().toString(36)
idStr += Math.random().toString(36).substr(3, length)
return idStr
}
/**
* @description 时间格式化
* @param dateTime { number } 时间戳
* @param fmt { string } 时间格式
* @return { string }
*/
// yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合
export const timeFormat = (dateTime: number, fmt = 'yyyy-mm-dd') => {
// 如果为null,则格式化当前时间
if (!dateTime) {
dateTime = Number(new Date())
}
// 如果dateTime长度为10或者13,则为秒和毫秒的时间戳,如果超过13位,则为其他的时间格式
if (dateTime.toString().length == 10) {
dateTime *= 1000
}
const date = new Date(dateTime)
let ret
const opt: any = {
'y+': date.getFullYear().toString(), // 年
'm+': (date.getMonth() + 1).toString(), // 月
'd+': date.getDate().toString(), // 日
'h+': date.getHours().toString(), // 时
'M+': date.getMinutes().toString(), // 分
's+': date.getSeconds().toString() // 秒
}
for (const k in opt) {
ret = new RegExp('(' + k + ')').exec(fmt)
if (ret) {
fmt = fmt.replace(
ret[1],
ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
)
}
}
return fmt
}
// /**
// *
// * @param {*} tree
// * @param {*} arr
// * @returns
// */
// export function flatten(tree = [], arr = []) {
// tree.forEach((item) => {
// const { children } = item
// arr.push(item)
// if (children) flatten(children, arr)
// })
// return arr
// }
/**
* @description 树状数组扁平化
* @param { Array } tree 树状结构数组
* @param { Array } arr 扁平化后的数组
* @param { String } childrenKey 子节点键名
* @return { Array } 扁平化后的数组
*/
export function flatten(tree = [], arr = [], childrenKey = 'children') {
tree.forEach(item => {
const children = item[childrenKey]
children ? flatten(children, arr, childrenKey) : arr.push(item)
})
return arr
}
| 23.842105 | 81 | 0.533726 | 90 | 11 | 0 | 17 | 14 | 0 | 2 | 10 | 2 | 0 | 3 | 7.454545 | 1,272 | 0.022013 | 0.011006 | 0 | 0 | 0.002358 | 0.238095 | 0.047619 | 0.253814 | /**
* 工具方法
* 请谨慎操作,影响全局
*/
/**
* 深拷贝
* @param {any} target 需要深拷贝的对象
* @returns {Object}
*/
export /* Example usages of 'deepClone' are shown below:
cloneResult[key] = deepClone(value);
deepClone(target);
*/
function deepClone(target) {
if (typeof target !== 'object' || target === null) {
return target
}
const cloneResult = Array.isArray(target) ? [] : {}
for (const key in target) {
if (Object.prototype.hasOwnProperty.call(target, key)) {
const value = target[key]
if (typeof value === 'object' && value !== null) {
cloneResult[key] = deepClone(value)
} else {
cloneResult[key] = value
}
}
}
return cloneResult
}
/**
* 过滤对象属性
* @param { Object } target
* @param { Array } filters
* @return { Object } 过滤后的对象
*/
export function filterObject(target, filters) {
const _target = deepClone(target)
filters.map(key => delete _target[key])
return _target
}
/**
* 节流
* @param { Function } func
* @param { Number } time
* @param context
* @return { Function }
*/
export function throttle(func, time = 1000, context?) {
let previous = new Date(0).getTime()
return function (...args) {
const now = new Date().getTime()
if (now - previous > time) {
previous = now
return func.apply(context, args)
}
}
}
/**
* Query语法格式化为对象
* @param { String } str
* @return { Object }
*/
export function queryToObject(str) {
const params = {}
for (const item of str.split('&')) {
params[item.split('=')[0]] = item.split('=')[1]
}
return params
}
/**
* 对象格式化为Query语法
* @param { Object } params
* @return {string} Query语法
*/
export function objectToQuery(params) {
let p = ''
if (typeof params === 'object') {
p = '?'
for (const props in params) {
p += `${props}=${params[props]}&`
}
p = p.slice(0, -1)
}
return p
}
/**
* @description 获取不重复的id
* @param length { Number } id的长度
* @return { String } id
*/
export const getNonDuplicateID = (length = 8) => {
let idStr = Date.now().toString(36)
idStr += Math.random().toString(36).substr(3, length)
return idStr
}
/**
* @description 时间格式化
* @param dateTime { number } 时间戳
* @param fmt { string } 时间格式
* @return { string }
*/
// yyyy:mm:dd|yyyy:mm|yyyy年mm月dd日|yyyy年mm月dd日 hh时MM分等,可自定义组合
export const timeFormat = (dateTime, fmt = 'yyyy-mm-dd') => {
// 如果为null,则格式化当前时间
if (!dateTime) {
dateTime = Number(new Date())
}
// 如果dateTime长度为10或者13,则为秒和毫秒的时间戳,如果超过13位,则为其他的时间格式
if (dateTime.toString().length == 10) {
dateTime *= 1000
}
const date = new Date(dateTime)
let ret
const opt = {
'y+': date.getFullYear().toString(), // 年
'm+': (date.getMonth() + 1).toString(), // 月
'd+': date.getDate().toString(), // 日
'h+': date.getHours().toString(), // 时
'M+': date.getMinutes().toString(), // 分
's+': date.getSeconds().toString() // 秒
}
for (const k in opt) {
ret = new RegExp('(' + k + ')').exec(fmt)
if (ret) {
fmt = fmt.replace(
ret[1],
ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
)
}
}
return fmt
}
// /**
// *
// * @param {*} tree
// * @param {*} arr
// * @returns
// */
// export function flatten(tree = [], arr = []) {
// tree.forEach((item) => {
// const { children } = item
// arr.push(item)
// if (children) flatten(children, arr)
// })
// return arr
// }
/**
* @description 树状数组扁平化
* @param { Array } tree 树状结构数组
* @param { Array } arr 扁平化后的数组
* @param { String } childrenKey 子节点键名
* @return { Array } 扁平化后的数组
*/
export /* Example usages of 'flatten' are shown below:
children ? flatten(children, arr, childrenKey) : arr.push(item);
*/
function flatten(tree = [], arr = [], childrenKey = 'children') {
tree.forEach(item => {
const children = item[childrenKey]
children ? flatten(children, arr, childrenKey) : arr.push(item)
})
return arr
}
|
d427a493f22b76a6f03b2bc1886cc5ca77e22794 | 2,409 | ts | TypeScript | src/converter.ts | tnk050/quesheetCreator | 136b1d82316936bce657e68c36c59beb5c8add1f | [
"MIT"
] | null | null | null | src/converter.ts | tnk050/quesheetCreator | 136b1d82316936bce657e68c36c59beb5c8add1f | [
"MIT"
] | 3 | 2022-03-28T04:58:27.000Z | 2022-03-28T04:59:56.000Z | src/converter.ts | tnk050/quesheetCreator | 136b1d82316936bce657e68c36c59beb5c8add1f | [
"MIT"
] | null | null | null | export function convertDirection(input: string): string {
const directionPattern = {
Straight: '直進',
Left: '左折',
Right: '右折',
'Slight Left': '左方向',
'Slight Right': '右方向',
};
return directionPattern[input] || input;
}
export function convertCrossing(input: string): string {
const rxp = /(.*?)(交差点)/;
const mutchs = rxp.exec(input);
return mutchs ? mutchs[1] : '';
}
export function convertRoute(input: string, type?: string): string {
const rxp = /(.道)(\d+)号/g;
const routeType = {
R: '国道',
T: '都道',
D: '道道',
F: '府道',
K: '県道',
C: '市道',
};
const routes = input.match(rxp);
if (!routes) {
return '';
}
if (routes.length === 1) {
return translate(routes[0]);
}
const nRoutes = routes.filter((route) => route.includes(routeType.R));
const pRoutes = routes.filter(
(route) =>
route.includes(routeType.T) ||
route.includes(routeType.D) ||
route.includes(routeType.F) ||
route.includes(routeType.K)
);
const cRoutes = routes.filter((route) => route.includes(routeType.C));
if (nRoutes.length) {
return translate(nRoutes[0]);
} else if (pRoutes.length) {
return translate(pRoutes[0]);
} else if (cRoutes.length) {
return translate(cRoutes[0]);
} else {
return 'sortError';
}
function translate(route: string): string {
const isIntegrateK = type === 'k';
const isEnglish = type === 'en' || isIntegrateK;
if (isEnglish) {
const strs = rxp.exec(route);
let prefix =
Object.keys(routeType).filter((key) => routeType[key] === strs[1])[0] ||
strs[1];
if (
isIntegrateK &&
(prefix === 'T' || prefix === 'D' || prefix === 'F' || prefix === 'K')
) {
prefix = 'K';
}
const routeNumber = strs[2] || 'xxx';
return prefix + routeNumber;
} else {
return route;
}
}
}
export function extractRemarks(input: string): string {
const ignoreRxp = /(右折|左折|直進)する|進む/;
const cutRxp = /(.*?)((右折|左折|直進)して|曲がり)/;
if (cutRxp.test(input)) {
const newstr = input.replace(cutRxp, '');
return newstr.replace(/^、/, '').trim();
} else if (ignoreRxp.test(input)) {
return '';
} else {
return input;
}
}
export function carryUp(input: number): number | string {
if (Number.isNaN(input)) {
return 'carry up error';
}
return Math.round(input * 10) / 10;
}
| 25.357895 | 80 | 0.575758 | 89 | 10 | 0 | 11 | 17 | 0 | 1 | 0 | 14 | 0 | 0 | 10.4 | 787 | 0.026684 | 0.021601 | 0 | 0 | 0 | 0 | 0.368421 | 0.302862 | export function convertDirection(input) {
const directionPattern = {
Straight: '直進',
Left: '左折',
Right: '右折',
'Slight Left': '左方向',
'Slight Right': '右方向',
};
return directionPattern[input] || input;
}
export function convertCrossing(input) {
const rxp = /(.*?)(交差点)/;
const mutchs = rxp.exec(input);
return mutchs ? mutchs[1] : '';
}
export function convertRoute(input, type?) {
const rxp = /(.道)(\d+)号/g;
const routeType = {
R: '国道',
T: '都道',
D: '道道',
F: '府道',
K: '県道',
C: '市道',
};
const routes = input.match(rxp);
if (!routes) {
return '';
}
if (routes.length === 1) {
return translate(routes[0]);
}
const nRoutes = routes.filter((route) => route.includes(routeType.R));
const pRoutes = routes.filter(
(route) =>
route.includes(routeType.T) ||
route.includes(routeType.D) ||
route.includes(routeType.F) ||
route.includes(routeType.K)
);
const cRoutes = routes.filter((route) => route.includes(routeType.C));
if (nRoutes.length) {
return translate(nRoutes[0]);
} else if (pRoutes.length) {
return translate(pRoutes[0]);
} else if (cRoutes.length) {
return translate(cRoutes[0]);
} else {
return 'sortError';
}
/* Example usages of 'translate' are shown below:
translate(routes[0]);
translate(nRoutes[0]);
translate(pRoutes[0]);
translate(cRoutes[0]);
*/
function translate(route) {
const isIntegrateK = type === 'k';
const isEnglish = type === 'en' || isIntegrateK;
if (isEnglish) {
const strs = rxp.exec(route);
let prefix =
Object.keys(routeType).filter((key) => routeType[key] === strs[1])[0] ||
strs[1];
if (
isIntegrateK &&
(prefix === 'T' || prefix === 'D' || prefix === 'F' || prefix === 'K')
) {
prefix = 'K';
}
const routeNumber = strs[2] || 'xxx';
return prefix + routeNumber;
} else {
return route;
}
}
}
export function extractRemarks(input) {
const ignoreRxp = /(右折|左折|直進)する|進む/;
const cutRxp = /(.*?)((右折|左折|直進)して|曲がり)/;
if (cutRxp.test(input)) {
const newstr = input.replace(cutRxp, '');
return newstr.replace(/^、/, '').trim();
} else if (ignoreRxp.test(input)) {
return '';
} else {
return input;
}
}
export function carryUp(input) {
if (Number.isNaN(input)) {
return 'carry up error';
}
return Math.round(input * 10) / 10;
}
|
d4d153d5202d5af8c07e4d83da69664d7336a49e | 5,011 | ts | TypeScript | src/MySqlClient.ts | antares-sql/antares-mysql-dumper | 3668d09c4ead187b7d7bb43e286c2b3890777547 | [
"MIT"
] | 1 | 2022-03-31T17:57:35.000Z | 2022-03-31T17:57:35.000Z | src/MySqlClient.ts | antares-sql/antares-mysql-dumper | 3668d09c4ead187b7d7bb43e286c2b3890777547 | [
"MIT"
] | null | null | null | src/MySqlClient.ts | antares-sql/antares-mysql-dumper | 3668d09c4ead187b7d7bb43e286c2b3890777547 | [
"MIT"
] | null | null | null | export class MySqlClient {
connection: any;
schema: string;
constructor(connection, schema) {
this.connection = connection;
this.schema = schema;
}
/**
* @param {Object} params
* @param {String} params.schema
* @param {String} params.table
* @returns {Object} table scructure
* @memberof MySQLClient
*/
async getTableColumns({ schema, table }) {
const { rows } = await this.raw(
`SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '${schema}' AND TABLE_NAME='${table}'`
);
const { rows: fields } = await this.raw(
`SHOW CREATE TABLE \`${schema}\`.\`${table}\``
);
const remappedFields = fields.map((row) => {
if (!row["Create Table"]) return false;
let n = 0;
return row["Create Table"]
.split("")
.reduce((acc, curr) => {
if (curr === ")") n--;
if (n !== 0) acc += curr;
if (curr === "(") n++;
return acc;
}, "")
.replace(/\n/g, "")
.split(/,\s?(?![^(]*\))/)
.map((f) => {
try {
const fieldArr = f.trim().split(" ");
const nameAndType = fieldArr.slice(0, 2);
if (nameAndType[0].charAt(0) !== "`") return false;
const details = fieldArr.slice(2).join(" ");
let defaultValue = null;
if (details.includes("DEFAULT"))
defaultValue = details
.match(/(?<=DEFAULT ).*?$/gs)[0]
.split(" COMMENT")[0];
// const defaultValueArr = defaultValue.split('');
// if (defaultValueArr[0] === '\'') {
// defaultValueArr.shift();
// defaultValueArr.pop();
// defaultValue = defaultValueArr.join('');
// }
const typeAndLength = nameAndType[1].replace(")", "").split("(");
return {
name: nameAndType[0].replace(/`/g, ""),
type: typeAndLength[0].toUpperCase(),
length: typeAndLength[1] ? typeAndLength[1] : null,
default: defaultValue,
};
} catch (err) {
return false;
}
})
.filter(Boolean)
.reduce((acc, curr) => {
acc[curr.name] = curr;
return acc;
}, {});
})[0];
return rows.map((field) => {
let numLength = field.COLUMN_TYPE.match(/int\(([^)]+)\)/);
numLength = numLength
? +numLength.pop()
: field.NUMERIC_PRECISION || null;
const enumValues = /(enum|set)/.test(field.COLUMN_TYPE)
? field.COLUMN_TYPE.match(/\(([^)]+)\)/)[0].slice(1, -1)
: null;
const defaultValue =
remappedFields && remappedFields[field.COLUMN_NAME]
? remappedFields[field.COLUMN_NAME].default
: field.COLUMN_DEFAULT;
return {
name: field.COLUMN_NAME,
key: field.COLUMN_KEY.toLowerCase(),
type:
remappedFields && remappedFields[field.COLUMN_NAME]
? remappedFields[field.COLUMN_NAME].type
: field.DATA_TYPE.toUpperCase(),
schema: field.TABLE_SCHEMA,
table: field.TABLE_NAME,
numPrecision: field.NUMERIC_PRECISION,
numScale: Number(field.NUMERIC_SCALE),
numLength,
enumValues,
datePrecision: field.DATETIME_PRECISION,
charLength: field.CHARACTER_MAXIMUM_LENGTH,
nullable: field.IS_NULLABLE.includes("YES"),
unsigned: field.COLUMN_TYPE.includes("unsigned"),
zerofill: field.COLUMN_TYPE.includes("zerofill"),
order: field.ORDINAL_POSITION,
default: defaultValue,
charset: field.CHARACTER_SET_NAME,
collation: field.COLLATION_NAME,
autoIncrement: field.EXTRA.includes("auto_increment"),
generated: field.EXTRA.toLowerCase().includes("generated"),
onUpdate: field.EXTRA.toLowerCase().includes("on update")
? field.EXTRA.substr(
field.EXTRA.indexOf("on update") + 9,
field.EXTRA.length
).trim()
: "",
comment: field.COLUMN_COMMENT,
};
});
}
async raw(sql: string): Promise<{ rows: any[] }> {
return new Promise((resolve, reject) => {
this.connection.query(sql, function (error, results, fields) {
if (error) reject(error);
resolve({ rows: results });
});
});
}
async getVersion() {
const sql = 'SHOW VARIABLES LIKE "%vers%"';
const { rows } = await this.raw(sql);
return rows.reduce((acc, curr) => {
switch (curr.Variable_name) {
case "version":
acc.number = curr.Value.split("-")[0];
break;
case "version_comment":
acc.name = curr.Value.replace("(GPL)", "");
break;
case "version_compile_machine":
acc.arch = curr.Value;
break;
case "version_compile_os":
acc.os = curr.Value;
break;
}
return acc;
}, {});
}
}
| 31.515723 | 107 | 0.533626 | 131 | 12 | 0 | 18 | 14 | 2 | 1 | 2 | 2 | 1 | 0 | 20.666667 | 1,243 | 0.024135 | 0.011263 | 0.001609 | 0.000805 | 0 | 0.043478 | 0.043478 | 0.264183 | export class MySqlClient {
connection;
schema;
constructor(connection, schema) {
this.connection = connection;
this.schema = schema;
}
/**
* @param {Object} params
* @param {String} params.schema
* @param {String} params.table
* @returns {Object} table scructure
* @memberof MySQLClient
*/
async getTableColumns({ schema, table }) {
const { rows } = await this.raw(
`SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '${schema}' AND TABLE_NAME='${table}'`
);
const { rows: fields } = await this.raw(
`SHOW CREATE TABLE \`${schema}\`.\`${table}\``
);
const remappedFields = fields.map((row) => {
if (!row["Create Table"]) return false;
let n = 0;
return row["Create Table"]
.split("")
.reduce((acc, curr) => {
if (curr === ")") n--;
if (n !== 0) acc += curr;
if (curr === "(") n++;
return acc;
}, "")
.replace(/\n/g, "")
.split(/,\s?(?![^(]*\))/)
.map((f) => {
try {
const fieldArr = f.trim().split(" ");
const nameAndType = fieldArr.slice(0, 2);
if (nameAndType[0].charAt(0) !== "`") return false;
const details = fieldArr.slice(2).join(" ");
let defaultValue = null;
if (details.includes("DEFAULT"))
defaultValue = details
.match(/(?<=DEFAULT ).*?$/gs)[0]
.split(" COMMENT")[0];
// const defaultValueArr = defaultValue.split('');
// if (defaultValueArr[0] === '\'') {
// defaultValueArr.shift();
// defaultValueArr.pop();
// defaultValue = defaultValueArr.join('');
// }
const typeAndLength = nameAndType[1].replace(")", "").split("(");
return {
name: nameAndType[0].replace(/`/g, ""),
type: typeAndLength[0].toUpperCase(),
length: typeAndLength[1] ? typeAndLength[1] : null,
default: defaultValue,
};
} catch (err) {
return false;
}
})
.filter(Boolean)
.reduce((acc, curr) => {
acc[curr.name] = curr;
return acc;
}, {});
})[0];
return rows.map((field) => {
let numLength = field.COLUMN_TYPE.match(/int\(([^)]+)\)/);
numLength = numLength
? +numLength.pop()
: field.NUMERIC_PRECISION || null;
const enumValues = /(enum|set)/.test(field.COLUMN_TYPE)
? field.COLUMN_TYPE.match(/\(([^)]+)\)/)[0].slice(1, -1)
: null;
const defaultValue =
remappedFields && remappedFields[field.COLUMN_NAME]
? remappedFields[field.COLUMN_NAME].default
: field.COLUMN_DEFAULT;
return {
name: field.COLUMN_NAME,
key: field.COLUMN_KEY.toLowerCase(),
type:
remappedFields && remappedFields[field.COLUMN_NAME]
? remappedFields[field.COLUMN_NAME].type
: field.DATA_TYPE.toUpperCase(),
schema: field.TABLE_SCHEMA,
table: field.TABLE_NAME,
numPrecision: field.NUMERIC_PRECISION,
numScale: Number(field.NUMERIC_SCALE),
numLength,
enumValues,
datePrecision: field.DATETIME_PRECISION,
charLength: field.CHARACTER_MAXIMUM_LENGTH,
nullable: field.IS_NULLABLE.includes("YES"),
unsigned: field.COLUMN_TYPE.includes("unsigned"),
zerofill: field.COLUMN_TYPE.includes("zerofill"),
order: field.ORDINAL_POSITION,
default: defaultValue,
charset: field.CHARACTER_SET_NAME,
collation: field.COLLATION_NAME,
autoIncrement: field.EXTRA.includes("auto_increment"),
generated: field.EXTRA.toLowerCase().includes("generated"),
onUpdate: field.EXTRA.toLowerCase().includes("on update")
? field.EXTRA.substr(
field.EXTRA.indexOf("on update") + 9,
field.EXTRA.length
).trim()
: "",
comment: field.COLUMN_COMMENT,
};
});
}
async raw(sql) {
return new Promise((resolve, reject) => {
this.connection.query(sql, function (error, results, fields) {
if (error) reject(error);
resolve({ rows: results });
});
});
}
async getVersion() {
const sql = 'SHOW VARIABLES LIKE "%vers%"';
const { rows } = await this.raw(sql);
return rows.reduce((acc, curr) => {
switch (curr.Variable_name) {
case "version":
acc.number = curr.Value.split("-")[0];
break;
case "version_comment":
acc.name = curr.Value.replace("(GPL)", "");
break;
case "version_compile_machine":
acc.arch = curr.Value;
break;
case "version_compile_os":
acc.os = curr.Value;
break;
}
return acc;
}, {});
}
}
|
d4fd0907652f36c4560edc81db8a328b4ae7de77 | 1,354 | ts | TypeScript | src/screens/LineChartComponent/utilityFunctions.ts | TheWidlarzGroup/charts-library | 333d8ddc67f87f83fa9c73b585a931c660c4dc0c | [
"MIT"
] | 1 | 2022-03-30T17:40:54.000Z | 2022-03-30T17:40:54.000Z | src/screens/LineChartComponent/utilityFunctions.ts | TheWidlarzGroup/charts-library | 333d8ddc67f87f83fa9c73b585a931c660c4dc0c | [
"MIT"
] | null | null | null | src/screens/LineChartComponent/utilityFunctions.ts | TheWidlarzGroup/charts-library | 333d8ddc67f87f83fa9c73b585a931c660c4dc0c | [
"MIT"
] | null | null | null | export const createAverageValuesArray = (data: number[]): number[] => {
const averageValue = data.reduce((a, b) => a + b) / data.length
return Array(data.length).fill(averageValue)
}
export const composeDataWithAverageValue = (
valuesArray: number[],
averageValuesArray: number[]
) => {
return [
{
data: valuesArray,
svg: { strokeWidth: 3 },
},
{
data: averageValuesArray,
svg: { strokeWidth: 1.5, strokeDasharray: [8, 16] },
},
]
}
export const composeMultiDataWithAverageValue = (
valuesArray: number[],
averageValuesArray: number[],
valuesArray2: number[],
averageValuesArray2: number[],
valuesArray3: number[],
averageValuesArray3: number[]
) => {
return [
{
data: valuesArray,
svg: { stroke: 'blue', strokeWidth: 1 },
},
{
data: averageValuesArray,
svg: { stroke: 'blue', strokeWidth: 1.5, strokeDasharray: [8, 16] },
},
{
data: valuesArray2,
svg: { stroke: 'red', strokeWidth: 1 },
},
{
data: averageValuesArray2,
svg: { stroke: 'red', strokeWidth: 1.5, strokeDasharray: [8, 16] },
},
{
data: valuesArray3,
svg: { stroke: 'green', strokeWidth: 1 },
},
{
data: averageValuesArray3,
svg: { stroke: 'green', strokeWidth: 1.5, strokeDasharray: [8, 16] },
},
]
}
| 23.754386 | 75 | 0.589365 | 54 | 4 | 0 | 11 | 4 | 0 | 0 | 0 | 10 | 0 | 0 | 9.75 | 402 | 0.037313 | 0.00995 | 0 | 0 | 0 | 0 | 0.526316 | 0.289209 | export const createAverageValuesArray = (data) => {
const averageValue = data.reduce((a, b) => a + b) / data.length
return Array(data.length).fill(averageValue)
}
export const composeDataWithAverageValue = (
valuesArray,
averageValuesArray
) => {
return [
{
data: valuesArray,
svg: { strokeWidth: 3 },
},
{
data: averageValuesArray,
svg: { strokeWidth: 1.5, strokeDasharray: [8, 16] },
},
]
}
export const composeMultiDataWithAverageValue = (
valuesArray,
averageValuesArray,
valuesArray2,
averageValuesArray2,
valuesArray3,
averageValuesArray3
) => {
return [
{
data: valuesArray,
svg: { stroke: 'blue', strokeWidth: 1 },
},
{
data: averageValuesArray,
svg: { stroke: 'blue', strokeWidth: 1.5, strokeDasharray: [8, 16] },
},
{
data: valuesArray2,
svg: { stroke: 'red', strokeWidth: 1 },
},
{
data: averageValuesArray2,
svg: { stroke: 'red', strokeWidth: 1.5, strokeDasharray: [8, 16] },
},
{
data: valuesArray3,
svg: { stroke: 'green', strokeWidth: 1 },
},
{
data: averageValuesArray3,
svg: { stroke: 'green', strokeWidth: 1.5, strokeDasharray: [8, 16] },
},
]
}
|
1085ac7acbf8f7d024dde2b4e7c558af490b9be4 | 1,602 | ts | TypeScript | src/taskpane/data/getTaxForIncome.ts | wandyezj/excel-life | f2e2f93771a98a268859d1d3f50677cb0066714b | [
"Unlicense"
] | null | null | null | src/taskpane/data/getTaxForIncome.ts | wandyezj/excel-life | f2e2f93771a98a268859d1d3f50677cb0066714b | [
"Unlicense"
] | 3 | 2022-01-22T13:30:34.000Z | 2022-02-27T09:15:13.000Z | src/taskpane/data/getTaxForIncome.ts | wandyezj/excel-life | f2e2f93771a98a268859d1d3f50677cb0066714b | [
"Unlicense"
] | null | null | null | // https://www.debt.org/tax/brackets/
const taxBrackets: {
above: number;
below: number;
rate: number;
}[] = [
{
above: 0,
below: 9875,
rate: 10
},
{
above: 9876,
below: 40125,
rate: 12
},
{
above: 40126,
below: 85525,
rate: 22
},
{
above: 85526,
below: 163300,
rate: 24
},
{
above: 163301,
below: 207350,
rate: 32
},
{
above: 207351,
below: 518400,
rate: 35
},
{
above: 518401,
below: undefined,
rate: 37
}
];
export default function getTaxForIncome(income: number) {
if (income <= 0) {
return 0;
}
const socialSecurityPercentage = 0.062;
const medicarePercentage = 0.0145;
const socialSecurityTax = income * socialSecurityPercentage;
const medicareTax = income * medicarePercentage;
const standardDeduction = 12200;
const taxableIncome = income > standardDeduction ? income - standardDeduction : 0;
const taxPerBracket = taxBrackets.map(({ above, below, rate }) => {
const percent = rate / 100.0;
if (taxableIncome > above) {
let taxableAtRate = 0;
if (taxableIncome > below) {
taxableAtRate = below - above;
} else {
taxableAtRate = taxableIncome - above;
}
const taxAtRate = taxableAtRate * percent;
return taxAtRate;
}
return 0;
});
// sum all tax per bracket
const totalBracketTax = taxPerBracket.reduce((previous, current) => previous + current, 0);
// All Taxes
const totalTax = totalBracketTax + socialSecurityTax + medicareTax;
return Math.floor(totalTax);
}
| 18.627907 | 93 | 0.612984 | 69 | 3 | 0 | 4 | 13 | 0 | 0 | 0 | 4 | 0 | 0 | 13 | 550 | 0.012727 | 0.023636 | 0 | 0 | 0 | 0 | 0.2 | 0.276815 | // https://www.debt.org/tax/brackets/
const taxBrackets = [
{
above: 0,
below: 9875,
rate: 10
},
{
above: 9876,
below: 40125,
rate: 12
},
{
above: 40126,
below: 85525,
rate: 22
},
{
above: 85526,
below: 163300,
rate: 24
},
{
above: 163301,
below: 207350,
rate: 32
},
{
above: 207351,
below: 518400,
rate: 35
},
{
above: 518401,
below: undefined,
rate: 37
}
];
export default function getTaxForIncome(income) {
if (income <= 0) {
return 0;
}
const socialSecurityPercentage = 0.062;
const medicarePercentage = 0.0145;
const socialSecurityTax = income * socialSecurityPercentage;
const medicareTax = income * medicarePercentage;
const standardDeduction = 12200;
const taxableIncome = income > standardDeduction ? income - standardDeduction : 0;
const taxPerBracket = taxBrackets.map(({ above, below, rate }) => {
const percent = rate / 100.0;
if (taxableIncome > above) {
let taxableAtRate = 0;
if (taxableIncome > below) {
taxableAtRate = below - above;
} else {
taxableAtRate = taxableIncome - above;
}
const taxAtRate = taxableAtRate * percent;
return taxAtRate;
}
return 0;
});
// sum all tax per bracket
const totalBracketTax = taxPerBracket.reduce((previous, current) => previous + current, 0);
// All Taxes
const totalTax = totalBracketTax + socialSecurityTax + medicareTax;
return Math.floor(totalTax);
}
|
109588fe8c889c93651e2a43e008d6e56d206dd4 | 1,866 | ts | TypeScript | src/lib/symbol-table.ts | zbennett10/hack-assembler | 49719fc65da550c8a857332dbbde8c0032b4db30 | [
"MIT"
] | null | null | null | src/lib/symbol-table.ts | zbennett10/hack-assembler | 49719fc65da550c8a857332dbbde8c0032b4db30 | [
"MIT"
] | 1 | 2022-01-22T12:25:08.000Z | 2022-01-22T12:25:08.000Z | src/lib/symbol-table.ts | zbennett10/hack-assembler | 49719fc65da550c8a857332dbbde8c0032b4db30 | [
"MIT"
] | null | null | null | class SymbolTable {
private symbolMap;
constructor() {
this.symbolMap = {
'ARG': '2',
'KBD': '24576',
'LCL': '1',
'SCREEN': '16384',
'SP': '0',
'THAT': '4',
'THIS': '3'
};
['R0', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7', 'R8', 'R9', 'R10', 'R11', 'R12', 'R13', 'R14', 'R15']
.forEach((r, idx) => this.symbolMap[r] = idx.toString());
}
public contains(symbol: string): boolean {
const match = this.symbolMap[symbol];
return match && typeof match === 'number';
}
public getAddress(symbol: string): number {
return this.symbolMap[symbol];
}
public buildTable(asmLines: string[]): void {
let currentMemoryAddr = 16;
let currentLineCount = -1;
asmLines.forEach(line => {
const cleanLine = line.replace(/\s/g, '');
if (/^\/\//.test(cleanLine)) {
return;
}
if (/^\(.*\)/.test(cleanLine)) { // We have encountered a label!
const label = cleanLine.replace('(', '').replace(')', '')
this.addEntry(label, currentLineCount);
return;
}
if (/^@[a-z]/.test(cleanLine)) { // We have encountered a variable
const symbol = cleanLine.replace('@', '');
if (!this.contains(symbol)) {
this.addEntry(symbol, currentMemoryAddr);
currentMemoryAddr++;
}
}
currentLineCount++;
});
}
private addEntry(symbol: string, address: number): void {
if (!this.symbolMap[symbol]) {
this.symbolMap[symbol] = address;
}
}
}
const hackSymbolTable = new SymbolTable(); // Ensure this is a singleton
export default hackSymbolTable; | 27.043478 | 109 | 0.484995 | 53 | 7 | 0 | 8 | 7 | 1 | 2 | 0 | 9 | 1 | 1 | 8 | 499 | 0.03006 | 0.014028 | 0.002004 | 0.002004 | 0.002004 | 0 | 0.391304 | 0.289165 | class SymbolTable {
private symbolMap;
constructor() {
this.symbolMap = {
'ARG': '2',
'KBD': '24576',
'LCL': '1',
'SCREEN': '16384',
'SP': '0',
'THAT': '4',
'THIS': '3'
};
['R0', 'R1', 'R2', 'R3', 'R4', 'R5', 'R6', 'R7', 'R8', 'R9', 'R10', 'R11', 'R12', 'R13', 'R14', 'R15']
.forEach((r, idx) => this.symbolMap[r] = idx.toString());
}
public contains(symbol) {
const match = this.symbolMap[symbol];
return match && typeof match === 'number';
}
public getAddress(symbol) {
return this.symbolMap[symbol];
}
public buildTable(asmLines) {
let currentMemoryAddr = 16;
let currentLineCount = -1;
asmLines.forEach(line => {
const cleanLine = line.replace(/\s/g, '');
if (/^\/\//.test(cleanLine)) {
return;
}
if (/^\(.*\)/.test(cleanLine)) { // We have encountered a label!
const label = cleanLine.replace('(', '').replace(')', '')
this.addEntry(label, currentLineCount);
return;
}
if (/^@[a-z]/.test(cleanLine)) { // We have encountered a variable
const symbol = cleanLine.replace('@', '');
if (!this.contains(symbol)) {
this.addEntry(symbol, currentMemoryAddr);
currentMemoryAddr++;
}
}
currentLineCount++;
});
}
private addEntry(symbol, address) {
if (!this.symbolMap[symbol]) {
this.symbolMap[symbol] = address;
}
}
}
const hackSymbolTable = new SymbolTable(); // Ensure this is a singleton
export default hackSymbolTable; |
cb14c7a279f215293358730312da69fac60347a7 | 1,939 | ts | TypeScript | src/index.ts | olyop/bem | 884251d4b5b6f343936ae4acd3a5ec4fe5fd85e0 | [
"MIT"
] | 1 | 2022-01-30T08:08:28.000Z | 2022-01-30T08:08:28.000Z | src/index.ts | olyop/bem | 884251d4b5b6f343936ae4acd3a5ec4fe5fd85e0 | [
"MIT"
] | null | null | null | src/index.ts | olyop/bem | 884251d4b5b6f343936ae4acd3a5ec4fe5fd85e0 | [
"MIT"
] | null | null | null | const isNull =
(val: unknown): val is null =>
val === null
const isString =
(val: unknown): val is string =>
typeof val === "string"
const isBoolean =
(val: unknown): val is boolean =>
typeof val === "boolean"
const isUndefined =
(val: unknown): val is undefined =>
val === undefined
const isUpperCase =
(x: string): boolean =>
x === x.toUpperCase()
const isEmpty =
(val: string | unknown[]) =>
val.length === 0
const normalizeInput =
(classNames: BEMInput[]): BEMClassType[] =>
classNames
.map(
className => {
if (isBoolean(className) || isNull(className) || isUndefined(className)) {
return { className: "", remove: true }
} else if (isString(className)) {
if (isEmpty(className)) {
return { className }
} else if (isUpperCase(className.charAt(0))) {
return { className, ignore: true }
} else {
return { className }
}
} else {
return className
}
},
)
const filterRemove =
(classNames: BEMClassType[]) =>
classNames.filter(({ remove }) => !remove)
const mapBEMValues =
(classNames: BEMClassType[], componentName: string) =>
classNames.map(
({ ignore, className }) => {
if (ignore) {
return className
} else if (isEmpty(componentName)) {
return className
} else if (isEmpty(className)) {
return componentName
} else {
return `${componentName}__${className}`
}
},
)
const joinToString =
(classNames: string[]) => (
isEmpty(classNames) ?
undefined :
classNames.join(" ")
)
export const createBEM =
(componentName: string) =>
(...classNames: BEMInput[]) =>
joinToString(
mapBEMValues(
filterRemove(
normalizeInput(classNames),
),
componentName,
),
)
export interface BEMClassType {
remove?: boolean,
ignore?: boolean,
className: string,
}
export type BEMInput =
BEMClassType | string | boolean | undefined | null | 21.076087 | 79 | 0.615266 | 80 | 15 | 0 | 16 | 11 | 3 | 10 | 0 | 18 | 2 | 2 | 5.533333 | 564 | 0.054965 | 0.019504 | 0.005319 | 0.003546 | 0.003546 | 0 | 0.4 | 0.36964 | /* Example usages of 'isNull' are shown below:
isBoolean(className) || isNull(className) || isUndefined(className);
*/
const isNull =
(val): val is null =>
val === null
/* Example usages of 'isString' are shown below:
isString(className);
*/
const isString =
(val): val is string =>
typeof val === "string"
/* Example usages of 'isBoolean' are shown below:
isBoolean(className) || isNull(className) || isUndefined(className);
*/
const isBoolean =
(val): val is boolean =>
typeof val === "boolean"
/* Example usages of 'isUndefined' are shown below:
isBoolean(className) || isNull(className) || isUndefined(className);
*/
const isUndefined =
(val): val is undefined =>
val === undefined
/* Example usages of 'isUpperCase' are shown below:
isUpperCase(className.charAt(0));
*/
const isUpperCase =
(x) =>
x === x.toUpperCase()
/* Example usages of 'isEmpty' are shown below:
isEmpty(className);
isEmpty(componentName);
isEmpty(classNames) ?
undefined :
classNames.join(" ");
*/
const isEmpty =
(val) =>
val.length === 0
/* Example usages of 'normalizeInput' are shown below:
joinToString(mapBEMValues(filterRemove(normalizeInput(classNames)), componentName));
*/
const normalizeInput =
(classNames) =>
classNames
.map(
className => {
if (isBoolean(className) || isNull(className) || isUndefined(className)) {
return { className: "", remove: true }
} else if (isString(className)) {
if (isEmpty(className)) {
return { className }
} else if (isUpperCase(className.charAt(0))) {
return { className, ignore: true }
} else {
return { className }
}
} else {
return className
}
},
)
/* Example usages of 'filterRemove' are shown below:
joinToString(mapBEMValues(filterRemove(normalizeInput(classNames)), componentName));
*/
const filterRemove =
(classNames) =>
classNames.filter(({ remove }) => !remove)
/* Example usages of 'mapBEMValues' are shown below:
joinToString(mapBEMValues(filterRemove(normalizeInput(classNames)), componentName));
*/
const mapBEMValues =
(classNames, componentName) =>
classNames.map(
({ ignore, className }) => {
if (ignore) {
return className
} else if (isEmpty(componentName)) {
return className
} else if (isEmpty(className)) {
return componentName
} else {
return `${componentName}__${className}`
}
},
)
/* Example usages of 'joinToString' are shown below:
joinToString(mapBEMValues(filterRemove(normalizeInput(classNames)), componentName));
*/
const joinToString =
(classNames) => (
isEmpty(classNames) ?
undefined :
classNames.join(" ")
)
export const createBEM =
(componentName) =>
(...classNames) =>
joinToString(
mapBEMValues(
filterRemove(
normalizeInput(classNames),
),
componentName,
),
)
export interface BEMClassType {
remove?,
ignore?,
className,
}
export type BEMInput =
BEMClassType | string | boolean | undefined | null |
cb23f480dff3dcb0638a04477e44d04d09b484bd | 1,785 | ts | TypeScript | src/analyze-trace-options.ts | AlexRogalskiy/typescript-analyze-trace | e702ef05efb0f5afe25a34b851a39e77fe3e4d8f | [
"MIT"
] | 138 | 2022-01-15T01:24:17.000Z | 2022-03-30T13:26:55.000Z | src/analyze-trace-options.ts | microsoft/typescript-analyze-trace | e702ef05efb0f5afe25a34b851a39e77fe3e4d8f | [
"MIT"
] | 16 | 2022-01-14T22:28:03.000Z | 2022-03-12T01:26:10.000Z | src/analyze-trace-options.ts | AlexRogalskiy/typescript-analyze-trace | e702ef05efb0f5afe25a34b851a39e77fe3e4d8f | [
"MIT"
] | 9 | 2022-01-17T17:26:18.000Z | 2022-03-30T01:29:13.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export const commandLineOptions = {
"forceMillis": {
alias: ["forcemillis", "force-millis"],
describe: "Events of at least this duration (in milliseconds) will reported unconditionally",
type: "number",
default: 500,
},
"skipMillis": {
alias: ["skipmillis", "skip-millis"],
describe: "Events of less than this duration (in milliseconds) will suppressed unconditionally",
type: "number",
default: 100,
},
"expandTypes": {
alias: ["expandtypes", "expand-types"],
describe: "Expand types when printing",
type: "boolean",
default: true,
},
"color": {
describe: "Color the output to make it easier to read",
type: "boolean",
default: true,
},
"json": {
describe: "Produce JSON output for programmatic consumption (EXPERIMENTAL)",
type: "boolean",
default: false,
},
} as const;
// Replicating the type inference in yargs would be excessive
type Argv = {
forceMillis: number,
skipMillis: number,
expandTypes: boolean,
color: boolean,
json: boolean,
};
export function checkCommandLineOptions(argv: Argv): true {
if (argv.forceMillis < argv.skipMillis) {
throw new Error("forceMillis cannot be less than skipMillis")
}
return true;
}
export function pushCommandLineOptions(array: string[], argv: Argv): void {
array.push(
"--force-millis", `${argv.forceMillis}`,
"--skip-millis", `${argv.skipMillis}`,
argv.expandTypes ? "--expand-types" : "--no-expand-types",
argv.color ? "--color" : "--no-color",
argv.json ? "--json" : "--no-json",
);
}
| 29.75 | 104 | 0.603922 | 52 | 2 | 0 | 3 | 1 | 5 | 0 | 0 | 7 | 1 | 1 | 5.5 | 447 | 0.011186 | 0.002237 | 0.011186 | 0.002237 | 0.002237 | 0 | 0.636364 | 0.20595 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export const commandLineOptions = {
"forceMillis": {
alias: ["forcemillis", "force-millis"],
describe: "Events of at least this duration (in milliseconds) will reported unconditionally",
type: "number",
default: 500,
},
"skipMillis": {
alias: ["skipmillis", "skip-millis"],
describe: "Events of less than this duration (in milliseconds) will suppressed unconditionally",
type: "number",
default: 100,
},
"expandTypes": {
alias: ["expandtypes", "expand-types"],
describe: "Expand types when printing",
type: "boolean",
default: true,
},
"color": {
describe: "Color the output to make it easier to read",
type: "boolean",
default: true,
},
"json": {
describe: "Produce JSON output for programmatic consumption (EXPERIMENTAL)",
type: "boolean",
default: false,
},
} as const;
// Replicating the type inference in yargs would be excessive
type Argv = {
forceMillis,
skipMillis,
expandTypes,
color,
json,
};
export function checkCommandLineOptions(argv) {
if (argv.forceMillis < argv.skipMillis) {
throw new Error("forceMillis cannot be less than skipMillis")
}
return true;
}
export function pushCommandLineOptions(array, argv) {
array.push(
"--force-millis", `${argv.forceMillis}`,
"--skip-millis", `${argv.skipMillis}`,
argv.expandTypes ? "--expand-types" : "--no-expand-types",
argv.color ? "--color" : "--no-color",
argv.json ? "--json" : "--no-json",
);
}
|
cb3bd9a971a3dd45d4638abf35631445d21184c6 | 1,419 | ts | TypeScript | typescript/src/libs/binary_tree.ts | eteplus/leetcode | 13cb7aac323dd68c670b1548a8d72667eb68bd7c | [
"MIT"
] | 1 | 2022-01-25T09:03:59.000Z | 2022-01-25T09:03:59.000Z | typescript/src/libs/binary_tree.ts | eteplus/leetcode | 13cb7aac323dd68c670b1548a8d72667eb68bd7c | [
"MIT"
] | null | null | null | typescript/src/libs/binary_tree.ts | eteplus/leetcode | 13cb7aac323dd68c670b1548a8d72667eb68bd7c | [
"MIT"
] | null | null | null | /**
* Definition for a binary tree node.
*/
export class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
}
export function createBinaryTree(nums: Array<number | null>, index: number): TreeNode | null {
if (index < nums.length) {
const val = nums[index];
if (val === null) {
return null;
}
const node = new TreeNode(val);
node.left = createBinaryTree(nums, index * 2 + 1);
node.right = createBinaryTree(nums, index * 2 + 2);
return node;
}
return null;
}
export function findNode(root: TreeNode | null, val: number): TreeNode | null {
if (root === null) {
return null;
}
if (root.val === val) {
return root;
}
const left = findNode(root.left, val);
if (left) {
return left;
}
return findNode(root.right, val);
}
export function parseBinaryTree(root: TreeNode | null): Array<Number | null> {
if (root === null) {
return [];
}
const result: Array<Number | null> = [];
const traverse = (node: TreeNode | null) => {
if (node === null) {
return;
}
result.push(node.val);
traverse(node.left);
traverse(node.right);
}
traverse(root);
return result;
}
| 24.050847 | 94 | 0.603946 | 52 | 5 | 0 | 9 | 5 | 3 | 3 | 0 | 5 | 1 | 0 | 9 | 413 | 0.033898 | 0.012107 | 0.007264 | 0.002421 | 0 | 0 | 0.227273 | 0.293317 | /**
* Definition for a binary tree node.
*/
export class TreeNode {
val;
left;
right;
constructor(val?, left?, right?) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
}
export /* Example usages of 'createBinaryTree' are shown below:
node.left = createBinaryTree(nums, index * 2 + 1);
node.right = createBinaryTree(nums, index * 2 + 2);
*/
function createBinaryTree(nums, index) {
if (index < nums.length) {
const val = nums[index];
if (val === null) {
return null;
}
const node = new TreeNode(val);
node.left = createBinaryTree(nums, index * 2 + 1);
node.right = createBinaryTree(nums, index * 2 + 2);
return node;
}
return null;
}
export /* Example usages of 'findNode' are shown below:
findNode(root.left, val);
findNode(root.right, val);
*/
function findNode(root, val) {
if (root === null) {
return null;
}
if (root.val === val) {
return root;
}
const left = findNode(root.left, val);
if (left) {
return left;
}
return findNode(root.right, val);
}
export function parseBinaryTree(root) {
if (root === null) {
return [];
}
const result = [];
/* Example usages of 'traverse' are shown below:
traverse(node.left);
traverse(node.right);
traverse(root);
*/
const traverse = (node) => {
if (node === null) {
return;
}
result.push(node.val);
traverse(node.left);
traverse(node.right);
}
traverse(root);
return result;
}
|
cb4740ebaff249e3fd3fae4fc531be634a8f3b45 | 2,129 | ts | TypeScript | browser/path.ts | internet-of-presence/rollup | b8315e03f9790d610a413316fbf6d565f9340cab | [
"0BSD",
"MIT"
] | 1 | 2022-03-18T15:21:33.000Z | 2022-03-18T15:21:33.000Z | browser/path.ts | internet-of-presence/rollup | b8315e03f9790d610a413316fbf6d565f9340cab | [
"0BSD",
"MIT"
] | 1 | 2022-03-23T10:02:41.000Z | 2022-03-23T10:02:41.000Z | browser/path.ts | internet-of-presence/rollup | b8315e03f9790d610a413316fbf6d565f9340cab | [
"0BSD",
"MIT"
] | null | null | null | const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
const RELATIVE_PATH_REGEX = /^\.?\.\//;
const ALL_BACKSLASHES_REGEX = /\\/g;
const ANY_SLASH_REGEX = /[/\\]/;
const EXTNAME_REGEX = /\.[^.]+$/;
export function isAbsolute(path: string): boolean {
return ABSOLUTE_PATH_REGEX.test(path);
}
export function isRelative(path: string): boolean {
return RELATIVE_PATH_REGEX.test(path);
}
export function normalize(path: string): string {
return path.replace(ALL_BACKSLASHES_REGEX, '/');
}
export function basename(path: string): string {
return path.split(ANY_SLASH_REGEX).pop() || '';
}
export function dirname(path: string): string {
const match = /[/\\][^/\\]*$/.exec(path);
if (!match) return '.';
const dir = path.slice(0, -match[0].length);
// If `dir` is the empty string, we're at root.
return dir ? dir : '/';
}
export function extname(path: string): string {
const match = EXTNAME_REGEX.exec(basename(path)!);
return match ? match[0] : '';
}
export function relative(from: string, to: string): string {
const fromParts = from.split(ANY_SLASH_REGEX).filter(Boolean);
const toParts = to.split(ANY_SLASH_REGEX).filter(Boolean);
if (fromParts[0] === '.') fromParts.shift();
if (toParts[0] === '.') toParts.shift();
while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
fromParts.shift();
toParts.shift();
}
while (toParts[0] === '..' && fromParts.length > 0) {
toParts.shift();
fromParts.pop();
}
while (fromParts.pop()) {
toParts.unshift('..');
}
return toParts.join('/');
}
export function resolve(...paths: string[]): string {
const firstPathSegment = paths.shift();
if (!firstPathSegment) {
return '/';
}
let resolvedParts = firstPathSegment.split(ANY_SLASH_REGEX);
for (const path of paths) {
if (isAbsolute(path)) {
resolvedParts = path.split(ANY_SLASH_REGEX);
} else {
const parts = path.split(ANY_SLASH_REGEX);
while (parts[0] === '.' || parts[0] === '..') {
const part = parts.shift();
if (part === '..') {
resolvedParts.pop();
}
}
resolvedParts.push(...parts);
}
}
return resolvedParts.join('/');
}
| 24.193182 | 68 | 0.641146 | 67 | 8 | 0 | 9 | 14 | 0 | 2 | 0 | 17 | 0 | 0 | 5.75 | 722 | 0.023546 | 0.019391 | 0 | 0 | 0 | 0 | 0.548387 | 0.288295 | const ABSOLUTE_PATH_REGEX = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
const RELATIVE_PATH_REGEX = /^\.?\.\//;
const ALL_BACKSLASHES_REGEX = /\\/g;
const ANY_SLASH_REGEX = /[/\\]/;
const EXTNAME_REGEX = /\.[^.]+$/;
export /* Example usages of 'isAbsolute' are shown below:
isAbsolute(path);
*/
function isAbsolute(path) {
return ABSOLUTE_PATH_REGEX.test(path);
}
export function isRelative(path) {
return RELATIVE_PATH_REGEX.test(path);
}
export function normalize(path) {
return path.replace(ALL_BACKSLASHES_REGEX, '/');
}
export /* Example usages of 'basename' are shown below:
basename(path);
*/
function basename(path) {
return path.split(ANY_SLASH_REGEX).pop() || '';
}
export function dirname(path) {
const match = /[/\\][^/\\]*$/.exec(path);
if (!match) return '.';
const dir = path.slice(0, -match[0].length);
// If `dir` is the empty string, we're at root.
return dir ? dir : '/';
}
export function extname(path) {
const match = EXTNAME_REGEX.exec(basename(path)!);
return match ? match[0] : '';
}
export function relative(from, to) {
const fromParts = from.split(ANY_SLASH_REGEX).filter(Boolean);
const toParts = to.split(ANY_SLASH_REGEX).filter(Boolean);
if (fromParts[0] === '.') fromParts.shift();
if (toParts[0] === '.') toParts.shift();
while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
fromParts.shift();
toParts.shift();
}
while (toParts[0] === '..' && fromParts.length > 0) {
toParts.shift();
fromParts.pop();
}
while (fromParts.pop()) {
toParts.unshift('..');
}
return toParts.join('/');
}
export function resolve(...paths) {
const firstPathSegment = paths.shift();
if (!firstPathSegment) {
return '/';
}
let resolvedParts = firstPathSegment.split(ANY_SLASH_REGEX);
for (const path of paths) {
if (isAbsolute(path)) {
resolvedParts = path.split(ANY_SLASH_REGEX);
} else {
const parts = path.split(ANY_SLASH_REGEX);
while (parts[0] === '.' || parts[0] === '..') {
const part = parts.shift();
if (part === '..') {
resolvedParts.pop();
}
}
resolvedParts.push(...parts);
}
}
return resolvedParts.join('/');
}
|
cb600562dd4aeb9806486ad766958ebfef78cc9c | 1,731 | ts | TypeScript | packages/nebula/src/fusion/zipFusionAlgorithm.ts | Akimotorakiyu/Moonman | ac1a385f5ddf4750d2ad585b0c5074f6ee28c919 | [
"MIT"
] | 2 | 2022-03-12T14:52:31.000Z | 2022-03-13T00:48:51.000Z | packages/nebula/src/fusion/zipFusionAlgorithm.ts | Akimotorakiyu/Moonman | ac1a385f5ddf4750d2ad585b0c5074f6ee28c919 | [
"MIT"
] | null | null | null | packages/nebula/src/fusion/zipFusionAlgorithm.ts | Akimotorakiyu/Moonman | ac1a385f5ddf4750d2ad585b0c5074f6ee28c919 | [
"MIT"
] | null | null | null | export function zipFusion<T>(
side1: T[],
side2: T[],
compare: (value1: T, value2: T) => number,
): T[] {
let side1CurrentIndex = 0
let side2CurrentIndex = 0
const newArray = []
while (side1CurrentIndex < side1.length && side2CurrentIndex < side2.length) {
const side1Value = side1[side1CurrentIndex]
const side2Value = side2[side2CurrentIndex]
if (compare(side1Value, side2Value) > 0) {
newArray.push(side1Value)
side1CurrentIndex++
} else if (compare(side1Value, side2Value) < 0) {
newArray.push(side2Value)
side2CurrentIndex++
} else {
newArray.push(side1Value)
side1CurrentIndex++
side2CurrentIndex++
}
}
newArray.push(
...side1.slice(side1CurrentIndex),
...side2.slice(side2CurrentIndex),
)
return newArray
}
// 因为新的操作更多场景出现,所以反向操作在 side2 数量少的时候会需要更少次数的对比
export function zipFusionR<T>(
side1: T[],
side2: T[],
compare: (value1: T, value2: T) => number,
): T[] {
let side1CurrentIndex = side1.length - 1
let side2CurrentIndex = side2.length - 1
const newArray = []
while (side1CurrentIndex > -1 && side2CurrentIndex > -1) {
const side1Value = side1[side1CurrentIndex]
const side2Value = side2[side2CurrentIndex]
if (compare(side1Value, side2Value) > 0) {
newArray.push(side2Value)
side2CurrentIndex--
} else if (compare(side1Value, side2Value) < 0) {
newArray.push(side1Value)
side1CurrentIndex--
} else {
newArray.push(side1Value)
side1CurrentIndex--
side2CurrentIndex--
}
}
newArray.push(
...side1.slice(side1CurrentIndex).reverse(),
...side2.slice(side2CurrentIndex).reverse(),
)
newArray.reverse()
return newArray
}
| 23.712329 | 80 | 0.66089 | 59 | 2 | 0 | 6 | 10 | 0 | 0 | 0 | 2 | 0 | 0 | 23.5 | 549 | 0.014572 | 0.018215 | 0 | 0 | 0 | 0 | 0.111111 | 0.263579 | export function zipFusion<T>(
side1,
side2,
compare,
) {
let side1CurrentIndex = 0
let side2CurrentIndex = 0
const newArray = []
while (side1CurrentIndex < side1.length && side2CurrentIndex < side2.length) {
const side1Value = side1[side1CurrentIndex]
const side2Value = side2[side2CurrentIndex]
if (compare(side1Value, side2Value) > 0) {
newArray.push(side1Value)
side1CurrentIndex++
} else if (compare(side1Value, side2Value) < 0) {
newArray.push(side2Value)
side2CurrentIndex++
} else {
newArray.push(side1Value)
side1CurrentIndex++
side2CurrentIndex++
}
}
newArray.push(
...side1.slice(side1CurrentIndex),
...side2.slice(side2CurrentIndex),
)
return newArray
}
// 因为新的操作更多场景出现,所以反向操作在 side2 数量少的时候会需要更少次数的对比
export function zipFusionR<T>(
side1,
side2,
compare,
) {
let side1CurrentIndex = side1.length - 1
let side2CurrentIndex = side2.length - 1
const newArray = []
while (side1CurrentIndex > -1 && side2CurrentIndex > -1) {
const side1Value = side1[side1CurrentIndex]
const side2Value = side2[side2CurrentIndex]
if (compare(side1Value, side2Value) > 0) {
newArray.push(side2Value)
side2CurrentIndex--
} else if (compare(side1Value, side2Value) < 0) {
newArray.push(side1Value)
side1CurrentIndex--
} else {
newArray.push(side1Value)
side1CurrentIndex--
side2CurrentIndex--
}
}
newArray.push(
...side1.slice(side1CurrentIndex).reverse(),
...side2.slice(side2CurrentIndex).reverse(),
)
newArray.reverse()
return newArray
}
|
e91a96aa1ed7352799ddb4e0d1ecdd24fe548d74 | 8,851 | ts | TypeScript | src/Text.ts | ClintH/ixfx | 71ae665900fdc607cd013e330fde3fb68c4db119 | [
"MIT"
] | 2 | 2022-03-25T13:13:57.000Z | 2022-03-25T13:29:10.000Z | src/Text.ts | ClintH/ixfx | 71ae665900fdc607cd013e330fde3fb68c4db119 | [
"MIT"
] | null | null | null | src/Text.ts | ClintH/ixfx | 71ae665900fdc607cd013e330fde3fb68c4db119 | [
"MIT"
] | null | null | null | /**
* Returns source text that is between `start` and `end` match strings. Returns _undefined_ if start/end is not found.
*
* ```js
* // Yields ` orange `;
* between(`apple orange melon`, `apple`, `melon`);
* ```
* @param source Source text
* @param start Start match
* @param end If undefined, `start` will be used instead
* @param lastEndMatch If true, looks for the last match of `end` (default). If false, looks for the first match.
* @returns
*/
export const between = (source: string, start: string, end?: string, lastEndMatch = true): string | undefined => {
const startPos = source.indexOf(start);
if (startPos < 0) return;
if (end === undefined) end = start;
const endPos = lastEndMatch ? source.lastIndexOf(end) : source.indexOf(end, startPos+1);
if (endPos < 0) return;
return source.substring(startPos+1, endPos);
};
/**
* Returns first position of the given character code, or -1 if not found.
* @param source Source string
* @param code Code to seek
* @param start Start index, 0 by default
* @param end End index (inclusive), source.length-1 by default
* @returns Found position, or -1 if not found
*/
export const indexOfCharCode = (source:string, code:number, start = 0, end = source.length-1):number => {
//eslint-disable-next-line functional/no-loop-statement,functional/no-let
for (let i=start;i<=end;i++) {
if (source.charCodeAt(i) === code) return i;
}
return -1;
};
/**
* Returns `source` with chars removed at `removeStart` position
* ```js
* omitChars(`hello there`, 1, 3);
* // Yields: `ho there`
* ```
* @param source
* @param removeStart Start point to remove
* @param removeLength Number of characters to remove
* @returns
*/
export const omitChars = (source:string, removeStart:number, removeLength:number) => source.substring(0, removeStart) + source.substring(removeStart+removeLength);
/**
* Splits a string into `length`-size chunks.
*
* If `length` is greater than the length of `source`, a single element array is returned with source.
* The final array element may be smaller if we ran out of characters.
*
* ```js
* splitByLength(`hello there`, 2);
* // Yields:
* // [`he`, `ll`, `o `, `th`, `er`, `e`]
* ```
* @param source Source string
* @param length Length of each chunk
* @returns
*/
export const splitByLength = (source:string, length:number):readonly string[] => {
const chunks = Math.ceil(source.length/length);
const ret:string[] = [];
//eslint-disable-next-line functional/no-let
let start = 0;
//eslint-disable-next-line functional/no-loop-statement,functional/no-let
for (let c=0;c<chunks;c++) {
//eslint-disable-next-line functional/immutable-data
ret.push(source.substring(start, start+length));
start += length;
}
return ret;
};
/**
* Returns the `source` string up until (and excluding) `match`. If match is not
* found, all of `source` is returned.
*
* ```js
* // Yields `apple `
* untilMarch(`apple orange melon`, `orange`);
* ```
* @param source
* @param match
* @param startPos If provided, gives the starting offset. Default 0
*/
export const untilMatch = (source:string, match:string, startPos = 0):string => {
if (startPos > source.length) throw new Error(`startPos should be less than length`);
const m = source.indexOf(match, startPos);
if (m < 0) return source;
return source.substring(startPos, m);
};
/**
* 'Unwraps' a string, removing one or more 'wrapper' strings that it starts and ends with.
* ```js
* unwrap("'hello'", "'"); // hello
* unwrap("apple", "a"); // apple
* unwrap("wow", "w"); // o
* unwrap(`"'blah'"`, '"', "'"); // blah
* ```
* @param source
* @param wrappers
* @returns
*/
export const unwrap = (source: string, ...wrappers: readonly string[]): string => {
//eslint-disable-next-line functional/no-let
let matched = false;
//eslint-disable-next-line functional/no-loop-statement
do {
matched = false;
//eslint-disable-next-line functional/no-loop-statement
for (const w of wrappers) {
if (source.startsWith(w) && source.endsWith(w)) {
source = source.substring(w.length, source.length - (w.length * 2) + 1);
matched = true;
}
}
} while (matched);
return source;
};
/**
* A range
*/
export type Range = {
/**
* Text of range
*/
readonly text: string
/**
* Start position, with respect to source text
*/
readonly start: number
/**
* End position, with respect to source text
*/
readonly end: number
/**
* Index of range. First range is 0
*/
readonly index: number
}
export type LineSpan = {
readonly start: number
readonly end: number
readonly length: number
}
/**
* Calculates the span, defined in {@link Range} indexes, that includes `start` through to `end` character positions.
*
* After using {@link splitRanges} to split text, `lineSpan` is used to associate some text coordinates with ranges.
*
* @param ranges Ranges
* @param start Start character position, in source text reference
* @param end End character position, in source text reference
* @returns Span
*/
export const lineSpan = (ranges: readonly Range[], start: number, end: number): LineSpan => {
//eslint-disable-next-line functional/no-let
let s = -1;
//eslint-disable-next-line functional/no-let
let e = -1;
//eslint-disable-next-line functional/no-loop-statement,functional/no-let
for (let i = 0; i < ranges.length; i++) {
const r = ranges[i];
s = i;
if (r.text.length === 0) continue;
if (start < r.end) {
break;
}
}
//eslint-disable-next-line functional/no-loop-statement,functional/no-let
for (let i = s; i < ranges.length; i++) {
const r = ranges[i];
e = i;
if (end === r.end) {
e = i + 1;
break;
}
if (end < r.end) {
break;
}
}
return {length: e - s, start: s, end: e};
};
/**
* Splits a source string into ranges:
* ```js
* const ranges = splitRanges("hello;there;fella", ";");
* ```
*
* Each range consists of:
* ```js
* {
* text: string - the text of range
* start: number - start pos of range, wrt to source
* end: number - end pos of range, wrt to source
* index: number - index of range (starting at 0)
* }
* ```
* @param source
* @param split
* @returns
*/
export const splitRanges = (source: string, split: string):readonly Range[] => {
//eslint-disable-next-line functional/no-let
let start = 0;
//eslint-disable-next-line functional/no-let
let text = ``;
const ranges: Range[] = [];
//eslint-disable-next-line functional/no-let
let index = 0;
//eslint-disable-next-line functional/no-loop-statement,functional/no-let
for (let i = 0; i < source.length; i++) {
if (source.indexOf(split, i) === i) {
//eslint-disable-next-line functional/no-let
const end = i;
//eslint-disable-next-line functional/immutable-data
ranges.push({
text, start, end, index
});
start = end + 1;
text = ``;
index++;
} else {
text += source.charAt(i);
}
}
if (start < source.length) {
//eslint-disable-next-line functional/immutable-data
ranges.push({text, start, index, end: source.length});
}
return ranges;
};
/**
* Counts the number of times one of `chars` appears at the front of
* a string, contiguously.
*
* ```js
* countCharsFromStart(` hi`, ` `); // 2
* countCharsFromStart(`hi `, ` `); // 0
* countCharsFromStart(` hi `, ` `); // 2
* ```
* @param source
* @param chars
* @returns
*/
export const countCharsFromStart = (source: string, ...chars: readonly string[]): number => {
//eslint-disable-next-line functional/no-let
let counted = 0;
//eslint-disable-next-line functional/no-loop-statement,functional/no-let
for (let i = 0; i < source.length; i++) {
if (chars.includes(source.charAt(i))) {
counted++;
} else {
break;
}
}
return counted;
};
/**
* Returns _true_ if `source` starts and ends with `start` and `end`. Case-sensitive.
* If _end_ is omitted, the the `start` value will be used.
*
* ```js
* startsEnds(`This is a string`, `This`, `string`); // True
* startsEnds(`This is a string`, `is`, `a`); // False
* starsEnds(`test`, `t`); // True, starts and ends with 't'
* ```
* @param source String to search within
* @param start Start
* @param end End (if omitted, start will be looked for at end as well)
* @returns True if source starts and ends with provided values.
*/
export const startsEnds = (source:string, start:string, end:string = start):boolean => source.startsWith(start) && source.endsWith(end);
//eslint-disable-next-line no-useless-escape
export const htmlEntities = (source:string):string => source.replace(/[\u00A0-\u9999<>\&]/g, i => `&#${i.charCodeAt(0)};`); | 29.801347 | 164 | 0.63812 | 115 | 12 | 0 | 30 | 34 | 7 | 0 | 0 | 40 | 2 | 0 | 7.416667 | 2,605 | 0.016123 | 0.013052 | 0.002687 | 0.000768 | 0 | 0 | 0.481928 | 0.251024 | /**
* Returns source text that is between `start` and `end` match strings. Returns _undefined_ if start/end is not found.
*
* ```js
* // Yields ` orange `;
* between(`apple orange melon`, `apple`, `melon`);
* ```
* @param source Source text
* @param start Start match
* @param end If undefined, `start` will be used instead
* @param lastEndMatch If true, looks for the last match of `end` (default). If false, looks for the first match.
* @returns
*/
export const between = (source, start, end?, lastEndMatch = true) => {
const startPos = source.indexOf(start);
if (startPos < 0) return;
if (end === undefined) end = start;
const endPos = lastEndMatch ? source.lastIndexOf(end) : source.indexOf(end, startPos+1);
if (endPos < 0) return;
return source.substring(startPos+1, endPos);
};
/**
* Returns first position of the given character code, or -1 if not found.
* @param source Source string
* @param code Code to seek
* @param start Start index, 0 by default
* @param end End index (inclusive), source.length-1 by default
* @returns Found position, or -1 if not found
*/
export const indexOfCharCode = (source, code, start = 0, end = source.length-1) => {
//eslint-disable-next-line functional/no-loop-statement,functional/no-let
for (let i=start;i<=end;i++) {
if (source.charCodeAt(i) === code) return i;
}
return -1;
};
/**
* Returns `source` with chars removed at `removeStart` position
* ```js
* omitChars(`hello there`, 1, 3);
* // Yields: `ho there`
* ```
* @param source
* @param removeStart Start point to remove
* @param removeLength Number of characters to remove
* @returns
*/
export const omitChars = (source, removeStart, removeLength) => source.substring(0, removeStart) + source.substring(removeStart+removeLength);
/**
* Splits a string into `length`-size chunks.
*
* If `length` is greater than the length of `source`, a single element array is returned with source.
* The final array element may be smaller if we ran out of characters.
*
* ```js
* splitByLength(`hello there`, 2);
* // Yields:
* // [`he`, `ll`, `o `, `th`, `er`, `e`]
* ```
* @param source Source string
* @param length Length of each chunk
* @returns
*/
export const splitByLength = (source, length) => {
const chunks = Math.ceil(source.length/length);
const ret = [];
//eslint-disable-next-line functional/no-let
let start = 0;
//eslint-disable-next-line functional/no-loop-statement,functional/no-let
for (let c=0;c<chunks;c++) {
//eslint-disable-next-line functional/immutable-data
ret.push(source.substring(start, start+length));
start += length;
}
return ret;
};
/**
* Returns the `source` string up until (and excluding) `match`. If match is not
* found, all of `source` is returned.
*
* ```js
* // Yields `apple `
* untilMarch(`apple orange melon`, `orange`);
* ```
* @param source
* @param match
* @param startPos If provided, gives the starting offset. Default 0
*/
export const untilMatch = (source, match, startPos = 0) => {
if (startPos > source.length) throw new Error(`startPos should be less than length`);
const m = source.indexOf(match, startPos);
if (m < 0) return source;
return source.substring(startPos, m);
};
/**
* 'Unwraps' a string, removing one or more 'wrapper' strings that it starts and ends with.
* ```js
* unwrap("'hello'", "'"); // hello
* unwrap("apple", "a"); // apple
* unwrap("wow", "w"); // o
* unwrap(`"'blah'"`, '"', "'"); // blah
* ```
* @param source
* @param wrappers
* @returns
*/
export const unwrap = (source, ...wrappers) => {
//eslint-disable-next-line functional/no-let
let matched = false;
//eslint-disable-next-line functional/no-loop-statement
do {
matched = false;
//eslint-disable-next-line functional/no-loop-statement
for (const w of wrappers) {
if (source.startsWith(w) && source.endsWith(w)) {
source = source.substring(w.length, source.length - (w.length * 2) + 1);
matched = true;
}
}
} while (matched);
return source;
};
/**
* A range
*/
export type Range = {
/**
* Text of range
*/
readonly text
/**
* Start position, with respect to source text
*/
readonly start
/**
* End position, with respect to source text
*/
readonly end
/**
* Index of range. First range is 0
*/
readonly index
}
export type LineSpan = {
readonly start
readonly end
readonly length
}
/**
* Calculates the span, defined in {@link Range} indexes, that includes `start` through to `end` character positions.
*
* After using {@link splitRanges} to split text, `lineSpan` is used to associate some text coordinates with ranges.
*
* @param ranges Ranges
* @param start Start character position, in source text reference
* @param end End character position, in source text reference
* @returns Span
*/
export const lineSpan = (ranges, start, end) => {
//eslint-disable-next-line functional/no-let
let s = -1;
//eslint-disable-next-line functional/no-let
let e = -1;
//eslint-disable-next-line functional/no-loop-statement,functional/no-let
for (let i = 0; i < ranges.length; i++) {
const r = ranges[i];
s = i;
if (r.text.length === 0) continue;
if (start < r.end) {
break;
}
}
//eslint-disable-next-line functional/no-loop-statement,functional/no-let
for (let i = s; i < ranges.length; i++) {
const r = ranges[i];
e = i;
if (end === r.end) {
e = i + 1;
break;
}
if (end < r.end) {
break;
}
}
return {length: e - s, start: s, end: e};
};
/**
* Splits a source string into ranges:
* ```js
* const ranges = splitRanges("hello;there;fella", ";");
* ```
*
* Each range consists of:
* ```js
* {
* text: string - the text of range
* start: number - start pos of range, wrt to source
* end: number - end pos of range, wrt to source
* index: number - index of range (starting at 0)
* }
* ```
* @param source
* @param split
* @returns
*/
export const splitRanges = (source, split) => {
//eslint-disable-next-line functional/no-let
let start = 0;
//eslint-disable-next-line functional/no-let
let text = ``;
const ranges = [];
//eslint-disable-next-line functional/no-let
let index = 0;
//eslint-disable-next-line functional/no-loop-statement,functional/no-let
for (let i = 0; i < source.length; i++) {
if (source.indexOf(split, i) === i) {
//eslint-disable-next-line functional/no-let
const end = i;
//eslint-disable-next-line functional/immutable-data
ranges.push({
text, start, end, index
});
start = end + 1;
text = ``;
index++;
} else {
text += source.charAt(i);
}
}
if (start < source.length) {
//eslint-disable-next-line functional/immutable-data
ranges.push({text, start, index, end: source.length});
}
return ranges;
};
/**
* Counts the number of times one of `chars` appears at the front of
* a string, contiguously.
*
* ```js
* countCharsFromStart(` hi`, ` `); // 2
* countCharsFromStart(`hi `, ` `); // 0
* countCharsFromStart(` hi `, ` `); // 2
* ```
* @param source
* @param chars
* @returns
*/
export const countCharsFromStart = (source, ...chars) => {
//eslint-disable-next-line functional/no-let
let counted = 0;
//eslint-disable-next-line functional/no-loop-statement,functional/no-let
for (let i = 0; i < source.length; i++) {
if (chars.includes(source.charAt(i))) {
counted++;
} else {
break;
}
}
return counted;
};
/**
* Returns _true_ if `source` starts and ends with `start` and `end`. Case-sensitive.
* If _end_ is omitted, the the `start` value will be used.
*
* ```js
* startsEnds(`This is a string`, `This`, `string`); // True
* startsEnds(`This is a string`, `is`, `a`); // False
* starsEnds(`test`, `t`); // True, starts and ends with 't'
* ```
* @param source String to search within
* @param start Start
* @param end End (if omitted, start will be looked for at end as well)
* @returns True if source starts and ends with provided values.
*/
export const startsEnds = (source, start, end = start) => source.startsWith(start) && source.endsWith(end);
//eslint-disable-next-line no-useless-escape
export const htmlEntities = (source) => source.replace(/[\u00A0-\u9999<>\&]/g, i => `&#${i.charCodeAt(0)};`); |
e92848efdb8efe2325f8d32ba61a54d2b22ab4fe | 2,517 | ts | TypeScript | src/lib/util/colors.ts | cosmicplayground/cosmicplayground | 0133b7d6c7df1bfbea00795f66574d844ad7546f | [
"Unlicense"
] | 1 | 2022-03-26T21:20:19.000Z | 2022-03-26T21:20:19.000Z | src/lib/util/colors.ts | cosmicplayground/cosmicplayground | 0133b7d6c7df1bfbea00795f66574d844ad7546f | [
"Unlicense"
] | null | null | null | src/lib/util/colors.ts | cosmicplayground/cosmicplayground | 0133b7d6c7df1bfbea00795f66574d844ad7546f | [
"Unlicense"
] | 1 | 2022-03-26T06:12:29.000Z | 2022-03-26T06:12:29.000Z | // https://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion
export type Hue = number; // [0, 1]
export type Saturation = number; // [0, 1]
export type Lightness = number; // [0, 1]
export type Hsl = readonly [Hue, Saturation, Lightness]; // [0,1]
export type Rgb = readonly [number, number, number]; // [0,255]
export const hueToRgb = (p: number, q: number, t: number): number => {
if (t < 0) t += 1; // eslint-disable-line no-param-reassign
if (t > 1) t -= 1; // eslint-disable-line no-param-reassign
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
};
export const rgbToHex = (r: number, g: number, b: number): number => (r << 16) + (g << 8) + b;
/**
* Converts an RGB color value to HSL. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Values r/g/b are in the range [0,255] and
* returns h/s/l in the range [0,1].
*/
export const rgbToHsl = (r: number, g: number, b: number): Hsl => {
r /= 255; // eslint-disable-line no-param-reassign
g /= 255; // eslint-disable-line no-param-reassign
b /= 255; // eslint-disable-line no-param-reassign
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const l: Lightness = (max + min) / 2;
let h!: Hue, s: Saturation;
if (max === min) {
h = s = 0; // achromatic
} else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return [h, s, l];
};
/**
* Converts an HSL color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Values h/s/l are in the range [0,1] and
* returns r/g/b in the range [0,255].
*/
export const hslToRgb = (h: Hue, s: Saturation, l: Lightness): Rgb => {
let r: number, g: number, b: number;
if (s === 0) {
r = g = b = l; // achromatic
} else {
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
r = hueToRgb(p, q, h + 1 / 3);
g = hueToRgb(p, q, h);
b = hueToRgb(p, q, h - 1 / 3);
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
};
export const hslToHex = (h: Hue, s: Saturation, l: Lightness): number =>
rgbToHex(...hslToRgb(h, s, l));
export const hslToStr = (h: Hue, s: Saturation, l: Lightness): string =>
`hsl(${h * 360}, ${s * 100}%, ${l * 100}%)`;
| 31.4625 | 94 | 0.566945 | 59 | 6 | 0 | 18 | 17 | 0 | 3 | 0 | 22 | 5 | 0 | 7.666667 | 1,087 | 0.022079 | 0.015639 | 0 | 0.0046 | 0 | 0 | 0.536585 | 0.280307 | // https://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion
export type Hue = number; // [0, 1]
export type Saturation = number; // [0, 1]
export type Lightness = number; // [0, 1]
export type Hsl = readonly [Hue, Saturation, Lightness]; // [0,1]
export type Rgb = readonly [number, number, number]; // [0,255]
export /* Example usages of 'hueToRgb' are shown below:
r = hueToRgb(p, q, h + 1 / 3);
g = hueToRgb(p, q, h);
b = hueToRgb(p, q, h - 1 / 3);
*/
const hueToRgb = (p, q, t) => {
if (t < 0) t += 1; // eslint-disable-line no-param-reassign
if (t > 1) t -= 1; // eslint-disable-line no-param-reassign
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
};
export /* Example usages of 'rgbToHex' are shown below:
rgbToHex(...hslToRgb(h, s, l));
*/
const rgbToHex = (r, g, b) => (r << 16) + (g << 8) + b;
/**
* Converts an RGB color value to HSL. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Values r/g/b are in the range [0,255] and
* returns h/s/l in the range [0,1].
*/
export const rgbToHsl = (r, g, b) => {
r /= 255; // eslint-disable-line no-param-reassign
g /= 255; // eslint-disable-line no-param-reassign
b /= 255; // eslint-disable-line no-param-reassign
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const l = (max + min) / 2;
let h!, s;
if (max === min) {
h = s = 0; // achromatic
} else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
return [h, s, l];
};
/**
* Converts an HSL color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Values h/s/l are in the range [0,1] and
* returns r/g/b in the range [0,255].
*/
export /* Example usages of 'hslToRgb' are shown below:
hslToRgb(h, s, l);
*/
const hslToRgb = (h, s, l) => {
let r, g, b;
if (s === 0) {
r = g = b = l; // achromatic
} else {
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
r = hueToRgb(p, q, h + 1 / 3);
g = hueToRgb(p, q, h);
b = hueToRgb(p, q, h - 1 / 3);
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
};
export const hslToHex = (h, s, l) =>
rgbToHex(...hslToRgb(h, s, l));
export const hslToStr = (h, s, l) =>
`hsl(${h * 360}, ${s * 100}%, ${l * 100}%)`;
|
e94c96ae0ff7f93e6d3a0b385b0561f1d1425b10 | 11,817 | ts | TypeScript | openmetadata-ui/src/main/resources/ui/src/constants/constants.ts | fangchangtan/OpenMetadata | 83a3307b60c2b4ca8b8bf4852d79e1cac65ca4af | [
"Apache-2.0"
] | 1 | 2022-03-17T08:55:30.000Z | 2022-03-17T08:55:30.000Z | openmetadata-ui/src/main/resources/ui/src/constants/constants.ts | fangchangtan/OpenMetadata | 83a3307b60c2b4ca8b8bf4852d79e1cac65ca4af | [
"Apache-2.0"
] | null | null | null | openmetadata-ui/src/main/resources/ui/src/constants/constants.ts | fangchangtan/OpenMetadata | 83a3307b60c2b4ca8b8bf4852d79e1cac65ca4af | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2021 Collate
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const FOLLOWERS_VIEW_CAP = 20;
export const JSON_TAB_SIZE = 2;
export const PAGE_SIZE = 10;
export const API_RES_MAX_SIZE = 100000;
export const LIST_SIZE = 5;
export const SIDEBAR_WIDTH_COLLAPSED = 290;
export const SIDEBAR_WIDTH_EXPANDED = 290;
export const LOCALSTORAGE_RECENTLY_VIEWED = 'recentlyViewedData';
export const LOCALSTORAGE_RECENTLY_SEARCHED = 'recentlySearchedData';
export const oidcTokenKey = 'oidcIdToken';
export const isAdminUpdated = 'isAdminUpdated';
export const imageTypes = {
image: 's96-c',
image192: 's192-c',
image24: 's24-c',
image32: 's32-c',
image48: 's48-c',
image512: 's512-c',
image72: 's72-c',
};
export const COMMON_ERROR_MSG = 'Something went wrong.';
export const TOUR_SEARCH_TERM = 'dim_a';
export const ERROR404 = 'No data found';
export const ERROR500 = 'Something went wrong';
const PLACEHOLDER_ROUTE_TABLE_FQN = ':datasetFQN';
const PLACEHOLDER_ROUTE_TOPIC_FQN = ':topicFQN';
const PLACEHOLDER_ROUTE_PIPELINE_FQN = ':pipelineFQN';
const PLACEHOLDER_ROUTE_DASHBOARD_FQN = ':dashboardFQN';
const PLACEHOLDER_ROUTE_DATABASE_FQN = ':databaseFQN';
const PLACEHOLDER_ROUTE_SERVICE_FQN = ':serviceFQN';
const PLACEHOLDER_ROUTE_SERVICE_CAT = ':serviceCategory';
const PLACEHOLDER_ROUTE_SEARCHQUERY = ':searchQuery';
const PLACEHOLDER_ROUTE_TAB = ':tab';
const PLACEHOLDER_ROUTE_TEAM = ':team';
const PLAEHOLDER_ROUTE_VERSION = ':version';
const PLACEHOLDER_ROUTE_ENTITY_TYPE = ':entityType';
const PLACEHOLDER_ROUTE_ENTITY_FQN = ':entityFQN';
const PLACEHOLDER_WEBHOOK_NAME = ':webhookName';
const PLACEHOLDER_GLOSSARY_NAME = ':glossaryName';
const PLACEHOLDER_GLOSSARY_TERMS_FQN = ':glossaryTermsFQN';
const PLACEHOLDER_USER_NAME = ':username';
export const pagingObject = { after: '', before: '' };
export const ONLY_NUMBER_REGEX = /^[0-9\b]+$/;
/* eslint-disable @typescript-eslint/camelcase */
export const tiers = [
{ key: 'Tier.Tier1', doc_count: 0 },
{ key: 'Tier.Tier2', doc_count: 0 },
{ key: 'Tier.Tier3', doc_count: 0 },
{ key: 'Tier.Tier4', doc_count: 0 },
{ key: 'Tier.Tier5', doc_count: 0 },
];
export const versionTypes = [
{ name: 'All', value: 'all' },
{ name: 'Major', value: 'major' },
{ name: 'Minor', value: 'minor' },
];
export const DESCRIPTIONLENGTH = 100;
export const visibleFilters = ['service', 'tier', 'tags', 'database'];
export const tableSortingFields = [
{
name: 'Last Updated',
value: 'last_updated_timestamp',
},
{ name: 'Weekly Usage', value: 'weekly_stats' },
// { name: 'Daily Usage', value: 'daily_stats' },
// { name: 'Monthly Usage', value: 'monthly_stats' },
];
export const topicSortingFields = [
{
name: 'Last Updated',
value: 'last_updated_timestamp',
},
];
export const sortingOrder = [
{ name: 'Ascending', value: 'asc' },
{ name: 'Descending', value: 'desc' },
];
export const facetFilterPlaceholder = [
{
name: 'Service',
value: 'Service',
},
{
name: 'Tier',
value: 'Tier',
},
{
name: 'Tags',
value: 'Tags',
},
{
name: 'Database',
value: 'Database',
},
];
export const ROUTES = {
HOME: '/',
CALLBACK: '/callback',
NOT_FOUND: '/404',
MY_DATA: '/my-data',
TOUR: '/tour',
REPORTS: '/reports',
EXPLORE: '/explore',
EXPLORE_WITH_SEARCH: `/explore/${PLACEHOLDER_ROUTE_TAB}/${PLACEHOLDER_ROUTE_SEARCHQUERY}`,
EXPLORE_WITH_TAB: `/explore/${PLACEHOLDER_ROUTE_TAB}`,
WORKFLOWS: '/workflows',
SQL_BUILDER: '/sql-builder',
TEAMS: '/teams',
TEAM_DETAILS: `/teams/${PLACEHOLDER_ROUTE_TEAM}`,
SETTINGS: '/settings',
STORE: '/store',
FEEDS: '/feeds',
DUMMY: '/dummy',
SERVICE: `/service/${PLACEHOLDER_ROUTE_SERVICE_CAT}/${PLACEHOLDER_ROUTE_SERVICE_FQN}`,
SERVICE_WITH_TAB: `/service/${PLACEHOLDER_ROUTE_SERVICE_CAT}/${PLACEHOLDER_ROUTE_SERVICE_FQN}/${PLACEHOLDER_ROUTE_TAB}`,
SERVICES: '/services',
USERS: '/users',
SCORECARD: '/scorecard',
SWAGGER: '/docs',
TAGS: '/tags',
SIGNUP: '/signup',
SIGNIN: '/signin',
TABLE_DETAILS: `/table/${PLACEHOLDER_ROUTE_TABLE_FQN}`,
TABLE_DETAILS_WITH_TAB: `/table/${PLACEHOLDER_ROUTE_TABLE_FQN}/${PLACEHOLDER_ROUTE_TAB}`,
ENTITY_VERSION: `/${PLACEHOLDER_ROUTE_ENTITY_TYPE}/${PLACEHOLDER_ROUTE_ENTITY_FQN}/versions/${PLAEHOLDER_ROUTE_VERSION}`,
TOPIC_DETAILS: `/topic/${PLACEHOLDER_ROUTE_TOPIC_FQN}`,
TOPIC_DETAILS_WITH_TAB: `/topic/${PLACEHOLDER_ROUTE_TOPIC_FQN}/${PLACEHOLDER_ROUTE_TAB}`,
DASHBOARD_DETAILS: `/dashboard/${PLACEHOLDER_ROUTE_DASHBOARD_FQN}`,
DASHBOARD_DETAILS_WITH_TAB: `/dashboard/${PLACEHOLDER_ROUTE_DASHBOARD_FQN}/${PLACEHOLDER_ROUTE_TAB}`,
DATABASE_DETAILS: `/database/${PLACEHOLDER_ROUTE_DATABASE_FQN}`,
DATABASE_DETAILS_WITH_TAB: `/database/${PLACEHOLDER_ROUTE_DATABASE_FQN}/${PLACEHOLDER_ROUTE_TAB}`,
PIPELINE_DETAILS: `/pipeline/${PLACEHOLDER_ROUTE_PIPELINE_FQN}`,
PIPELINE_DETAILS_WITH_TAB: `/pipeline/${PLACEHOLDER_ROUTE_PIPELINE_FQN}/${PLACEHOLDER_ROUTE_TAB}`,
USER_LIST: '/user-list',
USER_PROFILE: `/users/${PLACEHOLDER_USER_NAME}`,
ROLES: '/roles',
WEBHOOKS: '/webhooks',
ADD_WEBHOOK: '/add-webhook',
EDIT_WEBHOOK: `/webhook/${PLACEHOLDER_WEBHOOK_NAME}`,
GLOSSARY: '/glossary',
ADD_GLOSSARY: '/add-glossary',
GLOSSARY_DETAILS: `/glossary/${PLACEHOLDER_GLOSSARY_NAME}`,
ADD_GLOSSARY_TERMS: `/glossary/${PLACEHOLDER_GLOSSARY_NAME}/add-term`,
GLOSSARY_TERMS: `/glossary/${PLACEHOLDER_GLOSSARY_NAME}/term/${PLACEHOLDER_GLOSSARY_TERMS_FQN}`,
ADD_GLOSSARY_TERMS_CHILD: `/glossary/${PLACEHOLDER_GLOSSARY_NAME}/term/${PLACEHOLDER_GLOSSARY_TERMS_FQN}/add-term`,
};
export const IN_PAGE_SEARCH_ROUTES: Record<string, Array<string>> = {
'/database/': ['In this Database'],
};
export const getTableDetailsPath = (tableFQN: string, columnName?: string) => {
let path = ROUTES.TABLE_DETAILS;
path = path.replace(PLACEHOLDER_ROUTE_TABLE_FQN, tableFQN);
return `${path}${columnName ? `.${columnName}` : ''}`;
};
export const getVersionPath = (
entityType: string,
fqn: string,
version: string
) => {
let path = ROUTES.ENTITY_VERSION;
path = path
.replace(PLACEHOLDER_ROUTE_ENTITY_TYPE, entityType)
.replace(PLACEHOLDER_ROUTE_ENTITY_FQN, fqn)
.replace(PLAEHOLDER_ROUTE_VERSION, version);
return path;
};
export const getTableTabPath = (tableFQN: string, tab = 'schema') => {
let path = ROUTES.TABLE_DETAILS_WITH_TAB;
path = path
.replace(PLACEHOLDER_ROUTE_TABLE_FQN, tableFQN)
.replace(PLACEHOLDER_ROUTE_TAB, tab);
return path;
};
export const getServiceDetailsPath = (
serviceFQN: string,
serviceCat: string,
tab?: string
) => {
let path = tab ? ROUTES.SERVICE_WITH_TAB : ROUTES.SERVICE;
path = path
.replace(PLACEHOLDER_ROUTE_SERVICE_CAT, serviceCat)
.replace(PLACEHOLDER_ROUTE_SERVICE_FQN, serviceFQN);
if (tab) {
path = path.replace(PLACEHOLDER_ROUTE_TAB, tab);
}
return path;
};
export const getExplorePathWithSearch = (searchQuery = '', tab = 'tables') => {
let path = ROUTES.EXPLORE_WITH_SEARCH;
path = path
.replace(PLACEHOLDER_ROUTE_SEARCHQUERY, searchQuery)
.replace(PLACEHOLDER_ROUTE_TAB, tab);
return path;
};
export const getDatabaseDetailsPath = (databaseFQN: string, tab?: string) => {
let path = tab ? ROUTES.DATABASE_DETAILS_WITH_TAB : ROUTES.DATABASE_DETAILS;
path = path.replace(PLACEHOLDER_ROUTE_DATABASE_FQN, databaseFQN);
if (tab) {
path = path.replace(PLACEHOLDER_ROUTE_TAB, tab);
}
return path;
};
export const getTopicDetailsPath = (topicFQN: string, tab?: string) => {
let path = tab ? ROUTES.TOPIC_DETAILS_WITH_TAB : ROUTES.TOPIC_DETAILS;
path = path.replace(PLACEHOLDER_ROUTE_TOPIC_FQN, topicFQN);
if (tab) {
path = path.replace(PLACEHOLDER_ROUTE_TAB, tab);
}
return path;
};
export const getDashboardDetailsPath = (dashboardFQN: string, tab?: string) => {
let path = tab ? ROUTES.DASHBOARD_DETAILS_WITH_TAB : ROUTES.DASHBOARD_DETAILS;
path = path.replace(PLACEHOLDER_ROUTE_DASHBOARD_FQN, dashboardFQN);
if (tab) {
path = path.replace(PLACEHOLDER_ROUTE_TAB, tab);
}
return path;
};
export const getPipelineDetailsPath = (pipelineFQN: string, tab?: string) => {
let path = tab ? ROUTES.PIPELINE_DETAILS_WITH_TAB : ROUTES.PIPELINE_DETAILS;
path = path.replace(PLACEHOLDER_ROUTE_PIPELINE_FQN, pipelineFQN);
if (tab) {
path = path.replace(PLACEHOLDER_ROUTE_TAB, tab);
}
return path;
};
export const getTeamDetailsPath = (teamName: string) => {
let path = ROUTES.TEAM_DETAILS;
path = path.replace(PLACEHOLDER_ROUTE_TEAM, teamName);
return path;
};
export const getEditWebhookPath = (webhookName: string) => {
let path = ROUTES.EDIT_WEBHOOK;
path = path.replace(PLACEHOLDER_WEBHOOK_NAME, webhookName);
return path;
};
export const getUserPath = (username: string) => {
let path = ROUTES.USER_PROFILE;
path = path.replace(PLACEHOLDER_USER_NAME, username);
return path;
};
export const getGlossaryPath = (fqn?: string) => {
let path = ROUTES.GLOSSARY;
if (fqn) {
path = ROUTES.GLOSSARY_DETAILS;
path = path.replace(PLACEHOLDER_GLOSSARY_NAME, fqn);
}
return path;
};
export const getGlossaryTermsPath = (
glossaryName: string,
glossaryTerm = ''
) => {
let path = glossaryTerm ? ROUTES.GLOSSARY_TERMS : ROUTES.GLOSSARY_DETAILS;
path = path.replace(PLACEHOLDER_GLOSSARY_NAME, glossaryName);
if (glossaryTerm) {
path = path.replace(PLACEHOLDER_GLOSSARY_TERMS_FQN, glossaryTerm);
}
return path;
};
export const getAddGlossaryTermsPath = (
glossaryName: string,
glossaryTerm = ''
) => {
let path = glossaryTerm
? ROUTES.ADD_GLOSSARY_TERMS_CHILD
: ROUTES.ADD_GLOSSARY_TERMS;
path = path.replace(PLACEHOLDER_GLOSSARY_NAME, glossaryName);
if (glossaryTerm) {
path = path.replace(PLACEHOLDER_GLOSSARY_TERMS_FQN, glossaryTerm);
}
return path;
};
export const LIST_TYPES = ['numbered-list', 'bulleted-list'];
export const TIMEOUT = {
USER_LIST: 60000, // 60 seconds for user retrieval
TOAST_DELAY: 5000, // 5 seconds timeout for toaster autohide delay
};
export const navLinkDevelop = [
{ name: 'Reports', to: '/reports', disabled: false },
{ name: 'SQL Builder', to: '/sql-builder', disabled: false },
{ name: 'Workflows', to: '/workflows', disabled: false },
];
export const navLinkSettings = [
{ name: 'Glossaries', to: '/glossary', disabled: false },
{ name: 'Roles', to: '/roles', disabled: false, isAdminOnly: true },
{ name: 'Services', to: '/services', disabled: false },
{ name: 'Tags', to: '/tags', disabled: false },
{ name: 'Teams', to: '/teams', disabled: false },
{ name: 'Users', to: '/user-list', disabled: false, isAdminOnly: true },
// { name: 'Store', to: '/store', disabled: false },
{ name: 'Webhooks', to: '/webhooks', disabled: false },
// { name: 'Ingestions', to: '/ingestion', disabled: false },
// { name: 'Marketplace', to: '/marketplace', disabled: true },
// { name: 'Preferences', to: '/preference', disabled: true },
];
export const TITLE_FOR_NON_OWNER_ACTION =
'You need to be owner to perform this action';
export const TITLE_FOR_NON_ADMIN_ACTION =
'Only Admin is allowed for the action';
// Entity Lineage Constant
export const positionX = 150;
export const positionY = 60;
export const nodeWidth = 240;
export const nodeHeight = 40;
| 31.344828 | 123 | 0.71541 | 297 | 15 | 0 | 28 | 85 | 0 | 0 | 0 | 25 | 0 | 0 | 5.333333 | 3,635 | 0.011829 | 0.023384 | 0 | 0 | 0 | 0 | 0.195313 | 0.273857 | /*
* Copyright 2021 Collate
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const FOLLOWERS_VIEW_CAP = 20;
export const JSON_TAB_SIZE = 2;
export const PAGE_SIZE = 10;
export const API_RES_MAX_SIZE = 100000;
export const LIST_SIZE = 5;
export const SIDEBAR_WIDTH_COLLAPSED = 290;
export const SIDEBAR_WIDTH_EXPANDED = 290;
export const LOCALSTORAGE_RECENTLY_VIEWED = 'recentlyViewedData';
export const LOCALSTORAGE_RECENTLY_SEARCHED = 'recentlySearchedData';
export const oidcTokenKey = 'oidcIdToken';
export const isAdminUpdated = 'isAdminUpdated';
export const imageTypes = {
image: 's96-c',
image192: 's192-c',
image24: 's24-c',
image32: 's32-c',
image48: 's48-c',
image512: 's512-c',
image72: 's72-c',
};
export const COMMON_ERROR_MSG = 'Something went wrong.';
export const TOUR_SEARCH_TERM = 'dim_a';
export const ERROR404 = 'No data found';
export const ERROR500 = 'Something went wrong';
const PLACEHOLDER_ROUTE_TABLE_FQN = ':datasetFQN';
const PLACEHOLDER_ROUTE_TOPIC_FQN = ':topicFQN';
const PLACEHOLDER_ROUTE_PIPELINE_FQN = ':pipelineFQN';
const PLACEHOLDER_ROUTE_DASHBOARD_FQN = ':dashboardFQN';
const PLACEHOLDER_ROUTE_DATABASE_FQN = ':databaseFQN';
const PLACEHOLDER_ROUTE_SERVICE_FQN = ':serviceFQN';
const PLACEHOLDER_ROUTE_SERVICE_CAT = ':serviceCategory';
const PLACEHOLDER_ROUTE_SEARCHQUERY = ':searchQuery';
const PLACEHOLDER_ROUTE_TAB = ':tab';
const PLACEHOLDER_ROUTE_TEAM = ':team';
const PLAEHOLDER_ROUTE_VERSION = ':version';
const PLACEHOLDER_ROUTE_ENTITY_TYPE = ':entityType';
const PLACEHOLDER_ROUTE_ENTITY_FQN = ':entityFQN';
const PLACEHOLDER_WEBHOOK_NAME = ':webhookName';
const PLACEHOLDER_GLOSSARY_NAME = ':glossaryName';
const PLACEHOLDER_GLOSSARY_TERMS_FQN = ':glossaryTermsFQN';
const PLACEHOLDER_USER_NAME = ':username';
export const pagingObject = { after: '', before: '' };
export const ONLY_NUMBER_REGEX = /^[0-9\b]+$/;
/* eslint-disable @typescript-eslint/camelcase */
export const tiers = [
{ key: 'Tier.Tier1', doc_count: 0 },
{ key: 'Tier.Tier2', doc_count: 0 },
{ key: 'Tier.Tier3', doc_count: 0 },
{ key: 'Tier.Tier4', doc_count: 0 },
{ key: 'Tier.Tier5', doc_count: 0 },
];
export const versionTypes = [
{ name: 'All', value: 'all' },
{ name: 'Major', value: 'major' },
{ name: 'Minor', value: 'minor' },
];
export const DESCRIPTIONLENGTH = 100;
export const visibleFilters = ['service', 'tier', 'tags', 'database'];
export const tableSortingFields = [
{
name: 'Last Updated',
value: 'last_updated_timestamp',
},
{ name: 'Weekly Usage', value: 'weekly_stats' },
// { name: 'Daily Usage', value: 'daily_stats' },
// { name: 'Monthly Usage', value: 'monthly_stats' },
];
export const topicSortingFields = [
{
name: 'Last Updated',
value: 'last_updated_timestamp',
},
];
export const sortingOrder = [
{ name: 'Ascending', value: 'asc' },
{ name: 'Descending', value: 'desc' },
];
export const facetFilterPlaceholder = [
{
name: 'Service',
value: 'Service',
},
{
name: 'Tier',
value: 'Tier',
},
{
name: 'Tags',
value: 'Tags',
},
{
name: 'Database',
value: 'Database',
},
];
export const ROUTES = {
HOME: '/',
CALLBACK: '/callback',
NOT_FOUND: '/404',
MY_DATA: '/my-data',
TOUR: '/tour',
REPORTS: '/reports',
EXPLORE: '/explore',
EXPLORE_WITH_SEARCH: `/explore/${PLACEHOLDER_ROUTE_TAB}/${PLACEHOLDER_ROUTE_SEARCHQUERY}`,
EXPLORE_WITH_TAB: `/explore/${PLACEHOLDER_ROUTE_TAB}`,
WORKFLOWS: '/workflows',
SQL_BUILDER: '/sql-builder',
TEAMS: '/teams',
TEAM_DETAILS: `/teams/${PLACEHOLDER_ROUTE_TEAM}`,
SETTINGS: '/settings',
STORE: '/store',
FEEDS: '/feeds',
DUMMY: '/dummy',
SERVICE: `/service/${PLACEHOLDER_ROUTE_SERVICE_CAT}/${PLACEHOLDER_ROUTE_SERVICE_FQN}`,
SERVICE_WITH_TAB: `/service/${PLACEHOLDER_ROUTE_SERVICE_CAT}/${PLACEHOLDER_ROUTE_SERVICE_FQN}/${PLACEHOLDER_ROUTE_TAB}`,
SERVICES: '/services',
USERS: '/users',
SCORECARD: '/scorecard',
SWAGGER: '/docs',
TAGS: '/tags',
SIGNUP: '/signup',
SIGNIN: '/signin',
TABLE_DETAILS: `/table/${PLACEHOLDER_ROUTE_TABLE_FQN}`,
TABLE_DETAILS_WITH_TAB: `/table/${PLACEHOLDER_ROUTE_TABLE_FQN}/${PLACEHOLDER_ROUTE_TAB}`,
ENTITY_VERSION: `/${PLACEHOLDER_ROUTE_ENTITY_TYPE}/${PLACEHOLDER_ROUTE_ENTITY_FQN}/versions/${PLAEHOLDER_ROUTE_VERSION}`,
TOPIC_DETAILS: `/topic/${PLACEHOLDER_ROUTE_TOPIC_FQN}`,
TOPIC_DETAILS_WITH_TAB: `/topic/${PLACEHOLDER_ROUTE_TOPIC_FQN}/${PLACEHOLDER_ROUTE_TAB}`,
DASHBOARD_DETAILS: `/dashboard/${PLACEHOLDER_ROUTE_DASHBOARD_FQN}`,
DASHBOARD_DETAILS_WITH_TAB: `/dashboard/${PLACEHOLDER_ROUTE_DASHBOARD_FQN}/${PLACEHOLDER_ROUTE_TAB}`,
DATABASE_DETAILS: `/database/${PLACEHOLDER_ROUTE_DATABASE_FQN}`,
DATABASE_DETAILS_WITH_TAB: `/database/${PLACEHOLDER_ROUTE_DATABASE_FQN}/${PLACEHOLDER_ROUTE_TAB}`,
PIPELINE_DETAILS: `/pipeline/${PLACEHOLDER_ROUTE_PIPELINE_FQN}`,
PIPELINE_DETAILS_WITH_TAB: `/pipeline/${PLACEHOLDER_ROUTE_PIPELINE_FQN}/${PLACEHOLDER_ROUTE_TAB}`,
USER_LIST: '/user-list',
USER_PROFILE: `/users/${PLACEHOLDER_USER_NAME}`,
ROLES: '/roles',
WEBHOOKS: '/webhooks',
ADD_WEBHOOK: '/add-webhook',
EDIT_WEBHOOK: `/webhook/${PLACEHOLDER_WEBHOOK_NAME}`,
GLOSSARY: '/glossary',
ADD_GLOSSARY: '/add-glossary',
GLOSSARY_DETAILS: `/glossary/${PLACEHOLDER_GLOSSARY_NAME}`,
ADD_GLOSSARY_TERMS: `/glossary/${PLACEHOLDER_GLOSSARY_NAME}/add-term`,
GLOSSARY_TERMS: `/glossary/${PLACEHOLDER_GLOSSARY_NAME}/term/${PLACEHOLDER_GLOSSARY_TERMS_FQN}`,
ADD_GLOSSARY_TERMS_CHILD: `/glossary/${PLACEHOLDER_GLOSSARY_NAME}/term/${PLACEHOLDER_GLOSSARY_TERMS_FQN}/add-term`,
};
export const IN_PAGE_SEARCH_ROUTES = {
'/database/': ['In this Database'],
};
export const getTableDetailsPath = (tableFQN, columnName?) => {
let path = ROUTES.TABLE_DETAILS;
path = path.replace(PLACEHOLDER_ROUTE_TABLE_FQN, tableFQN);
return `${path}${columnName ? `.${columnName}` : ''}`;
};
export const getVersionPath = (
entityType,
fqn,
version
) => {
let path = ROUTES.ENTITY_VERSION;
path = path
.replace(PLACEHOLDER_ROUTE_ENTITY_TYPE, entityType)
.replace(PLACEHOLDER_ROUTE_ENTITY_FQN, fqn)
.replace(PLAEHOLDER_ROUTE_VERSION, version);
return path;
};
export const getTableTabPath = (tableFQN, tab = 'schema') => {
let path = ROUTES.TABLE_DETAILS_WITH_TAB;
path = path
.replace(PLACEHOLDER_ROUTE_TABLE_FQN, tableFQN)
.replace(PLACEHOLDER_ROUTE_TAB, tab);
return path;
};
export const getServiceDetailsPath = (
serviceFQN,
serviceCat,
tab?
) => {
let path = tab ? ROUTES.SERVICE_WITH_TAB : ROUTES.SERVICE;
path = path
.replace(PLACEHOLDER_ROUTE_SERVICE_CAT, serviceCat)
.replace(PLACEHOLDER_ROUTE_SERVICE_FQN, serviceFQN);
if (tab) {
path = path.replace(PLACEHOLDER_ROUTE_TAB, tab);
}
return path;
};
export const getExplorePathWithSearch = (searchQuery = '', tab = 'tables') => {
let path = ROUTES.EXPLORE_WITH_SEARCH;
path = path
.replace(PLACEHOLDER_ROUTE_SEARCHQUERY, searchQuery)
.replace(PLACEHOLDER_ROUTE_TAB, tab);
return path;
};
export const getDatabaseDetailsPath = (databaseFQN, tab?) => {
let path = tab ? ROUTES.DATABASE_DETAILS_WITH_TAB : ROUTES.DATABASE_DETAILS;
path = path.replace(PLACEHOLDER_ROUTE_DATABASE_FQN, databaseFQN);
if (tab) {
path = path.replace(PLACEHOLDER_ROUTE_TAB, tab);
}
return path;
};
export const getTopicDetailsPath = (topicFQN, tab?) => {
let path = tab ? ROUTES.TOPIC_DETAILS_WITH_TAB : ROUTES.TOPIC_DETAILS;
path = path.replace(PLACEHOLDER_ROUTE_TOPIC_FQN, topicFQN);
if (tab) {
path = path.replace(PLACEHOLDER_ROUTE_TAB, tab);
}
return path;
};
export const getDashboardDetailsPath = (dashboardFQN, tab?) => {
let path = tab ? ROUTES.DASHBOARD_DETAILS_WITH_TAB : ROUTES.DASHBOARD_DETAILS;
path = path.replace(PLACEHOLDER_ROUTE_DASHBOARD_FQN, dashboardFQN);
if (tab) {
path = path.replace(PLACEHOLDER_ROUTE_TAB, tab);
}
return path;
};
export const getPipelineDetailsPath = (pipelineFQN, tab?) => {
let path = tab ? ROUTES.PIPELINE_DETAILS_WITH_TAB : ROUTES.PIPELINE_DETAILS;
path = path.replace(PLACEHOLDER_ROUTE_PIPELINE_FQN, pipelineFQN);
if (tab) {
path = path.replace(PLACEHOLDER_ROUTE_TAB, tab);
}
return path;
};
export const getTeamDetailsPath = (teamName) => {
let path = ROUTES.TEAM_DETAILS;
path = path.replace(PLACEHOLDER_ROUTE_TEAM, teamName);
return path;
};
export const getEditWebhookPath = (webhookName) => {
let path = ROUTES.EDIT_WEBHOOK;
path = path.replace(PLACEHOLDER_WEBHOOK_NAME, webhookName);
return path;
};
export const getUserPath = (username) => {
let path = ROUTES.USER_PROFILE;
path = path.replace(PLACEHOLDER_USER_NAME, username);
return path;
};
export const getGlossaryPath = (fqn?) => {
let path = ROUTES.GLOSSARY;
if (fqn) {
path = ROUTES.GLOSSARY_DETAILS;
path = path.replace(PLACEHOLDER_GLOSSARY_NAME, fqn);
}
return path;
};
export const getGlossaryTermsPath = (
glossaryName,
glossaryTerm = ''
) => {
let path = glossaryTerm ? ROUTES.GLOSSARY_TERMS : ROUTES.GLOSSARY_DETAILS;
path = path.replace(PLACEHOLDER_GLOSSARY_NAME, glossaryName);
if (glossaryTerm) {
path = path.replace(PLACEHOLDER_GLOSSARY_TERMS_FQN, glossaryTerm);
}
return path;
};
export const getAddGlossaryTermsPath = (
glossaryName,
glossaryTerm = ''
) => {
let path = glossaryTerm
? ROUTES.ADD_GLOSSARY_TERMS_CHILD
: ROUTES.ADD_GLOSSARY_TERMS;
path = path.replace(PLACEHOLDER_GLOSSARY_NAME, glossaryName);
if (glossaryTerm) {
path = path.replace(PLACEHOLDER_GLOSSARY_TERMS_FQN, glossaryTerm);
}
return path;
};
export const LIST_TYPES = ['numbered-list', 'bulleted-list'];
export const TIMEOUT = {
USER_LIST: 60000, // 60 seconds for user retrieval
TOAST_DELAY: 5000, // 5 seconds timeout for toaster autohide delay
};
export const navLinkDevelop = [
{ name: 'Reports', to: '/reports', disabled: false },
{ name: 'SQL Builder', to: '/sql-builder', disabled: false },
{ name: 'Workflows', to: '/workflows', disabled: false },
];
export const navLinkSettings = [
{ name: 'Glossaries', to: '/glossary', disabled: false },
{ name: 'Roles', to: '/roles', disabled: false, isAdminOnly: true },
{ name: 'Services', to: '/services', disabled: false },
{ name: 'Tags', to: '/tags', disabled: false },
{ name: 'Teams', to: '/teams', disabled: false },
{ name: 'Users', to: '/user-list', disabled: false, isAdminOnly: true },
// { name: 'Store', to: '/store', disabled: false },
{ name: 'Webhooks', to: '/webhooks', disabled: false },
// { name: 'Ingestions', to: '/ingestion', disabled: false },
// { name: 'Marketplace', to: '/marketplace', disabled: true },
// { name: 'Preferences', to: '/preference', disabled: true },
];
export const TITLE_FOR_NON_OWNER_ACTION =
'You need to be owner to perform this action';
export const TITLE_FOR_NON_ADMIN_ACTION =
'Only Admin is allowed for the action';
// Entity Lineage Constant
export const positionX = 150;
export const positionY = 60;
export const nodeWidth = 240;
export const nodeHeight = 40;
|
e95b95e8c5b43a03f4a34e0c395e96db04c52a9f | 3,835 | ts | TypeScript | problemset/median-of-two-sorted-arrays/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/median-of-two-sorted-arrays/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/median-of-two-sorted-arrays/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 暴力解法
* @desc 时间复杂度 O((n+m)log(n+m)) 空间复杂度 O(n+m)
* @desc https://segmentfault.com/a/1190000010648740
* @param nums1 {Array<number>}
* @param nums2 {Array<number>}
* @return {number}
*/
export function findMedianSortedArrays(
nums1: number[],
nums2: number[],
): number {
// 合并数组
let nums: number[] = [...nums1, ...nums2]
const len = nums.length
if (len === 1) return nums[0]
// 使用sort对数组进行排序
nums = nums.sort((a, b) => a - b)
// 判断数组长度,返回中位数
if (len % 2) {
// 奇数长度
return nums[(len - 1) / 2]
}
else {
// 偶数长度
return (nums[len / 2] + nums[len / 2 - 1]) / 2
}
}
/**
* 二分法
* @desc 时间复杂度 O(log(n+m)) 空间复杂度 O(1)
* @param nums1 {Array<number>}
* @param nums2 {Array<number>}
* @return {number}
*/
export function findMedianSortedArrays2(
nums1: number[],
nums2: number[],
): number {
// 总长度
const len: number = nums1.length + nums2.length
// 判断是奇数还是偶数
if (len % 2) {
const middleIdx: number = (len - 1) / 2
return getMedian(nums1, nums2, middleIdx, false)
}
else {
const middleIdx: number = len / 2 // 获取第二个中位值idx
return getMedian(nums1, nums2, middleIdx, true)
}
/**
* 获取数组的中位值
* @param nums1 {Array<number>}
* @param nums2 {Array<number>}
* @param middleIdx {number}
* @param isEven {boolean} 是否为偶数
*/
function getMedian(
nums1: Array<number>,
nums2: Array<number>,
middleIdx: number,
isEven = false,
): number {
let idx1 = 0
let idx2 = 0
let prevMedian = NaN
let median = NaN
// 遍历
while (idx1 + idx2 <= middleIdx) {
// 获取两个数组当前值
const num1: number = nums1[idx1]
const num2: number = nums2[idx2]
if (num1 === num2) {
// 如果num1等于num2,判断idx1和idx2是否来到临界值,如果是的话,只进一位;如果不是的话进两位
idx1 + idx2 < middleIdx
? (prevMedian = median = num1)
: setMedian(num1)
idx1++
idx2++
}
else if (num1 < num2 || (!num2 && num2 !== 0)) {
// 如果num1小于num2,或者num2没有值
idx1++
setMedian(num1)
}
else if (num1 > num2 || (!num1 && num1 !== 0)) {
// 如果num1大于num2,或者num1没有值
idx2++
setMedian(num2)
}
}
return isEven ? (prevMedian + median) / 2 : median
/**
* 设置中位数
* @param num {number}
*/
function setMedian(num: number): void {
if (isNaN(median)) {
prevMedian = median = num
}
else {
prevMedian = median
median = num
}
}
}
}
/**
* 划分数组
* @desc 时间复杂度 O(log min(n,m)) 空间复杂度 O(1)
* @param nums1 {Array<number>}
* @param nums2 {Array<number>}
* @return {number}
*/
export function findMedianSortedArrays3(
nums1: number[],
nums2: number[],
): number {
// 确保nums1长度小于nums2
if (nums1.length > nums2.length)
return findMedianSortedArrays3(nums2, nums1)
const len1: number = nums1.length
const len2: number = nums2.length
// 前一部分的最大值
let median1 = 0
// 后一部分的最小值
let median2 = 0
let left = 0
let right: number = len1
while (left <= right) {
// 前一部分包含 nums1[0 .. i-1] 和 nums2[0 .. j-1]
// 后一部分包含 nums1[i .. len1-1] 和 nums2[j .. len2-1]
const i: number = Math.floor((left + right) / 2)
const j: number = Math.floor((len1 + len2 + 1) / 2) - i
// nums_im1, nums_i, nums_jm1, nums_j 分别表示 nums1[i-1], nums1[i], nums2[j-1], nums2[j]
const num_im1: number = i === 0 ? -Infinity : nums1[i - 1]
const num_i: number = i === len1 ? Infinity : nums1[i]
const num_jm1: number = j === 0 ? -Infinity : nums2[j - 1]
const num_j: number = j === len2 ? Infinity : nums2[j]
if (num_im1 <= num_j) {
median1 = Math.max(num_im1, num_jm1)
median2 = Math.min(num_i, num_j)
left = i + 1
}
else {
right = i - 1
}
}
return (len1 + len2) % 2 ? median1 : (median1 + median2) / 2
}
| 22.692308 | 89 | 0.562712 | 99 | 6 | 0 | 13 | 23 | 0 | 3 | 0 | 30 | 0 | 0 | 20.833333 | 1,448 | 0.013122 | 0.015884 | 0 | 0 | 0 | 0 | 0.714286 | 0.252547 | /**
* 暴力解法
* @desc 时间复杂度 O((n+m)log(n+m)) 空间复杂度 O(n+m)
* @desc https://segmentfault.com/a/1190000010648740
* @param nums1 {Array<number>}
* @param nums2 {Array<number>}
* @return {number}
*/
export function findMedianSortedArrays(
nums1,
nums2,
) {
// 合并数组
let nums = [...nums1, ...nums2]
const len = nums.length
if (len === 1) return nums[0]
// 使用sort对数组进行排序
nums = nums.sort((a, b) => a - b)
// 判断数组长度,返回中位数
if (len % 2) {
// 奇数长度
return nums[(len - 1) / 2]
}
else {
// 偶数长度
return (nums[len / 2] + nums[len / 2 - 1]) / 2
}
}
/**
* 二分法
* @desc 时间复杂度 O(log(n+m)) 空间复杂度 O(1)
* @param nums1 {Array<number>}
* @param nums2 {Array<number>}
* @return {number}
*/
export function findMedianSortedArrays2(
nums1,
nums2,
) {
// 总长度
const len = nums1.length + nums2.length
// 判断是奇数还是偶数
if (len % 2) {
const middleIdx = (len - 1) / 2
return getMedian(nums1, nums2, middleIdx, false)
}
else {
const middleIdx = len / 2 // 获取第二个中位值idx
return getMedian(nums1, nums2, middleIdx, true)
}
/**
* 获取数组的中位值
* @param nums1 {Array<number>}
* @param nums2 {Array<number>}
* @param middleIdx {number}
* @param isEven {boolean} 是否为偶数
*/
/* Example usages of 'getMedian' are shown below:
getMedian(nums1, nums2, middleIdx, false);
getMedian(nums1, nums2, middleIdx, true);
*/
function getMedian(
nums1,
nums2,
middleIdx,
isEven = false,
) {
let idx1 = 0
let idx2 = 0
let prevMedian = NaN
let median = NaN
// 遍历
while (idx1 + idx2 <= middleIdx) {
// 获取两个数组当前值
const num1 = nums1[idx1]
const num2 = nums2[idx2]
if (num1 === num2) {
// 如果num1等于num2,判断idx1和idx2是否来到临界值,如果是的话,只进一位;如果不是的话进两位
idx1 + idx2 < middleIdx
? (prevMedian = median = num1)
: setMedian(num1)
idx1++
idx2++
}
else if (num1 < num2 || (!num2 && num2 !== 0)) {
// 如果num1小于num2,或者num2没有值
idx1++
setMedian(num1)
}
else if (num1 > num2 || (!num1 && num1 !== 0)) {
// 如果num1大于num2,或者num1没有值
idx2++
setMedian(num2)
}
}
return isEven ? (prevMedian + median) / 2 : median
/**
* 设置中位数
* @param num {number}
*/
/* Example usages of 'setMedian' are shown below:
// 如果num1等于num2,判断idx1和idx2是否来到临界值,如果是的话,只进一位;如果不是的话进两位
idx1 + idx2 < middleIdx
? (prevMedian = median = num1)
: setMedian(num1);
setMedian(num1);
setMedian(num2);
*/
function setMedian(num) {
if (isNaN(median)) {
prevMedian = median = num
}
else {
prevMedian = median
median = num
}
}
}
}
/**
* 划分数组
* @desc 时间复杂度 O(log min(n,m)) 空间复杂度 O(1)
* @param nums1 {Array<number>}
* @param nums2 {Array<number>}
* @return {number}
*/
export /* Example usages of 'findMedianSortedArrays3' are shown below:
findMedianSortedArrays3(nums2, nums1);
*/
function findMedianSortedArrays3(
nums1,
nums2,
) {
// 确保nums1长度小于nums2
if (nums1.length > nums2.length)
return findMedianSortedArrays3(nums2, nums1)
const len1 = nums1.length
const len2 = nums2.length
// 前一部分的最大值
let median1 = 0
// 后一部分的最小值
let median2 = 0
let left = 0
let right = len1
while (left <= right) {
// 前一部分包含 nums1[0 .. i-1] 和 nums2[0 .. j-1]
// 后一部分包含 nums1[i .. len1-1] 和 nums2[j .. len2-1]
const i = Math.floor((left + right) / 2)
const j = Math.floor((len1 + len2 + 1) / 2) - i
// nums_im1, nums_i, nums_jm1, nums_j 分别表示 nums1[i-1], nums1[i], nums2[j-1], nums2[j]
const num_im1 = i === 0 ? -Infinity : nums1[i - 1]
const num_i = i === len1 ? Infinity : nums1[i]
const num_jm1 = j === 0 ? -Infinity : nums2[j - 1]
const num_j = j === len2 ? Infinity : nums2[j]
if (num_im1 <= num_j) {
median1 = Math.max(num_im1, num_jm1)
median2 = Math.min(num_i, num_j)
left = i + 1
}
else {
right = i - 1
}
}
return (len1 + len2) % 2 ? median1 : (median1 + median2) / 2
}
|
e98d86cfc058767b3e421f91a487fca89b5c8419 | 28,925 | ts | TypeScript | src/util/SNBT.ts | HURDOO/animated-java | 6c34a59e7b554a4f2651f5765822449f5ec992ad | [
"Apache-2.0"
] | 58 | 2022-01-03T17:15:19.000Z | 2022-03-22T13:24:59.000Z | src/util/SNBT.ts | HURDOO/animated-java | 6c34a59e7b554a4f2651f5765822449f5ec992ad | [
"Apache-2.0"
] | 64 | 2022-01-03T17:40:17.000Z | 2022-03-31T15:27:23.000Z | src/util/SNBT.ts | HURDOO/animated-java | 6c34a59e7b554a4f2651f5765822449f5ec992ad | [
"Apache-2.0"
] | 15 | 2022-01-03T17:16:35.000Z | 2022-03-28T12:30:08.000Z | function assert(condition: any, message?: string) {
if (!condition) {
throw new Error(message || 'Assertion failed')
}
}
function every<T>(v: T[], arg1: (x: T) => boolean): any {
assert(Array.isArray(v), 'expected an array')
return !v.find((x) => !arg1(x))
}
export enum SNBTTagType {
END = 0,
BYTE = 1,
SHORT = 2,
INT = 3,
LONG = 4,
FLOAT = 5,
DOUBLE = 6,
BYTE_ARRAY = 7,
STRING = 8,
LIST = 9,
COMPOUND = 10,
INT_ARRAY = 11,
LONG_ARRAY = 12,
BOOLEAN = 13,
}
enum SNBTStringifyFlags {
NONE = 0,
EXCLUDE_TYPE = 1,
}
// this class is a generic for holding an NBT value,
// it supports merge, set, stringify, and clone
function typeToConstructor(type: SNBTTagType) {
switch (type) {
case SNBTTagType.BOOLEAN:
return SNBT.Boolean
case SNBTTagType.BYTE:
return SNBT.Byte
case SNBTTagType.BYTE_ARRAY:
return SNBT.Byte_Array
case SNBTTagType.COMPOUND:
return SNBT.Compound
case SNBTTagType.DOUBLE:
return SNBT.Double
case SNBTTagType.END:
throw new Error(
'SNBTTagType.END should never be used in a SNBT construct'
)
case SNBTTagType.FLOAT:
return SNBT.Float
case SNBTTagType.INT:
return SNBT.Int
case SNBTTagType.INT_ARRAY:
return SNBT.Int_Array
case SNBTTagType.LIST:
return SNBT.List
case SNBTTagType.LONG:
return SNBT.Long
case SNBTTagType.LONG_ARRAY:
return SNBT.Long_Array
case SNBTTagType.SHORT:
return SNBT.Short
case SNBTTagType.STRING:
return SNBT.String
default:
throw `Unknown SNBTTagType ${type}`
}
}
export class SNBTTag {
assert(path: string, type: SNBTTagType) {
const gotten = this.get(path)
if (!gotten) {
this.set(path, typeToConstructor(type)())
} else if (!(type === gotten.type)) {
throw Error(
`NBT type at ${path} is not of type ${
SNBTTagType[type]
}. Instead found: ${SNBTTagType[gotten.type]}`
)
}
}
push(...values: SNBTTag[]) {
for (const value of values) {
switch (this.type) {
case SNBTTagType.LIST:
this.value.push(value)
break
case SNBTTagType.BYTE_ARRAY:
assert(
value.type === SNBTTagType.BYTE,
`Expected BYTE to push to BYTE_ARRAY. Got ${
SNBTTagType[value.type]
}`
)
this.value.push(value)
break
case SNBTTagType.INT_ARRAY:
assert(
value.type === SNBTTagType.INT,
`Expected INT to push to INT_ARRAY. Got ${
SNBTTagType[value.type]
}`
)
this.value.push(value)
break
case SNBTTagType.LONG_ARRAY:
assert(
value.type === SNBTTagType.LONG,
`Expected LONG to push to LONG_ARRAY. Got ${
SNBTTagType[value.type]
}`
)
this.value.push(value)
break
default:
throw `Unable to perform push on ${SNBTTagType[this.type]}`
}
}
}
_merge(b: SNBTTag) {
// if merging is possible merge otherwise set
if (
(this.type === SNBTTagType.COMPOUND &&
b.type === SNBTTagType.COMPOUND) ||
(this.type === SNBTTagType.LIST && b.type === SNBTTagType.LIST) ||
(this.type === SNBTTagType.INT_ARRAY &&
b.type === SNBTTagType.INT_ARRAY) ||
(this.type === SNBTTagType.LONG_ARRAY &&
b.type === SNBTTagType.LONG_ARRAY) ||
(this.type === SNBTTagType.BYTE_ARRAY &&
b.type === SNBTTagType.BYTE_ARRAY)
) {
for (let [key, value] of Object.entries(
b.value as Record<string, SNBTTag>
)) {
if (!(key in this.value)) {
this.value[key] = value.clone()
} else {
this.value[key]._merge(value)
}
}
} else {
this.type = b.type
this.value = b.value
}
}
constructor(public type: SNBTTagType, public value: any) {}
set(path: string, value: SNBTTag) {
let parts = path.split(/(\[\-?\d+\])|\./g).filter(Boolean)
return this._set(parts, value)
}
// traverse the path and set the value
// if the path does not exist, create it
// if the path is a list or compound, set the value at the given key,
//TODO: validate the key is valid for the type
_set(parts: string[], value: SNBTTag) {
let key = parts.shift() as string
// if (parts.length === 0) {
// this.value[key] = value;
// }
if (key.startsWith('[') && key.endsWith(']')) {
key = key.substring(1, key.length - 1)
if (
this.type === SNBTTagType.INT_ARRAY ||
this.type === SNBTTagType.LONG_ARRAY ||
this.type === SNBTTagType.BYTE_ARRAY ||
this.type === SNBTTagType.LIST
) {
if (parts.length === 0) {
this.value[
this.value.indexOf(this.value.at(parseInt(key)))
] = value
}
let value2 = this.value.at(parseInt(key))
return value2._set(parts, value)
}
}
if (parts.length === 0) {
if (
this.type === SNBTTagType.COMPOUND ||
this.type === SNBTTagType.LIST ||
this.type === SNBTTagType.INT_ARRAY ||
this.type === SNBTTagType.LONG_ARRAY ||
this.type === SNBTTagType.BYTE_ARRAY
) {
this.value[key] = value
}
return this
}
if (!(key in this.value)) {
this.value[key] = new SNBTTag(SNBTTagType.COMPOUND, {})
}
this.value[key]._set(parts, value)
return this
}
_get(parts: string[]) {
if (parts.length === 0) return this
let key = parts.shift() as string
if (key.startsWith('[') && key.endsWith(']')) {
key = key.substring(1, key.length - 1)
if (
this.type === SNBTTagType.INT_ARRAY ||
this.type === SNBTTagType.LONG_ARRAY ||
this.type === SNBTTagType.BYTE_ARRAY ||
this.type === SNBTTagType.LIST
) {
let value = this.value.at(parseInt(key))
if (parts.length === 0) {
return this.value
}
return value._get(parts)
}
}
if (parts.length === 0) {
return this.value[key]
}
if (!(key in this.value)) {
return null
}
return this.value[key]._get(parts)
}
get(path: string): SNBTTag | null {
let parts = path.split(/(\[\-?\d+\])|\./g).filter(Boolean)
return this._get(parts)
}
//TODO: the BYTE_ARRAY, INT_ARRAY, and LONG_ARRAY types do not use the type prefix, they make a list with each entry being a Tag
toString(flags: number = 0): string {
const exclude_type = flags & SNBTStringifyFlags.EXCLUDE_TYPE
switch (this.type) {
case SNBTTagType.END:
throw new Error('Cannot convert END tag to string')
case SNBTTagType.BYTE:
return this.value.toString() + (exclude_type ? '' : 'b')
case SNBTTagType.SHORT:
return this.value.toString() + (exclude_type ? '' : 's')
case SNBTTagType.INT:
return this.value.toString()
case SNBTTagType.LONG:
return this.value.toString() + (exclude_type ? '' : 'l')
case SNBTTagType.FLOAT:
return this.value.toString() + (exclude_type ? '' : 'f')
case SNBTTagType.DOUBLE:
return this.value.toString() + Number.isInteger(this.value)
? '.0'
: ''
case SNBTTagType.STRING:
return SNBTUtil.stringify(this.value)
case SNBTTagType.LONG_ARRAY:
case SNBTTagType.BYTE_ARRAY:
case SNBTTagType.LIST:
return '[' + this.value.join(',') + ']'
case SNBTTagType.COMPOUND:
return (
'{' +
Object.entries(this.value as Record<any, SNBTTag>)
.map(([key, value]) => `${key}:${value.toString()}`)
.join(',') +
'}'
)
case SNBTTagType.INT_ARRAY:
return (
'[I;' +
this.value
.map((v: SNBTTag) =>
v.toString(SNBTStringifyFlags.EXCLUDE_TYPE)
)
.join(',') +
']'
)
case SNBTTagType.BOOLEAN:
return this.value ? 'true' : 'false'
}
}
toPrettyString(exclude_type?: true) {
switch (this.type) {
case SNBTTagType.END:
throw new Error('Cannot convert END tag to string')
case SNBTTagType.BYTE:
return this.value.toString() + (exclude_type ? '' : 'b')
case SNBTTagType.SHORT:
return this.value.toString() + (exclude_type ? '' : 's')
case SNBTTagType.INT:
return this.value.toString()
case SNBTTagType.LONG:
return this.value.toString()
case SNBTTagType.FLOAT:
return this.value.toString()
case SNBTTagType.DOUBLE:
return this.value.toString() + Number.isInteger(this.value)
? '.0'
: ''
case SNBTTagType.STRING:
return SNBTUtil.stringify(this.value)
case SNBTTagType.COMPOUND:
return (
'{\n' +
Object.entries(this.value as Record<any, SNBTTag>)
.map(([key, value]) =>
`${key}:${value.toPrettyString()}`
.split('\n')
.map((_) => ` ${_}`)
.join('\n')
)
.join(',\n') +
'\n}'
)
case SNBTTagType.INT_ARRAY: {
let items = this.value.map((item) => item.toPrettyString())
let combined = items.join(',')
let isIndented = items.indexOf('\n') > -1
if (combined.length > 16) isIndented = true
if (isIndented) {
return `[I;\n${items.map((_) => ` ${_}`).join(',\n')}\n]`
}
return '[I;' + combined + ']'
}
case SNBTTagType.BYTE_ARRAY:
case SNBTTagType.LIST:
case SNBTTagType.LONG_ARRAY: {
let items = this.value.map((item) => item.toPrettyString())
let combined = items.join(', ')
let isIndented = combined.indexOf('\n') > -1
if (combined.length > 16) isIndented = true
if (isIndented) {
return `[\n${items
.map((_) =>
_.split('\n')
.map((i) => ` ${i}`)
.join('\n')
)
.join(',\n')}\n]`
}
return '[' + combined + ']'
}
case SNBTTagType.BOOLEAN:
return this.value ? 'true' : 'false'
}
}
toHighlightString(
highlighters: Record<string, (string) => string>,
exclude_type?: true
) {
function NO_SYNTAX_HIGHLIGHTER(s) {
return s
}
function getFormatter(name) {
return name in highlighters
? highlighters[name]
: NO_SYNTAX_HIGHLIGHTER
}
const STRING_FORMATTER = getFormatter('string')
const NUMBER_FORMATTER = getFormatter('number')
const BOOLEAN_FORMATTER = getFormatter('boolean')
const BRACKET_FORMATTER = getFormatter('brackets')
const ARRAY_FORMATTER = getFormatter('list')
const TYPE_BYTE = getFormatter('type_byte')
const TYPE_SHORT = getFormatter('type_short')
const TYPE_INT = getFormatter('type_int_list')
const SNYTAX = getFormatter('syntax')
const COMPOUND_NAME_FORMATTER = getFormatter('compound_name')
switch (this.type) {
case SNBTTagType.END:
throw new Error('Cannot convert END tag to string')
case SNBTTagType.BYTE:
return (
NUMBER_FORMATTER(this.value.toString()) +
TYPE_BYTE(exclude_type ? '' : 'b')
)
case SNBTTagType.SHORT:
return (
NUMBER_FORMATTER(this.value.toString()) +
TYPE_SHORT(exclude_type ? '' : 's')
)
case SNBTTagType.INT:
return NUMBER_FORMATTER(this.value.toString())
case SNBTTagType.LONG:
return NUMBER_FORMATTER(this.value.toString())
case SNBTTagType.FLOAT:
return NUMBER_FORMATTER(this.value.toString())
case SNBTTagType.DOUBLE:
return NUMBER_FORMATTER(
this.value.toString() + Number.isInteger(this.value)
? '.0'
: ''
)
case SNBTTagType.STRING:
return STRING_FORMATTER(SNBTUtil.stringify(this.value))
case SNBTTagType.COMPOUND:
let entries = Object.entries(this.value as Record<any, SNBTTag>)
if (!entries.length) return BRACKET_FORMATTER(`{}`)
return (
BRACKET_FORMATTER('{') +
'\n' +
entries
.map(([key, value]) =>
`${COMPOUND_NAME_FORMATTER(key)}${SNYTAX(
':'
)}${value.toHighlightString(highlighters)}`
.split('\n')
.map((_) => ` ${_}`)
.join('\n')
)
.join(SNYTAX(',') + '\n') +
'\n' +
BRACKET_FORMATTER('}')
)
case SNBTTagType.INT_ARRAY: {
let items = this.value.map((item) =>
item.toHighlightString(highlighters)
)
let combined = items.join(SNYTAX(','))
let isIndented = items.indexOf('\n') > -1
if (this.value.join(',').length > 16) isIndented = true
if (isIndented) {
return `${ARRAY_FORMATTER('[')}${TYPE_INT('I')};\n${items
.map((_) => ` ${_}`)
.join(SNYTAX(',') + '\n')}\n${ARRAY_FORMATTER(']')}`
}
return (
`${ARRAY_FORMATTER('[')}${TYPE_INT('I')};` +
combined +
ARRAY_FORMATTER(']')
)
}
case SNBTTagType.BYTE_ARRAY:
case SNBTTagType.LIST:
case SNBTTagType.LONG_ARRAY: {
let items = this.value.map((item) =>
item.toHighlightString(highlighters)
)
let combined = items.join(', ')
let isIndented = combined.indexOf('\n') > -1
if (combined.length > 16) isIndented = true
if (isIndented) {
return `${ARRAY_FORMATTER('[')}\n${items
.map((_) =>
_.split('\n')
.map((i) => ` ${i}`)
.join('\n')
)
.join(SNYTAX(',') + '\n')}\n${ARRAY_FORMATTER(']')}`
}
return ARRAY_FORMATTER('[') + combined + ARRAY_FORMATTER(']')
}
case SNBTTagType.BOOLEAN:
return BOOLEAN_FORMATTER(this.value ? 'true' : 'false')
}
}
// clone the tag taking into account the type
// the LIST, INT_ARRAY, BYTE_ARRAY, and LONG_ARRAY clone each item into a new list,
// the COMPOUND copies each entry and makes a new compound
clone(): SNBTTag {
if (this.type === SNBTTagType.COMPOUND) {
return new SNBTTag(
this.type,
Object.fromEntries(
Object.entries(this.value as Record<string, SNBTTag>).map(
([key, value]) => [key, value.clone()]
)
)
)
}
if (
this.type === SNBTTagType.LIST ||
this.type === SNBTTagType.INT_ARRAY ||
this.type === SNBTTagType.LONG_ARRAY ||
this.type === SNBTTagType.BYTE_ARRAY
) {
return new SNBTTag(
this.type,
(this.value as SNBTTag[]).map((v) => v.clone())
)
}
return new SNBTTag(this.type, this.value)
}
}
const SNBTUtil = {
//TODO: this does not correctly handle escaped characters
// it should be able to handle escaped characters such as \n \t \s where
// the result of the escape sequence is not the character after the \
unescape(str: string) {
return str.replace(/\\(.)/g, '$1')
},
parseString(str: string): string {
if (str[0] === "'" && str[str.length - 1] === "'") {
return SNBTUtil.unescape(str.slice(1, str.length - 1))
}
if (str[0] === '"' && str[str.length - 1] === '"') {
return SNBTUtil.unescape(str.slice(1, str.length - 1))
}
throw new Error('Invalid string')
},
stringify(str: string) {
const hasSingleQuote = str.indexOf("'") !== -1
const hasDoubleQuote = str.indexOf('"') !== -1
if (hasSingleQuote || hasDoubleQuote) {
if (!hasSingleQuote && hasDoubleQuote) {
return `'${str}'`
} else if (hasSingleQuote && !hasDoubleQuote) {
return `"${str}"`
}
return `"${str.replace(/\"/g, '\\"')}"`
}
return `'${str}'`
},
TAG_Byte(value: number) {
return new SNBTTag(SNBTTagType.BYTE, value)
},
TAG_Short(value: number) {
return new SNBTTag(SNBTTagType.SHORT, value)
},
TAG_Int(value: number) {
return new SNBTTag(SNBTTagType.INT, value)
},
TAG_Long(value: number) {
return new SNBTTag(SNBTTagType.LONG, value)
},
TAG_Float(value: number) {
return new SNBTTag(SNBTTagType.FLOAT, value)
},
TAG_Double(value: number) {
return new SNBTTag(SNBTTagType.DOUBLE, value)
},
TAG_Byte_Array(value: SNBTTag[]) {
return new SNBTTag(SNBTTagType.BYTE_ARRAY, value)
},
TAG_String(value: string) {
return new SNBTTag(SNBTTagType.STRING, value)
},
TAG_List(value: SNBTTag[]) {
return new SNBTTag(SNBTTagType.LIST, value)
},
TAG_Compound(value: Record<string, SNBTTag>) {
return new SNBTTag(SNBTTagType.COMPOUND, value)
},
TAG_Int_Array(value: SNBTTag[]) {
return new SNBTTag(SNBTTagType.INT_ARRAY, value)
},
TAG_Long_Array(value: SNBTTag[]) {
return new SNBTTag(SNBTTagType.LONG_ARRAY, value)
},
TAG_Boolean(value: boolean) {
return new SNBTTag(SNBTTagType.BOOLEAN, value)
},
TAG_End() {
return new SNBTTag(SNBTTagType.END, null)
},
}
// this class is used for itterating over a string.
// supports things such as look ahead and look behind, read, readUntilX
class StringReader {
cursor: number
str: string
constructor(str: string) {
this.cursor = 0
this.str = str.trim()
}
read(length: number) {
const result = this.str.substr(this.cursor, length)
this.cursor += length
if (this.cursor > this.str.length) {
throw new Error('Unexpected end of string')
}
return result
}
readUntil(char: string) {
const result = this.str.substr(this.cursor)
const index = result.indexOf(char)
if (index === -1) {
throw new Error('Unexpected end of string')
}
this.cursor += index + 1
return result.substr(0, index)
}
peek(length: number) {
return this.str.substr(this.cursor, length)
}
peekReversed(length: number) {
if (this.cursor - length < 0) {
return null
}
return this.str.substr(this.cursor - length, length)
}
peekUntil(char: string) {
return this.str.substr(this.str.indexOf(char, this.cursor))
}
skip(length: number) {
this.cursor += length
if (this.cursor > this.str.length) {
throw new Error('Unexpected end of string')
}
}
skipUntil(char: string) {
const index = this.str.indexOf(char, this.cursor)
if (index === -1) {
throw new Error('Unexpected end of string')
}
this.cursor += index + 1
}
skipWhitespace() {
while (
(this.peek(1) === ' ' ||
this.peek(1) === '\n' ||
this.peek(1) === '\r' ||
this.peek(1) === '\t') &&
this.remaining() > 0
) {
this.skip(1)
}
}
isEnd() {
return this.cursor >= this.str.length
}
fork() {
return new StringReader(this.str.substr(this.cursor))
}
readString() {
const start = this.cursor
if (this.peek(1) === '"') this.skip(1)
while (
this.peek(1) !== '"' &&
this.peekReversed(1) !== '\\' &&
!this.isEnd()
) {
this.skip(1)
}
if (this.isEnd()) {
throw new Error('Unexpected end of string')
}
this.skip(1)
const end = this.cursor
return this.str.substr(start, end - start)
}
readSingleQuotedString() {
const start = this.cursor
if (this.peek(1) === "'") this.skip(1)
while (
this.peek(1) !== "'" &&
this.peekReversed(1) !== '\\' &&
!this.isEnd()
) {
this.skip(1)
}
if (this.isEnd()) {
throw new Error('Unexpected end of string')
}
this.skip(1)
const end = this.cursor
return this.str.substr(start, end - start)
}
readUntilMatchingBracket(bracketOpen: string, bracketClose: string) {
const start = this.cursor
let count = this.peek(1) === bracketOpen ? 1 : 0
this.skip(count)
let inString: '"' | "'" | null = null
while (count > 0) {
if (this.isEnd()) throw new Error('Unmatched Brackets')
if (inString !== null) {
if (this.peek(1) === inString) inString = null
} else if (this.peek(1) === '"') {
inString = '"'
} else if (this.peek(1) === "'") {
inString = "'"
} else if (inString === null && this.peek(1) === bracketOpen) {
count++
} else if (this.peek(1) === bracketClose) {
count--
}
this.skip(1)
}
const end = this.cursor
// if (!this.isEnd()) this.skip(1)
return this.str.substr(start, end - start)
}
readUntilAnyOf(chars: string[]) {
const start = this.cursor
while (!chars.some((char) => this.peek(1) === char) && !this.isEnd()) {
this.skip(1)
}
const end = this.cursor
this.skip(1)
return this.str.substr(start, end - start)
}
hasCharInRest(char: string) {
return this.str.indexOf(char, this.cursor) !== -1
}
readUntilNextLogicalBreakOrEnd() {
if (this.peek(1) === '[') {
return this.readUntilMatchingBracket('[', ']')
}
if (this.peek(1) === '{') {
return this.readUntilMatchingBracket('{', '}')
}
if (this.peek(1) === "'") {
return this.readSingleQuotedString()
}
if (this.peek(1) === '"') {
return this.readString()
}
if (this.hasCharInRest(',')) {
return this.readUntil(',')
}
return this.read(this.remaining())
}
readNumber() {
const start = this.cursor
if (this.peek(1) === '-') this.skip(1)
while (
this.peek(1) >= '0' &&
this.peek(1) <= '9' &&
this.remaining() > 0
) {
this.skip(1)
}
const end = this.cursor
return this.str.substr(start, end - start)
}
remaining() {
return this.str.length - this.cursor
}
}
// the parser is used to parse the string into a tree of SNBTTag objects
class SNBTParser {
reader: StringReader
constructor(public input: string) {
this.reader = new StringReader(input)
}
parse() {
this.reader.skipWhitespace()
let result
if (this.reader.peek(1) === '{') {
result = this.parseCompound()
} else if (this.reader.peek(3) === '[B;') {
result = this.parseByteArray()
} else if (this.reader.peek(3) === '[I;') {
result = this.parseIntArray()
} else if (this.reader.peek(3) === '[L;') {
result = this.parseLongArray()
} else if (this.reader.peek(1) === '[') {
result = this.parseList()
} else if (this.reader.peek(1) === '"') {
result = this.parseString()
} else if (this.reader.peek(1) === "'") {
result = this.parseString()
} else if (
this.reader.peek(4) === 'true' ||
this.reader.peek(5) === 'false'
) {
result = this.parseBoolean()
} else if (
this.reader.peek(1) === '-' ||
this.reader.peek(1) === '.' ||
(this.reader.peek(1) >= '0' && this.reader.peek(1) <= '9')
) {
result = this.parseNumber()
} else {
throw new Error('Unexpected character ' + this.reader.peek(1))
}
return result
}
parseCompound(): any {
this.reader.skipWhitespace()
// if (this.reader.peek(2) === '{}') return SNBTUtil.TAG_Compound({})
let contents = this.reader
.readUntilMatchingBracket('{', '}')
.trim()
.substring(1)
contents = contents.substring(0, contents.length - 1)
const reader = new StringReader(contents)
let dict: Record<string, SNBTTag> = {}
while (!reader.isEnd()) {
if (reader.hasCharInRest(':')) {
let name = reader.readUntil(':')
if (name.startsWith('"') && name.endsWith('"')) {
name = name.substring(1, name.length - 1)
}
const value = new SNBTParser(
reader.readUntilNextLogicalBreakOrEnd()
).parse()
dict[name] = value
if (reader.peek(1) === ',') reader.skip(1)
reader.skipWhitespace()
} else {
throw new Error('Expected ":" in compound contents')
}
}
return SNBT.Compound(dict)
}
parseTypedArray(readerFn: (value: string) => any) {
const contents = this.reader.readUntilMatchingBracket('[', ']')
const reader = new StringReader(
contents.substring(3, contents.length - 1)
)
const result = []
while (reader.hasCharInRest(',') && reader.remaining() > 0) {
result.push(readerFn(reader.readUntil(',')))
}
if (reader.remaining() > 0)
result.push(readerFn(reader.read(reader.remaining())))
return result
}
parseByteArray(): any {
return SNBT.Byte_Array(
this.parseTypedArray((v) =>
parseInt(v.endsWith('b') ? v.substring(0, v.length - 1) : v)
)
)
}
parseIntArray(): any {
return SNBT.Int_Array(this.parseTypedArray(parseInt))
}
parseLongArray(): any {
return SNBT.Long_Array(
this.parseTypedArray((v) =>
parseInt(v.endsWith('l') ? v.substring(0, v.length - 1) : v)
)
)
}
parseList(): any {
let contents = this.reader
.readUntilMatchingBracket('[', ']')
.substring(1)
contents = contents.substring(0, contents.length - 1)
const reader = new StringReader(contents)
const result = []
while (reader.remaining() > 0) {
let peek = reader.peek(1)
if (peek === "'") {
result.push(
new SNBTParser(reader.readSingleQuotedString()).parse()
)
} else if (peek === '"') {
result.push(new SNBTParser(reader.readString()).parse())
} else if (peek === '{') {
result.push(
new SNBTParser(
reader.readUntilMatchingBracket('{', '}')
).parse()
)
} else if (peek === '[') {
result.push(
new SNBTParser(
reader.readUntilMatchingBracket('[', ']')
).parse()
)
} else if (reader.hasCharInRest(',')) {
result.push(new SNBTParser(reader.readUntil(',')).parse())
} else {
result.push(
new SNBTParser(reader.read(reader.remaining())).parse()
)
}
if (reader.peek(1) === ',') reader.skip(1)
}
return SNBT.List(result)
}
parseString(): any {
if (this.reader.peek(1) === '"') {
return SNBT.String(SNBTUtil.parseString(this.reader.readString()))
} else {
return SNBT.String(
SNBTUtil.parseString(this.reader.readSingleQuotedString())
)
}
}
parseBoolean(): any {
if (this.reader.peek(4) === 'true') {
this.reader.skip(4)
return SNBT.Boolean(true)
} else {
this.reader.skip(5)
return SNBT.Boolean(false)
}
}
parseNumber(): any {
let int = this.reader.readNumber()
let dec
if (this.reader.peek(1).toLowerCase() === '.') {
this.reader.skip(1)
dec = this.reader.readNumber()
}
if (this.reader.peek(1).toLowerCase() === 'f') {
this.reader.skip(1)
return SNBT.Float(parseFloat(int + '.' + dec))
}
if (this.reader.peek(1).toLowerCase() === 'd') {
this.reader.skip(1)
return SNBT.Double(parseFloat(int + '.' + dec))
}
if (this.reader.peek(1).toLowerCase() === 'l') {
this.reader.skip(1)
return SNBT.Long(parseInt(int + '.' + dec))
}
if (this.reader.peek(1).toLowerCase() === 's') {
this.reader.skip(1)
return SNBT.Short(parseInt(int + '.' + dec))
}
if (this.reader.peek(1).toLowerCase() === 'b') {
this.reader.skip(1)
return SNBT.Byte(parseInt(int + '.' + dec))
}
if (this.reader.peek(1).toLowerCase() === 'i') {
this.reader.skip(1)
return SNBT.Int(parseInt(int))
}
if (!dec) {
return SNBT.Int(parseInt(int))
}
return SNBT.Float(parseInt(int + '.' + dec))
}
}
// a function that removes spaces and newlines from a string except when they are between " and '
export function removeSpacesAndNewlines(str: string): string {
let result = ''
let inString: false | string = false
for (let i = 0; i < str.length; i++) {
if (!inString && (str[i] === '"' || str[i] === "'")) {
inString = str[i] as string
} else if (inString && str[i] === inString && str[i - 1] !== '\\') {
inString = false
}
if (!inString) {
if (str[i] === ' ' && !inString) {
continue
}
if (str[i] === '\n' && !inString) {
continue
}
}
result += str[i]
}
return result
}
export const SNBT = {
parse(str: string): SNBTTag {
let parser = new SNBTParser(removeSpacesAndNewlines(str.trim()))
let result = parser.parse()
if (!parser.reader.isEnd()) {
throw new Error('finished reading before end of string.')
}
return result
},
// type creations
Byte(v: number = 0) {
//assert v is a number between -128 and 127
assert(v >= -128 && v <= 127, 'Byte value must be between -128 and 127')
return SNBTUtil.TAG_Byte(v)
},
Short(v: number = 0) {
//assert v is a number between -32768 and 32767
assert(
v >= -32768 && v <= 32767,
'Short value must be between -32768 and 32767'
)
return SNBTUtil.TAG_Short(v)
},
Int(v: number = 0) {
//assert v is a number between -2147483648 and 2147483647
assert(
v >= -2147483648 && v <= 2147483647,
'Int value must be between -2147483648 and 2147483647'
)
return SNBTUtil.TAG_Int(v)
},
Long(v: number = 0) {
//assert v is a number between -9223372036854775808 and 9223372036854775807
assert(
v >= -9223372036854775808 && v <= 9223372036854775807,
'Long value must be between -9223372036854775808 and 9223372036854775807'
)
return SNBTUtil.TAG_Long(v)
},
Float(v: number = 0) {
//assert v is a number between -3.4028235e+38 and 3.4028235e+38
assert(
v >= -3.4028235e38 && v <= 3.4028235e38,
'Float value must be between -3.4028235e+38 and 3.4028235e+38'
)
return SNBTUtil.TAG_Float(v)
},
Double(v: number = 0) {
//assert v is a number between -1.7976931348623157e+308 and 1.7976931348623157e+308
assert(
v >= -1.7976931348623157e308 && v <= 1.7976931348623157e308,
'Double value must be between -1.7976931348623157e+308 and 1.7976931348623157e+308'
)
return SNBTUtil.TAG_Double(v)
},
Byte_Array(v: number[] = []) {
//assert v is an array of numbers between -128 and 127
assert(
every(v, (x) => x >= -128 && x <= 127),
'Byte array values must be between -128 and 127'
)
return SNBTUtil.TAG_Byte_Array(v.map(SNBT.Byte))
},
String(v: string = '') {
return SNBTUtil.TAG_String(v)
},
List(v: SNBTTag[] = []) {
return SNBTUtil.TAG_List(v)
},
Compound(v: Record<string, SNBTTag> = {}) {
return SNBTUtil.TAG_Compound(v)
},
Int_Array(v: number[] = []) {
//assert v is an array of numbers between -2147483648 and 2147483647
assert(
every(v, (x) => x >= -2147483648 && x <= 2147483647),
'Int array values must be between -2147483648 and 2147483647'
)
return SNBTUtil.TAG_Int_Array(v.map(SNBT.Int))
},
Long_Array(v: number[] = []) {
//assert v is an array of numbers between -9223372036854775808 and 9223372036854775807
assert(
every(
v,
(x) => x >= -9223372036854775808 && x <= 9223372036854775807
),
'Long array values must be between -9223372036854775808 and 9223372036854775807'
)
return SNBTUtil.TAG_Long_Array(v.map(SNBT.Long))
},
Boolean(v: boolean = false) {
return SNBTUtil.TAG_Boolean(v)
},
End() {
return SNBTUtil.TAG_End()
},
merge(a: SNBTTag, b: SNBTTag) {
const workingCopy = a.clone()
workingCopy._merge(b)
return workingCopy
},
}
| 27.732502 | 129 | 0.621608 | 1,002 | 106 | 0 | 95 | 72 | 3 | 68 | 15 | 62 | 3 | 9 | 8.018868 | 10,738 | 0.018719 | 0.006705 | 0.000279 | 0.000279 | 0.000838 | 0.054348 | 0.224638 | 0.252308 | /* Example usages of 'assert' are shown below:
assert(Array.isArray(v), 'expected an array');
assert(value.type === SNBTTagType.BYTE, `Expected BYTE to push to BYTE_ARRAY. Got ${SNBTTagType[value.type]}`);
assert(value.type === SNBTTagType.INT, `Expected INT to push to INT_ARRAY. Got ${SNBTTagType[value.type]}`);
assert(value.type === SNBTTagType.LONG, `Expected LONG to push to LONG_ARRAY. Got ${SNBTTagType[value.type]}`);
//assert v is a number between -128 and 127
assert(v >= -128 && v <= 127, 'Byte value must be between -128 and 127');
//assert v is a number between -32768 and 32767
assert(v >= -32768 && v <= 32767, 'Short value must be between -32768 and 32767');
//assert v is a number between -2147483648 and 2147483647
assert(v >= -2147483648 && v <= 2147483647, 'Int value must be between -2147483648 and 2147483647');
//assert v is a number between -9223372036854775808 and 9223372036854775807
assert(v >= -9223372036854775808 && v <= 9223372036854775807, 'Long value must be between -9223372036854775808 and 9223372036854775807');
//assert v is a number between -3.4028235e+38 and 3.4028235e+38
assert(v >= -3.4028235e38 && v <= 3.4028235e38, 'Float value must be between -3.4028235e+38 and 3.4028235e+38');
//assert v is a number between -1.7976931348623157e+308 and 1.7976931348623157e+308
assert(v >= -1.7976931348623157e308 && v <= 1.7976931348623157e308, 'Double value must be between -1.7976931348623157e+308 and 1.7976931348623157e+308');
//assert v is an array of numbers between -128 and 127
assert(every(v, (x) => x >= -128 && x <= 127), 'Byte array values must be between -128 and 127');
//assert v is an array of numbers between -2147483648 and 2147483647
assert(every(v, (x) => x >= -2147483648 && x <= 2147483647), 'Int array values must be between -2147483648 and 2147483647');
//assert v is an array of numbers between -9223372036854775808 and 9223372036854775807
assert(every(v, (x) => x >= -9223372036854775808 && x <= 9223372036854775807), 'Long array values must be between -9223372036854775808 and 9223372036854775807');
*/
function assert(condition, message?) {
if (!condition) {
throw new Error(message || 'Assertion failed')
}
}
/* Example usages of 'every' are shown below:
//assert v is an array of numbers between -128 and 127
assert(every(v, (x) => x >= -128 && x <= 127), 'Byte array values must be between -128 and 127');
//assert v is an array of numbers between -2147483648 and 2147483647
assert(every(v, (x) => x >= -2147483648 && x <= 2147483647), 'Int array values must be between -2147483648 and 2147483647');
//assert v is an array of numbers between -9223372036854775808 and 9223372036854775807
assert(every(v, (x) => x >= -9223372036854775808 && x <= 9223372036854775807), 'Long array values must be between -9223372036854775808 and 9223372036854775807');
*/
function every<T>(v, arg1) {
assert(Array.isArray(v), 'expected an array')
return !v.find((x) => !arg1(x))
}
export enum SNBTTagType {
END = 0,
BYTE = 1,
SHORT = 2,
INT = 3,
LONG = 4,
FLOAT = 5,
DOUBLE = 6,
BYTE_ARRAY = 7,
STRING = 8,
LIST = 9,
COMPOUND = 10,
INT_ARRAY = 11,
LONG_ARRAY = 12,
BOOLEAN = 13,
}
enum SNBTStringifyFlags {
NONE = 0,
EXCLUDE_TYPE = 1,
}
// this class is a generic for holding an NBT value,
// it supports merge, set, stringify, and clone
/* Example usages of 'typeToConstructor' are shown below:
this.set(path, typeToConstructor(type)());
*/
function typeToConstructor(type) {
switch (type) {
case SNBTTagType.BOOLEAN:
return SNBT.Boolean
case SNBTTagType.BYTE:
return SNBT.Byte
case SNBTTagType.BYTE_ARRAY:
return SNBT.Byte_Array
case SNBTTagType.COMPOUND:
return SNBT.Compound
case SNBTTagType.DOUBLE:
return SNBT.Double
case SNBTTagType.END:
throw new Error(
'SNBTTagType.END should never be used in a SNBT construct'
)
case SNBTTagType.FLOAT:
return SNBT.Float
case SNBTTagType.INT:
return SNBT.Int
case SNBTTagType.INT_ARRAY:
return SNBT.Int_Array
case SNBTTagType.LIST:
return SNBT.List
case SNBTTagType.LONG:
return SNBT.Long
case SNBTTagType.LONG_ARRAY:
return SNBT.Long_Array
case SNBTTagType.SHORT:
return SNBT.Short
case SNBTTagType.STRING:
return SNBT.String
default:
throw `Unknown SNBTTagType ${type}`
}
}
export class SNBTTag {
assert(path, type) {
const gotten = this.get(path)
if (!gotten) {
this.set(path, typeToConstructor(type)())
} else if (!(type === gotten.type)) {
throw Error(
`NBT type at ${path} is not of type ${
SNBTTagType[type]
}. Instead found: ${SNBTTagType[gotten.type]}`
)
}
}
push(...values) {
for (const value of values) {
switch (this.type) {
case SNBTTagType.LIST:
this.value.push(value)
break
case SNBTTagType.BYTE_ARRAY:
assert(
value.type === SNBTTagType.BYTE,
`Expected BYTE to push to BYTE_ARRAY. Got ${
SNBTTagType[value.type]
}`
)
this.value.push(value)
break
case SNBTTagType.INT_ARRAY:
assert(
value.type === SNBTTagType.INT,
`Expected INT to push to INT_ARRAY. Got ${
SNBTTagType[value.type]
}`
)
this.value.push(value)
break
case SNBTTagType.LONG_ARRAY:
assert(
value.type === SNBTTagType.LONG,
`Expected LONG to push to LONG_ARRAY. Got ${
SNBTTagType[value.type]
}`
)
this.value.push(value)
break
default:
throw `Unable to perform push on ${SNBTTagType[this.type]}`
}
}
}
_merge(b) {
// if merging is possible merge otherwise set
if (
(this.type === SNBTTagType.COMPOUND &&
b.type === SNBTTagType.COMPOUND) ||
(this.type === SNBTTagType.LIST && b.type === SNBTTagType.LIST) ||
(this.type === SNBTTagType.INT_ARRAY &&
b.type === SNBTTagType.INT_ARRAY) ||
(this.type === SNBTTagType.LONG_ARRAY &&
b.type === SNBTTagType.LONG_ARRAY) ||
(this.type === SNBTTagType.BYTE_ARRAY &&
b.type === SNBTTagType.BYTE_ARRAY)
) {
for (let [key, value] of Object.entries(
b.value as Record<string, SNBTTag>
)) {
if (!(key in this.value)) {
this.value[key] = value.clone()
} else {
this.value[key]._merge(value)
}
}
} else {
this.type = b.type
this.value = b.value
}
}
constructor(public type, public value) {}
set(path, value) {
let parts = path.split(/(\[\-?\d+\])|\./g).filter(Boolean)
return this._set(parts, value)
}
// traverse the path and set the value
// if the path does not exist, create it
// if the path is a list or compound, set the value at the given key,
//TODO: validate the key is valid for the type
_set(parts, value) {
let key = parts.shift() as string
// if (parts.length === 0) {
// this.value[key] = value;
// }
if (key.startsWith('[') && key.endsWith(']')) {
key = key.substring(1, key.length - 1)
if (
this.type === SNBTTagType.INT_ARRAY ||
this.type === SNBTTagType.LONG_ARRAY ||
this.type === SNBTTagType.BYTE_ARRAY ||
this.type === SNBTTagType.LIST
) {
if (parts.length === 0) {
this.value[
this.value.indexOf(this.value.at(parseInt(key)))
] = value
}
let value2 = this.value.at(parseInt(key))
return value2._set(parts, value)
}
}
if (parts.length === 0) {
if (
this.type === SNBTTagType.COMPOUND ||
this.type === SNBTTagType.LIST ||
this.type === SNBTTagType.INT_ARRAY ||
this.type === SNBTTagType.LONG_ARRAY ||
this.type === SNBTTagType.BYTE_ARRAY
) {
this.value[key] = value
}
return this
}
if (!(key in this.value)) {
this.value[key] = new SNBTTag(SNBTTagType.COMPOUND, {})
}
this.value[key]._set(parts, value)
return this
}
_get(parts) {
if (parts.length === 0) return this
let key = parts.shift() as string
if (key.startsWith('[') && key.endsWith(']')) {
key = key.substring(1, key.length - 1)
if (
this.type === SNBTTagType.INT_ARRAY ||
this.type === SNBTTagType.LONG_ARRAY ||
this.type === SNBTTagType.BYTE_ARRAY ||
this.type === SNBTTagType.LIST
) {
let value = this.value.at(parseInt(key))
if (parts.length === 0) {
return this.value
}
return value._get(parts)
}
}
if (parts.length === 0) {
return this.value[key]
}
if (!(key in this.value)) {
return null
}
return this.value[key]._get(parts)
}
get(path) {
let parts = path.split(/(\[\-?\d+\])|\./g).filter(Boolean)
return this._get(parts)
}
//TODO: the BYTE_ARRAY, INT_ARRAY, and LONG_ARRAY types do not use the type prefix, they make a list with each entry being a Tag
toString(flags = 0) {
const exclude_type = flags & SNBTStringifyFlags.EXCLUDE_TYPE
switch (this.type) {
case SNBTTagType.END:
throw new Error('Cannot convert END tag to string')
case SNBTTagType.BYTE:
return this.value.toString() + (exclude_type ? '' : 'b')
case SNBTTagType.SHORT:
return this.value.toString() + (exclude_type ? '' : 's')
case SNBTTagType.INT:
return this.value.toString()
case SNBTTagType.LONG:
return this.value.toString() + (exclude_type ? '' : 'l')
case SNBTTagType.FLOAT:
return this.value.toString() + (exclude_type ? '' : 'f')
case SNBTTagType.DOUBLE:
return this.value.toString() + Number.isInteger(this.value)
? '.0'
: ''
case SNBTTagType.STRING:
return SNBTUtil.stringify(this.value)
case SNBTTagType.LONG_ARRAY:
case SNBTTagType.BYTE_ARRAY:
case SNBTTagType.LIST:
return '[' + this.value.join(',') + ']'
case SNBTTagType.COMPOUND:
return (
'{' +
Object.entries(this.value as Record<any, SNBTTag>)
.map(([key, value]) => `${key}:${value.toString()}`)
.join(',') +
'}'
)
case SNBTTagType.INT_ARRAY:
return (
'[I;' +
this.value
.map((v) =>
v.toString(SNBTStringifyFlags.EXCLUDE_TYPE)
)
.join(',') +
']'
)
case SNBTTagType.BOOLEAN:
return this.value ? 'true' : 'false'
}
}
toPrettyString(exclude_type?) {
switch (this.type) {
case SNBTTagType.END:
throw new Error('Cannot convert END tag to string')
case SNBTTagType.BYTE:
return this.value.toString() + (exclude_type ? '' : 'b')
case SNBTTagType.SHORT:
return this.value.toString() + (exclude_type ? '' : 's')
case SNBTTagType.INT:
return this.value.toString()
case SNBTTagType.LONG:
return this.value.toString()
case SNBTTagType.FLOAT:
return this.value.toString()
case SNBTTagType.DOUBLE:
return this.value.toString() + Number.isInteger(this.value)
? '.0'
: ''
case SNBTTagType.STRING:
return SNBTUtil.stringify(this.value)
case SNBTTagType.COMPOUND:
return (
'{\n' +
Object.entries(this.value as Record<any, SNBTTag>)
.map(([key, value]) =>
`${key}:${value.toPrettyString()}`
.split('\n')
.map((_) => ` ${_}`)
.join('\n')
)
.join(',\n') +
'\n}'
)
case SNBTTagType.INT_ARRAY: {
let items = this.value.map((item) => item.toPrettyString())
let combined = items.join(',')
let isIndented = items.indexOf('\n') > -1
if (combined.length > 16) isIndented = true
if (isIndented) {
return `[I;\n${items.map((_) => ` ${_}`).join(',\n')}\n]`
}
return '[I;' + combined + ']'
}
case SNBTTagType.BYTE_ARRAY:
case SNBTTagType.LIST:
case SNBTTagType.LONG_ARRAY: {
let items = this.value.map((item) => item.toPrettyString())
let combined = items.join(', ')
let isIndented = combined.indexOf('\n') > -1
if (combined.length > 16) isIndented = true
if (isIndented) {
return `[\n${items
.map((_) =>
_.split('\n')
.map((i) => ` ${i}`)
.join('\n')
)
.join(',\n')}\n]`
}
return '[' + combined + ']'
}
case SNBTTagType.BOOLEAN:
return this.value ? 'true' : 'false'
}
}
toHighlightString(
highlighters,
exclude_type?
) {
/* Example usages of 'NO_SYNTAX_HIGHLIGHTER' are shown below:
name in highlighters
? highlighters[name]
: NO_SYNTAX_HIGHLIGHTER;
*/
function NO_SYNTAX_HIGHLIGHTER(s) {
return s
}
/* Example usages of 'getFormatter' are shown below:
getFormatter('string');
getFormatter('number');
getFormatter('boolean');
getFormatter('brackets');
getFormatter('list');
getFormatter('type_byte');
getFormatter('type_short');
getFormatter('type_int_list');
getFormatter('syntax');
getFormatter('compound_name');
*/
function getFormatter(name) {
return name in highlighters
? highlighters[name]
: NO_SYNTAX_HIGHLIGHTER
}
const STRING_FORMATTER = getFormatter('string')
const NUMBER_FORMATTER = getFormatter('number')
const BOOLEAN_FORMATTER = getFormatter('boolean')
const BRACKET_FORMATTER = getFormatter('brackets')
const ARRAY_FORMATTER = getFormatter('list')
const TYPE_BYTE = getFormatter('type_byte')
const TYPE_SHORT = getFormatter('type_short')
const TYPE_INT = getFormatter('type_int_list')
const SNYTAX = getFormatter('syntax')
const COMPOUND_NAME_FORMATTER = getFormatter('compound_name')
switch (this.type) {
case SNBTTagType.END:
throw new Error('Cannot convert END tag to string')
case SNBTTagType.BYTE:
return (
NUMBER_FORMATTER(this.value.toString()) +
TYPE_BYTE(exclude_type ? '' : 'b')
)
case SNBTTagType.SHORT:
return (
NUMBER_FORMATTER(this.value.toString()) +
TYPE_SHORT(exclude_type ? '' : 's')
)
case SNBTTagType.INT:
return NUMBER_FORMATTER(this.value.toString())
case SNBTTagType.LONG:
return NUMBER_FORMATTER(this.value.toString())
case SNBTTagType.FLOAT:
return NUMBER_FORMATTER(this.value.toString())
case SNBTTagType.DOUBLE:
return NUMBER_FORMATTER(
this.value.toString() + Number.isInteger(this.value)
? '.0'
: ''
)
case SNBTTagType.STRING:
return STRING_FORMATTER(SNBTUtil.stringify(this.value))
case SNBTTagType.COMPOUND:
let entries = Object.entries(this.value as Record<any, SNBTTag>)
if (!entries.length) return BRACKET_FORMATTER(`{}`)
return (
BRACKET_FORMATTER('{') +
'\n' +
entries
.map(([key, value]) =>
`${COMPOUND_NAME_FORMATTER(key)}${SNYTAX(
':'
)}${value.toHighlightString(highlighters)}`
.split('\n')
.map((_) => ` ${_}`)
.join('\n')
)
.join(SNYTAX(',') + '\n') +
'\n' +
BRACKET_FORMATTER('}')
)
case SNBTTagType.INT_ARRAY: {
let items = this.value.map((item) =>
item.toHighlightString(highlighters)
)
let combined = items.join(SNYTAX(','))
let isIndented = items.indexOf('\n') > -1
if (this.value.join(',').length > 16) isIndented = true
if (isIndented) {
return `${ARRAY_FORMATTER('[')}${TYPE_INT('I')};\n${items
.map((_) => ` ${_}`)
.join(SNYTAX(',') + '\n')}\n${ARRAY_FORMATTER(']')}`
}
return (
`${ARRAY_FORMATTER('[')}${TYPE_INT('I')};` +
combined +
ARRAY_FORMATTER(']')
)
}
case SNBTTagType.BYTE_ARRAY:
case SNBTTagType.LIST:
case SNBTTagType.LONG_ARRAY: {
let items = this.value.map((item) =>
item.toHighlightString(highlighters)
)
let combined = items.join(', ')
let isIndented = combined.indexOf('\n') > -1
if (combined.length > 16) isIndented = true
if (isIndented) {
return `${ARRAY_FORMATTER('[')}\n${items
.map((_) =>
_.split('\n')
.map((i) => ` ${i}`)
.join('\n')
)
.join(SNYTAX(',') + '\n')}\n${ARRAY_FORMATTER(']')}`
}
return ARRAY_FORMATTER('[') + combined + ARRAY_FORMATTER(']')
}
case SNBTTagType.BOOLEAN:
return BOOLEAN_FORMATTER(this.value ? 'true' : 'false')
}
}
// clone the tag taking into account the type
// the LIST, INT_ARRAY, BYTE_ARRAY, and LONG_ARRAY clone each item into a new list,
// the COMPOUND copies each entry and makes a new compound
clone() {
if (this.type === SNBTTagType.COMPOUND) {
return new SNBTTag(
this.type,
Object.fromEntries(
Object.entries(this.value as Record<string, SNBTTag>).map(
([key, value]) => [key, value.clone()]
)
)
)
}
if (
this.type === SNBTTagType.LIST ||
this.type === SNBTTagType.INT_ARRAY ||
this.type === SNBTTagType.LONG_ARRAY ||
this.type === SNBTTagType.BYTE_ARRAY
) {
return new SNBTTag(
this.type,
(this.value as SNBTTag[]).map((v) => v.clone())
)
}
return new SNBTTag(this.type, this.value)
}
}
const SNBTUtil = {
//TODO: this does not correctly handle escaped characters
// it should be able to handle escaped characters such as \n \t \s where
// the result of the escape sequence is not the character after the \
unescape(str) {
return str.replace(/\\(.)/g, '$1')
},
parseString(str) {
if (str[0] === "'" && str[str.length - 1] === "'") {
return SNBTUtil.unescape(str.slice(1, str.length - 1))
}
if (str[0] === '"' && str[str.length - 1] === '"') {
return SNBTUtil.unescape(str.slice(1, str.length - 1))
}
throw new Error('Invalid string')
},
stringify(str) {
const hasSingleQuote = str.indexOf("'") !== -1
const hasDoubleQuote = str.indexOf('"') !== -1
if (hasSingleQuote || hasDoubleQuote) {
if (!hasSingleQuote && hasDoubleQuote) {
return `'${str}'`
} else if (hasSingleQuote && !hasDoubleQuote) {
return `"${str}"`
}
return `"${str.replace(/\"/g, '\\"')}"`
}
return `'${str}'`
},
TAG_Byte(value) {
return new SNBTTag(SNBTTagType.BYTE, value)
},
TAG_Short(value) {
return new SNBTTag(SNBTTagType.SHORT, value)
},
TAG_Int(value) {
return new SNBTTag(SNBTTagType.INT, value)
},
TAG_Long(value) {
return new SNBTTag(SNBTTagType.LONG, value)
},
TAG_Float(value) {
return new SNBTTag(SNBTTagType.FLOAT, value)
},
TAG_Double(value) {
return new SNBTTag(SNBTTagType.DOUBLE, value)
},
TAG_Byte_Array(value) {
return new SNBTTag(SNBTTagType.BYTE_ARRAY, value)
},
TAG_String(value) {
return new SNBTTag(SNBTTagType.STRING, value)
},
TAG_List(value) {
return new SNBTTag(SNBTTagType.LIST, value)
},
TAG_Compound(value) {
return new SNBTTag(SNBTTagType.COMPOUND, value)
},
TAG_Int_Array(value) {
return new SNBTTag(SNBTTagType.INT_ARRAY, value)
},
TAG_Long_Array(value) {
return new SNBTTag(SNBTTagType.LONG_ARRAY, value)
},
TAG_Boolean(value) {
return new SNBTTag(SNBTTagType.BOOLEAN, value)
},
TAG_End() {
return new SNBTTag(SNBTTagType.END, null)
},
}
// this class is used for itterating over a string.
// supports things such as look ahead and look behind, read, readUntilX
class StringReader {
cursor
str
constructor(str) {
this.cursor = 0
this.str = str.trim()
}
read(length) {
const result = this.str.substr(this.cursor, length)
this.cursor += length
if (this.cursor > this.str.length) {
throw new Error('Unexpected end of string')
}
return result
}
readUntil(char) {
const result = this.str.substr(this.cursor)
const index = result.indexOf(char)
if (index === -1) {
throw new Error('Unexpected end of string')
}
this.cursor += index + 1
return result.substr(0, index)
}
peek(length) {
return this.str.substr(this.cursor, length)
}
peekReversed(length) {
if (this.cursor - length < 0) {
return null
}
return this.str.substr(this.cursor - length, length)
}
peekUntil(char) {
return this.str.substr(this.str.indexOf(char, this.cursor))
}
skip(length) {
this.cursor += length
if (this.cursor > this.str.length) {
throw new Error('Unexpected end of string')
}
}
skipUntil(char) {
const index = this.str.indexOf(char, this.cursor)
if (index === -1) {
throw new Error('Unexpected end of string')
}
this.cursor += index + 1
}
skipWhitespace() {
while (
(this.peek(1) === ' ' ||
this.peek(1) === '\n' ||
this.peek(1) === '\r' ||
this.peek(1) === '\t') &&
this.remaining() > 0
) {
this.skip(1)
}
}
isEnd() {
return this.cursor >= this.str.length
}
fork() {
return new StringReader(this.str.substr(this.cursor))
}
readString() {
const start = this.cursor
if (this.peek(1) === '"') this.skip(1)
while (
this.peek(1) !== '"' &&
this.peekReversed(1) !== '\\' &&
!this.isEnd()
) {
this.skip(1)
}
if (this.isEnd()) {
throw new Error('Unexpected end of string')
}
this.skip(1)
const end = this.cursor
return this.str.substr(start, end - start)
}
readSingleQuotedString() {
const start = this.cursor
if (this.peek(1) === "'") this.skip(1)
while (
this.peek(1) !== "'" &&
this.peekReversed(1) !== '\\' &&
!this.isEnd()
) {
this.skip(1)
}
if (this.isEnd()) {
throw new Error('Unexpected end of string')
}
this.skip(1)
const end = this.cursor
return this.str.substr(start, end - start)
}
readUntilMatchingBracket(bracketOpen, bracketClose) {
const start = this.cursor
let count = this.peek(1) === bracketOpen ? 1 : 0
this.skip(count)
let inString = null
while (count > 0) {
if (this.isEnd()) throw new Error('Unmatched Brackets')
if (inString !== null) {
if (this.peek(1) === inString) inString = null
} else if (this.peek(1) === '"') {
inString = '"'
} else if (this.peek(1) === "'") {
inString = "'"
} else if (inString === null && this.peek(1) === bracketOpen) {
count++
} else if (this.peek(1) === bracketClose) {
count--
}
this.skip(1)
}
const end = this.cursor
// if (!this.isEnd()) this.skip(1)
return this.str.substr(start, end - start)
}
readUntilAnyOf(chars) {
const start = this.cursor
while (!chars.some((char) => this.peek(1) === char) && !this.isEnd()) {
this.skip(1)
}
const end = this.cursor
this.skip(1)
return this.str.substr(start, end - start)
}
hasCharInRest(char) {
return this.str.indexOf(char, this.cursor) !== -1
}
readUntilNextLogicalBreakOrEnd() {
if (this.peek(1) === '[') {
return this.readUntilMatchingBracket('[', ']')
}
if (this.peek(1) === '{') {
return this.readUntilMatchingBracket('{', '}')
}
if (this.peek(1) === "'") {
return this.readSingleQuotedString()
}
if (this.peek(1) === '"') {
return this.readString()
}
if (this.hasCharInRest(',')) {
return this.readUntil(',')
}
return this.read(this.remaining())
}
readNumber() {
const start = this.cursor
if (this.peek(1) === '-') this.skip(1)
while (
this.peek(1) >= '0' &&
this.peek(1) <= '9' &&
this.remaining() > 0
) {
this.skip(1)
}
const end = this.cursor
return this.str.substr(start, end - start)
}
remaining() {
return this.str.length - this.cursor
}
}
// the parser is used to parse the string into a tree of SNBTTag objects
class SNBTParser {
reader
constructor(public input) {
this.reader = new StringReader(input)
}
parse() {
this.reader.skipWhitespace()
let result
if (this.reader.peek(1) === '{') {
result = this.parseCompound()
} else if (this.reader.peek(3) === '[B;') {
result = this.parseByteArray()
} else if (this.reader.peek(3) === '[I;') {
result = this.parseIntArray()
} else if (this.reader.peek(3) === '[L;') {
result = this.parseLongArray()
} else if (this.reader.peek(1) === '[') {
result = this.parseList()
} else if (this.reader.peek(1) === '"') {
result = this.parseString()
} else if (this.reader.peek(1) === "'") {
result = this.parseString()
} else if (
this.reader.peek(4) === 'true' ||
this.reader.peek(5) === 'false'
) {
result = this.parseBoolean()
} else if (
this.reader.peek(1) === '-' ||
this.reader.peek(1) === '.' ||
(this.reader.peek(1) >= '0' && this.reader.peek(1) <= '9')
) {
result = this.parseNumber()
} else {
throw new Error('Unexpected character ' + this.reader.peek(1))
}
return result
}
parseCompound() {
this.reader.skipWhitespace()
// if (this.reader.peek(2) === '{}') return SNBTUtil.TAG_Compound({})
let contents = this.reader
.readUntilMatchingBracket('{', '}')
.trim()
.substring(1)
contents = contents.substring(0, contents.length - 1)
const reader = new StringReader(contents)
let dict = {}
while (!reader.isEnd()) {
if (reader.hasCharInRest(':')) {
let name = reader.readUntil(':')
if (name.startsWith('"') && name.endsWith('"')) {
name = name.substring(1, name.length - 1)
}
const value = new SNBTParser(
reader.readUntilNextLogicalBreakOrEnd()
).parse()
dict[name] = value
if (reader.peek(1) === ',') reader.skip(1)
reader.skipWhitespace()
} else {
throw new Error('Expected ":" in compound contents')
}
}
return SNBT.Compound(dict)
}
parseTypedArray(readerFn) {
const contents = this.reader.readUntilMatchingBracket('[', ']')
const reader = new StringReader(
contents.substring(3, contents.length - 1)
)
const result = []
while (reader.hasCharInRest(',') && reader.remaining() > 0) {
result.push(readerFn(reader.readUntil(',')))
}
if (reader.remaining() > 0)
result.push(readerFn(reader.read(reader.remaining())))
return result
}
parseByteArray() {
return SNBT.Byte_Array(
this.parseTypedArray((v) =>
parseInt(v.endsWith('b') ? v.substring(0, v.length - 1) : v)
)
)
}
parseIntArray() {
return SNBT.Int_Array(this.parseTypedArray(parseInt))
}
parseLongArray() {
return SNBT.Long_Array(
this.parseTypedArray((v) =>
parseInt(v.endsWith('l') ? v.substring(0, v.length - 1) : v)
)
)
}
parseList() {
let contents = this.reader
.readUntilMatchingBracket('[', ']')
.substring(1)
contents = contents.substring(0, contents.length - 1)
const reader = new StringReader(contents)
const result = []
while (reader.remaining() > 0) {
let peek = reader.peek(1)
if (peek === "'") {
result.push(
new SNBTParser(reader.readSingleQuotedString()).parse()
)
} else if (peek === '"') {
result.push(new SNBTParser(reader.readString()).parse())
} else if (peek === '{') {
result.push(
new SNBTParser(
reader.readUntilMatchingBracket('{', '}')
).parse()
)
} else if (peek === '[') {
result.push(
new SNBTParser(
reader.readUntilMatchingBracket('[', ']')
).parse()
)
} else if (reader.hasCharInRest(',')) {
result.push(new SNBTParser(reader.readUntil(',')).parse())
} else {
result.push(
new SNBTParser(reader.read(reader.remaining())).parse()
)
}
if (reader.peek(1) === ',') reader.skip(1)
}
return SNBT.List(result)
}
parseString() {
if (this.reader.peek(1) === '"') {
return SNBT.String(SNBTUtil.parseString(this.reader.readString()))
} else {
return SNBT.String(
SNBTUtil.parseString(this.reader.readSingleQuotedString())
)
}
}
parseBoolean() {
if (this.reader.peek(4) === 'true') {
this.reader.skip(4)
return SNBT.Boolean(true)
} else {
this.reader.skip(5)
return SNBT.Boolean(false)
}
}
parseNumber() {
let int = this.reader.readNumber()
let dec
if (this.reader.peek(1).toLowerCase() === '.') {
this.reader.skip(1)
dec = this.reader.readNumber()
}
if (this.reader.peek(1).toLowerCase() === 'f') {
this.reader.skip(1)
return SNBT.Float(parseFloat(int + '.' + dec))
}
if (this.reader.peek(1).toLowerCase() === 'd') {
this.reader.skip(1)
return SNBT.Double(parseFloat(int + '.' + dec))
}
if (this.reader.peek(1).toLowerCase() === 'l') {
this.reader.skip(1)
return SNBT.Long(parseInt(int + '.' + dec))
}
if (this.reader.peek(1).toLowerCase() === 's') {
this.reader.skip(1)
return SNBT.Short(parseInt(int + '.' + dec))
}
if (this.reader.peek(1).toLowerCase() === 'b') {
this.reader.skip(1)
return SNBT.Byte(parseInt(int + '.' + dec))
}
if (this.reader.peek(1).toLowerCase() === 'i') {
this.reader.skip(1)
return SNBT.Int(parseInt(int))
}
if (!dec) {
return SNBT.Int(parseInt(int))
}
return SNBT.Float(parseInt(int + '.' + dec))
}
}
// a function that removes spaces and newlines from a string except when they are between " and '
export /* Example usages of 'removeSpacesAndNewlines' are shown below:
new SNBTParser(removeSpacesAndNewlines(str.trim()));
*/
function removeSpacesAndNewlines(str) {
let result = ''
let inString = false
for (let i = 0; i < str.length; i++) {
if (!inString && (str[i] === '"' || str[i] === "'")) {
inString = str[i] as string
} else if (inString && str[i] === inString && str[i - 1] !== '\\') {
inString = false
}
if (!inString) {
if (str[i] === ' ' && !inString) {
continue
}
if (str[i] === '\n' && !inString) {
continue
}
}
result += str[i]
}
return result
}
export const SNBT = {
parse(str) {
let parser = new SNBTParser(removeSpacesAndNewlines(str.trim()))
let result = parser.parse()
if (!parser.reader.isEnd()) {
throw new Error('finished reading before end of string.')
}
return result
},
// type creations
Byte(v = 0) {
//assert v is a number between -128 and 127
assert(v >= -128 && v <= 127, 'Byte value must be between -128 and 127')
return SNBTUtil.TAG_Byte(v)
},
Short(v = 0) {
//assert v is a number between -32768 and 32767
assert(
v >= -32768 && v <= 32767,
'Short value must be between -32768 and 32767'
)
return SNBTUtil.TAG_Short(v)
},
Int(v = 0) {
//assert v is a number between -2147483648 and 2147483647
assert(
v >= -2147483648 && v <= 2147483647,
'Int value must be between -2147483648 and 2147483647'
)
return SNBTUtil.TAG_Int(v)
},
Long(v = 0) {
//assert v is a number between -9223372036854775808 and 9223372036854775807
assert(
v >= -9223372036854775808 && v <= 9223372036854775807,
'Long value must be between -9223372036854775808 and 9223372036854775807'
)
return SNBTUtil.TAG_Long(v)
},
Float(v = 0) {
//assert v is a number between -3.4028235e+38 and 3.4028235e+38
assert(
v >= -3.4028235e38 && v <= 3.4028235e38,
'Float value must be between -3.4028235e+38 and 3.4028235e+38'
)
return SNBTUtil.TAG_Float(v)
},
Double(v = 0) {
//assert v is a number between -1.7976931348623157e+308 and 1.7976931348623157e+308
assert(
v >= -1.7976931348623157e308 && v <= 1.7976931348623157e308,
'Double value must be between -1.7976931348623157e+308 and 1.7976931348623157e+308'
)
return SNBTUtil.TAG_Double(v)
},
Byte_Array(v = []) {
//assert v is an array of numbers between -128 and 127
assert(
every(v, (x) => x >= -128 && x <= 127),
'Byte array values must be between -128 and 127'
)
return SNBTUtil.TAG_Byte_Array(v.map(SNBT.Byte))
},
String(v = '') {
return SNBTUtil.TAG_String(v)
},
List(v = []) {
return SNBTUtil.TAG_List(v)
},
Compound(v = {}) {
return SNBTUtil.TAG_Compound(v)
},
Int_Array(v = []) {
//assert v is an array of numbers between -2147483648 and 2147483647
assert(
every(v, (x) => x >= -2147483648 && x <= 2147483647),
'Int array values must be between -2147483648 and 2147483647'
)
return SNBTUtil.TAG_Int_Array(v.map(SNBT.Int))
},
Long_Array(v = []) {
//assert v is an array of numbers between -9223372036854775808 and 9223372036854775807
assert(
every(
v,
(x) => x >= -9223372036854775808 && x <= 9223372036854775807
),
'Long array values must be between -9223372036854775808 and 9223372036854775807'
)
return SNBTUtil.TAG_Long_Array(v.map(SNBT.Long))
},
Boolean(v = false) {
return SNBTUtil.TAG_Boolean(v)
},
End() {
return SNBTUtil.TAG_End()
},
merge(a, b) {
const workingCopy = a.clone()
workingCopy._merge(b)
return workingCopy
},
}
|
e997c868e76e4bdf3af1aab3d9f2ccc201d6a11a | 4,812 | ts | TypeScript | frontend/lib/cyberconnect/schema.ts | strict-beauty/CCTwitter | 2f6537b9903daaa8fc7ecc7c4e250334dc7417ca | [
"MIT"
] | 2 | 2022-02-09T09:27:14.000Z | 2022-03-21T18:55:38.000Z | frontend/lib/cyberconnect/schema.ts | strict-beauty/CCTwitter | 2f6537b9903daaa8fc7ecc7c4e250334dc7417ca | [
"MIT"
] | null | null | null | frontend/lib/cyberconnect/schema.ts | strict-beauty/CCTwitter | 2f6537b9903daaa8fc7ecc7c4e250334dc7417ca | [
"MIT"
] | null | null | null | /**
*
*/
export const identitySchema = ({
address,
namespace,
network,
followingFirst,
followingAfter,
followerFirst,
followerAfter,
}) => {
return {
operationName: "identityQuery",
query: `query identityQuery(
$address: String!,
$namespace: String,
$network: Network,
$followingFirst: Int,
$followingAfter: String,
$followerFirst: Int,
$followerAfter: String) {
identity(address: $address, network: $network) {
domain,
address,
avatar,
followingCount(namespace: $namespace),
followerCount(namespace: $namespace),
followings(namespace: $namespace, first: $followingFirst, after: $followingAfter) {
pageInfo {
endCursor,
hasNextPage
},
list {
address,
domain,
avatar
}
}
followers(namespace: $namespace, first: $followerFirst, after: $followerAfter) {
pageInfo {
endCursor
hasNextPage
}
list {
address
domain
avatar
}
}
}
}`,
variables: {
address,
namespace,
network,
followingFirst,
followingAfter,
followerFirst,
followerAfter,
},
};
};
export const simpleIdentitySchema = ({ address, network }) => {
return {
operationName: "userInfoQuery",
query: `query userInfoQuery($address: String!, $network: Network) {
identity(address: $address, network: $network) {
address,
domain,
avatar,
}
}`,
variables: {
address,
network,
},
};
};
export const followInfoSchema = ({
fromAddr,
toAddr,
namespace,
network,
}) => {
return {
operationName: "followInfo",
query: `query followInfo($fromAddr: String!, $toAddr: String!, $namespace: String, $network: Network) {
identity(address: $toAddr, network: $network) {
address
domain
avatar
ens
}
followStatus(fromAddr: $fromAddr, toAddr: $toAddr, namespace: $namespace, network: $network) {
isFollowed
isFollowing
}
}`,
variables: {
fromAddr,
toAddr,
namespace,
network,
},
};
};
export const registerKeySchema = ({ address, message, signature, network }) => {
return {
operationName: "registerKeySchema",
query: `mutation registerKeySchema($input: RegisterKeyInput!){
registerKey(input:$input){
result
}
}`,
variables: {
input: {
address,
message,
signature,
network,
},
},
};
};
export const recommendsSchema = ({
address,
filter,
first,
after,
network,
}) => {
return {
operationName: "recommendationsQuery",
query: `query recommendationsQuery (
$address: String!,
$filter: RecommFilter,
$network: Network,
$first: Int,
$after: String){
recommendations (
address: $address,
filter: $filter,
network: $network,
first: $first,
after: $after){
result,
data{
pageInfo{
startCursor,
endCursor,
hasNextPage,
hasPreviousPage,
},
list{
address,
domain,
avatar,
recommendationReason,
followerCount
}
}
}
}`,
variables: {
address,
filter,
first,
after,
network,
},
};
};
export const homePageSchema = ({ network }) => {
return {
operationName: "homePage",
query: `query homePage($network: Network){
homePage(network: $network){
userCount
connectionCount
}
}`,
variables: {
network,
},
};
};
/*
mutation {
registerKey(
input: {
address: "0xF791ff20C453b718a85721C0E543a788E73D1eEc",
message: "xxx",
signature: "0xec531ac049f1f635de8db0ace48a44b7ef7545034ef1b19ca3e40443299bfb0756a5850a0bc5eff61cc71f67565f5e13bf191f421052cbe48be1d7bf58915fe01c",
network: ETH
}
) {
result
}
}
query {
identity(
address: "0x073443ce5ae3e53a57b4a5671b69bde0e9b772de"
network: ETH
) {
domain,
avatar,
address
}
}
query {
recommendations (
address: "0x073443ce5ae3e53a57b4a5671b69bde0e9b772de",
filter: SOCIAL,
network: ETH,
first: 20,
after: "-1"){
result,
data{
pageInfo{
startCursor,
endCursor,
hasNextPage,
hasPreviousPage,
},
list{
address,
domain,
avatar,
recommendationReason,
followerCount
}
}
}
}
*/
| 19.248 | 152 | 0.542186 | 184 | 6 | 0 | 6 | 6 | 0 | 0 | 0 | 0 | 0 | 0 | 25.5 | 1,285 | 0.009339 | 0.004669 | 0 | 0 | 0 | 0 | 0 | 0.207211 | /**
*
*/
export const identitySchema = ({
address,
namespace,
network,
followingFirst,
followingAfter,
followerFirst,
followerAfter,
}) => {
return {
operationName: "identityQuery",
query: `query identityQuery(
$address: String!,
$namespace: String,
$network: Network,
$followingFirst: Int,
$followingAfter: String,
$followerFirst: Int,
$followerAfter: String) {
identity(address: $address, network: $network) {
domain,
address,
avatar,
followingCount(namespace: $namespace),
followerCount(namespace: $namespace),
followings(namespace: $namespace, first: $followingFirst, after: $followingAfter) {
pageInfo {
endCursor,
hasNextPage
},
list {
address,
domain,
avatar
}
}
followers(namespace: $namespace, first: $followerFirst, after: $followerAfter) {
pageInfo {
endCursor
hasNextPage
}
list {
address
domain
avatar
}
}
}
}`,
variables: {
address,
namespace,
network,
followingFirst,
followingAfter,
followerFirst,
followerAfter,
},
};
};
export const simpleIdentitySchema = ({ address, network }) => {
return {
operationName: "userInfoQuery",
query: `query userInfoQuery($address: String!, $network: Network) {
identity(address: $address, network: $network) {
address,
domain,
avatar,
}
}`,
variables: {
address,
network,
},
};
};
export const followInfoSchema = ({
fromAddr,
toAddr,
namespace,
network,
}) => {
return {
operationName: "followInfo",
query: `query followInfo($fromAddr: String!, $toAddr: String!, $namespace: String, $network: Network) {
identity(address: $toAddr, network: $network) {
address
domain
avatar
ens
}
followStatus(fromAddr: $fromAddr, toAddr: $toAddr, namespace: $namespace, network: $network) {
isFollowed
isFollowing
}
}`,
variables: {
fromAddr,
toAddr,
namespace,
network,
},
};
};
export const registerKeySchema = ({ address, message, signature, network }) => {
return {
operationName: "registerKeySchema",
query: `mutation registerKeySchema($input: RegisterKeyInput!){
registerKey(input:$input){
result
}
}`,
variables: {
input: {
address,
message,
signature,
network,
},
},
};
};
export const recommendsSchema = ({
address,
filter,
first,
after,
network,
}) => {
return {
operationName: "recommendationsQuery",
query: `query recommendationsQuery (
$address: String!,
$filter: RecommFilter,
$network: Network,
$first: Int,
$after: String){
recommendations (
address: $address,
filter: $filter,
network: $network,
first: $first,
after: $after){
result,
data{
pageInfo{
startCursor,
endCursor,
hasNextPage,
hasPreviousPage,
},
list{
address,
domain,
avatar,
recommendationReason,
followerCount
}
}
}
}`,
variables: {
address,
filter,
first,
after,
network,
},
};
};
export const homePageSchema = ({ network }) => {
return {
operationName: "homePage",
query: `query homePage($network: Network){
homePage(network: $network){
userCount
connectionCount
}
}`,
variables: {
network,
},
};
};
/*
mutation {
registerKey(
input: {
address: "0xF791ff20C453b718a85721C0E543a788E73D1eEc",
message: "xxx",
signature: "0xec531ac049f1f635de8db0ace48a44b7ef7545034ef1b19ca3e40443299bfb0756a5850a0bc5eff61cc71f67565f5e13bf191f421052cbe48be1d7bf58915fe01c",
network: ETH
}
) {
result
}
}
query {
identity(
address: "0x073443ce5ae3e53a57b4a5671b69bde0e9b772de"
network: ETH
) {
domain,
avatar,
address
}
}
query {
recommendations (
address: "0x073443ce5ae3e53a57b4a5671b69bde0e9b772de",
filter: SOCIAL,
network: ETH,
first: 20,
after: "-1"){
result,
data{
pageInfo{
startCursor,
endCursor,
hasNextPage,
hasPreviousPage,
},
list{
address,
domain,
avatar,
recommendationReason,
followerCount
}
}
}
}
*/
|
e99ffa6521e270e17625094f6d846a6a2e7d6a67 | 1,262 | ts | TypeScript | bisasam/src/hooks/useTokenizeText.ts | Louis3797/social-media-app | 5af9b58d8d40f1ed408caa213e98c2b522c8629c | [
"MIT"
] | 1 | 2022-03-06T13:01:15.000Z | 2022-03-06T13:01:15.000Z | bisasam/src/hooks/useTokenizeText.ts | Louis3797/social-media-app | 5af9b58d8d40f1ed408caa213e98c2b522c8629c | [
"MIT"
] | null | null | null | bisasam/src/hooks/useTokenizeText.ts | Louis3797/social-media-app | 5af9b58d8d40f1ed408caa213e98c2b522c8629c | [
"MIT"
] | null | null | null | export const useTokenizeText = (
untransformedText: string
): readonly [
[
{
t: string;
v: string;
}
]
] => {
const tokens = [] as unknown as [
{
t: string;
v: string;
}
];
function isMention(text: string): boolean {
if (text.substr(0, 1) === "@") {
return true;
}
return false;
}
function isLink(text: string): boolean {
if (text.substr(0, 4) === "https" || text.substr(0, 4) === "http") {
return true;
}
return false;
}
function isHashtag(text: string): boolean {
if (
text.substr(0, 1) === "#" &&
text.length > 1 &&
text.slice(1).includes("#") === false
) {
return true;
}
return false;
}
function testToken(item: string): void {
if (isMention(item)) {
tokens.push({
t: "mention",
v: item,
});
} else if (isHashtag(item)) {
tokens.push({
t: "hashtag",
v: item,
});
} else if (isLink(item)) {
tokens.push({
t: "link",
v: item,
});
} else {
tokens.push({
t: "text",
v: item,
});
}
}
untransformedText.split(" ").forEach((item) => testToken(item));
return [tokens] as const;
};
| 17.774648 | 72 | 0.477021 | 64 | 6 | 0 | 6 | 2 | 0 | 4 | 0 | 14 | 0 | 3 | 15.166667 | 374 | 0.032086 | 0.005348 | 0 | 0 | 0.008021 | 0 | 1 | 0.261161 | export const useTokenizeText = (
untransformedText
) => {
const tokens = [] as unknown as [
{
t;
v;
}
];
/* Example usages of 'isMention' are shown below:
isMention(item);
*/
function isMention(text) {
if (text.substr(0, 1) === "@") {
return true;
}
return false;
}
/* Example usages of 'isLink' are shown below:
isLink(item);
*/
function isLink(text) {
if (text.substr(0, 4) === "https" || text.substr(0, 4) === "http") {
return true;
}
return false;
}
/* Example usages of 'isHashtag' are shown below:
isHashtag(item);
*/
function isHashtag(text) {
if (
text.substr(0, 1) === "#" &&
text.length > 1 &&
text.slice(1).includes("#") === false
) {
return true;
}
return false;
}
/* Example usages of 'testToken' are shown below:
testToken(item);
*/
function testToken(item) {
if (isMention(item)) {
tokens.push({
t: "mention",
v: item,
});
} else if (isHashtag(item)) {
tokens.push({
t: "hashtag",
v: item,
});
} else if (isLink(item)) {
tokens.push({
t: "link",
v: item,
});
} else {
tokens.push({
t: "text",
v: item,
});
}
}
untransformedText.split(" ").forEach((item) => testToken(item));
return [tokens] as const;
};
|
e9c20da04d7de4efaaafdfa61bbf6bc6a30da9b0 | 1,854 | ts | TypeScript | src/app/components/Analysis/TimeSeriesAnalysis/TimeSeriesAnalysisRepository.ts | Seibi0928/workspace | 80477130e83191050a5ab831e8cc4591e832aff0 | [
"MIT"
] | 1 | 2022-03-04T05:20:10.000Z | 2022-03-04T05:20:10.000Z | src/app/components/Analysis/TimeSeriesAnalysis/TimeSeriesAnalysisRepository.ts | Seibi0928/ResearchXBRL.Frontend | 80477130e83191050a5ab831e8cc4591e832aff0 | [
"MIT"
] | null | null | null | src/app/components/Analysis/TimeSeriesAnalysis/TimeSeriesAnalysisRepository.ts | Seibi0928/ResearchXBRL.Frontend | 80477130e83191050a5ab831e8cc4591e832aff0 | [
"MIT"
] | null | null | null | export interface TimeSeriesAnalysisRepository {
getAnalysisResult(corporationId: string, accountItemName: string): Promise<TimeSeriesAnalysisViewModel>;
}
export const isInstantPeriod = (period: AccountPeriod): period is InstantPeriod => {
const mayBeInstant = period as InstantPeriod;
return mayBeInstant.instant?.length > 0 ?? false;
}
export const comparePeriod = (a: TimeSeriesAnalysisValue, b: TimeSeriesAnalysisValue): number => {
if (isInstantPeriod(a.financialAccountPeriod)
&& isInstantPeriod(b.financialAccountPeriod)) {
return a.financialAccountPeriod.instant
.localeCompare(b.financialAccountPeriod.instant);
}
else if (!isInstantPeriod(a.financialAccountPeriod)
&& !isInstantPeriod(b.financialAccountPeriod)) {
return a.financialAccountPeriod.from
.localeCompare(b.financialAccountPeriod.from);
}
throw new Error('単位情報に不整合があります');
}
export type AccountPeriod = InstantPeriod | DurationPeriod;
export type InstantPeriod = {
instant: string
};
export type DurationPeriod = {
from: string,
to: string
}
export type TimeSeriesAnalysisValue = {
financialAccountPeriod: AccountPeriod
amount: number
};
export type TimeSeriesAnalysisViewModel = {
accountName: string,
unit: Unit,
corporation: { name: string },
consolidatedValues: TimeSeriesAnalysisValue[],
nonConsolidatedValues: TimeSeriesAnalysisValue[],
}
export type Unit = NormalUnit | DividedUnit
export type BaseUnit = { name: string }
export type NormalUnit = {
measure: string
} & BaseUnit
export type DividedUnit = {
unitNumerator: string,
unitDenominator: string
} & BaseUnit
export const isNormalUnit = (unit: Unit): unit is NormalUnit => {
const maybeNormalUnit = unit as DividedUnit;
return maybeNormalUnit.unitNumerator === null;
}; | 34.333333 | 108 | 0.734628 | 52 | 3 | 1 | 6 | 5 | 11 | 1 | 0 | 13 | 10 | 2 | 5 | 443 | 0.020316 | 0.011287 | 0.024831 | 0.022573 | 0.004515 | 0 | 0.5 | 0.289807 | export interface TimeSeriesAnalysisRepository {
getAnalysisResult(corporationId, accountItemName);
}
export /* Example usages of 'isInstantPeriod' are shown below:
isInstantPeriod(a.financialAccountPeriod)
&& isInstantPeriod(b.financialAccountPeriod);
!isInstantPeriod(a.financialAccountPeriod)
&& !isInstantPeriod(b.financialAccountPeriod);
*/
const isInstantPeriod = (period): period is InstantPeriod => {
const mayBeInstant = period as InstantPeriod;
return mayBeInstant.instant?.length > 0 ?? false;
}
export const comparePeriod = (a, b) => {
if (isInstantPeriod(a.financialAccountPeriod)
&& isInstantPeriod(b.financialAccountPeriod)) {
return a.financialAccountPeriod.instant
.localeCompare(b.financialAccountPeriod.instant);
}
else if (!isInstantPeriod(a.financialAccountPeriod)
&& !isInstantPeriod(b.financialAccountPeriod)) {
return a.financialAccountPeriod.from
.localeCompare(b.financialAccountPeriod.from);
}
throw new Error('単位情報に不整合があります');
}
export type AccountPeriod = InstantPeriod | DurationPeriod;
export type InstantPeriod = {
instant
};
export type DurationPeriod = {
from,
to
}
export type TimeSeriesAnalysisValue = {
financialAccountPeriod
amount
};
export type TimeSeriesAnalysisViewModel = {
accountName,
unit,
corporation,
consolidatedValues,
nonConsolidatedValues,
}
export type Unit = NormalUnit | DividedUnit
export type BaseUnit = { name }
export type NormalUnit = {
measure
} & BaseUnit
export type DividedUnit = {
unitNumerator,
unitDenominator
} & BaseUnit
export const isNormalUnit = (unit): unit is NormalUnit => {
const maybeNormalUnit = unit as DividedUnit;
return maybeNormalUnit.unitNumerator === null;
}; |
e9d8e243b46b70c80668cced2cddb54ae6f566a2 | 1,458 | ts | TypeScript | therr-public-library/therr-js-utilities/src/db/get-db-query-string.ts | rili-live/therr-app | 7e514a4cc2e072104005036962ebb2528e5d8b4c | [
"MIT"
] | 2 | 2022-01-12T07:29:38.000Z | 2022-03-31T06:03:54.000Z | therr-public-library/therr-js-utilities/src/db/get-db-query-string.ts | rili-live/therr-app | 7e514a4cc2e072104005036962ebb2528e5d8b4c | [
"MIT"
] | null | null | null | therr-public-library/therr-js-utilities/src/db/get-db-query-string.ts | rili-live/therr-app | 7e514a4cc2e072104005036962ebb2528e5d8b4c | [
"MIT"
] | null | null | null | export interface ISearchDbRecords {
queryBuilder: any;
execQuery: Function;
tableName: string;
conditions: {
filterBy?: string;
filterOperator?: string;
query?: string | number | boolean;
pagination: {
itemsPerPage: number;
pageNumber: number;
};
};
defaultConditions: any;
groupBy?: string;
orderBy?: string;
returning?: string | string[];
}
export default ({
queryBuilder,
tableName,
conditions,
defaultConditions,
groupBy,
orderBy,
returning,
}: ISearchDbRecords): string => {
const offset = conditions.pagination.itemsPerPage * (conditions.pagination.pageNumber - 1);
const limit = conditions.pagination.itemsPerPage;
let queryString = queryBuilder
.select(returning || '*')
.from(tableName)
.where(defaultConditions);
if (conditions.filterBy && conditions.query) {
const operator = conditions.filterOperator || '=';
const query = operator === 'ilike' ? `%${conditions.query}%` : conditions.query;
queryString = queryString.andWhere(conditions.filterBy, operator, query);
}
if (groupBy) {
queryString = queryString.groupBy(groupBy);
}
if (orderBy) {
queryString = queryString.orderBy(orderBy);
}
queryString = queryString
.limit(limit)
.offset(offset)
.toString();
return queryString;
};
| 25.578947 | 95 | 0.617284 | 50 | 1 | 0 | 1 | 5 | 8 | 0 | 3 | 13 | 1 | 0 | 22 | 316 | 0.006329 | 0.015823 | 0.025316 | 0.003165 | 0 | 0.2 | 0.866667 | 0.237416 | export interface ISearchDbRecords {
queryBuilder;
execQuery;
tableName;
conditions;
defaultConditions;
groupBy?;
orderBy?;
returning?;
}
export default ({
queryBuilder,
tableName,
conditions,
defaultConditions,
groupBy,
orderBy,
returning,
}) => {
const offset = conditions.pagination.itemsPerPage * (conditions.pagination.pageNumber - 1);
const limit = conditions.pagination.itemsPerPage;
let queryString = queryBuilder
.select(returning || '*')
.from(tableName)
.where(defaultConditions);
if (conditions.filterBy && conditions.query) {
const operator = conditions.filterOperator || '=';
const query = operator === 'ilike' ? `%${conditions.query}%` : conditions.query;
queryString = queryString.andWhere(conditions.filterBy, operator, query);
}
if (groupBy) {
queryString = queryString.groupBy(groupBy);
}
if (orderBy) {
queryString = queryString.orderBy(orderBy);
}
queryString = queryString
.limit(limit)
.offset(offset)
.toString();
return queryString;
};
|
a1154c7aad03c60173143a4314531dfc30724e36 | 1,402 | ts | TypeScript | packages/mjml/src/react/utils/render-utils.ts | carlosbensant/brail | 016d2ad4ca4c422548662af5f208f5e9ca2bd9b3 | [
"MIT"
] | 22 | 2022-03-15T07:22:08.000Z | 2022-03-31T02:34:49.000Z | packages/mjml/src/react/utils/render-utils.ts | carlosbensant/brail | 016d2ad4ca4c422548662af5f208f5e9ca2bd9b3 | [
"MIT"
] | null | null | null | packages/mjml/src/react/utils/render-utils.ts | carlosbensant/brail | 016d2ad4ca4c422548662af5f208f5e9ca2bd9b3 | [
"MIT"
] | 3 | 2022-03-29T13:24:59.000Z | 2022-03-29T21:00:46.000Z | const matchHtmlRegExp = /["'&<>$]/;
export function escapeHtml(string: any) {
const str = '' + string;
const match = matchHtmlRegExp.exec(str);
if (!match) {
return str;
}
let escape;
let html = '';
let index;
let lastIndex = 0;
for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34: // "
escape = '"';
break;
case 36: // $
escape = '$';
break;
case 38: // &
escape = '&';
break;
case 39: // '
escape = '''; // modified from escape-html; used to be '''
break;
case 60: // <
escape = '<';
break;
case 62: // >
escape = '>';
break;
default:
continue;
}
if (lastIndex !== index) {
html += str.substring(lastIndex, index);
}
lastIndex = index + 1;
html += escape;
}
return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
}
export function escapeTextForBrowser(text: any) {
if (typeof text === 'boolean' || typeof text === 'number') {
return '' + text;
}
return escapeHtml(text);
}
export function noop() {}
export function trimContent(child: any) {
if (child.content) {
child.content = child.content.trim();
} else if (child.children) {
child.children.forEach(trimContent);
}
}
| 20.925373 | 77 | 0.536377 | 56 | 4 | 0 | 3 | 7 | 0 | 1 | 3 | 0 | 0 | 2 | 12 | 400 | 0.0175 | 0.0175 | 0 | 0 | 0.005 | 0.214286 | 0 | 0.264279 | const matchHtmlRegExp = /["'&<>$]/;
export /* Example usages of 'escapeHtml' are shown below:
escapeHtml(text);
*/
function escapeHtml(string) {
const str = '' + string;
const match = matchHtmlRegExp.exec(str);
if (!match) {
return str;
}
let escape;
let html = '';
let index;
let lastIndex = 0;
for (index = match.index; index < str.length; index++) {
switch (str.charCodeAt(index)) {
case 34: // "
escape = '"';
break;
case 36: // $
escape = '$';
break;
case 38: // &
escape = '&';
break;
case 39: // '
escape = '''; // modified from escape-html; used to be '''
break;
case 60: // <
escape = '<';
break;
case 62: // >
escape = '>';
break;
default:
continue;
}
if (lastIndex !== index) {
html += str.substring(lastIndex, index);
}
lastIndex = index + 1;
html += escape;
}
return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
}
export function escapeTextForBrowser(text) {
if (typeof text === 'boolean' || typeof text === 'number') {
return '' + text;
}
return escapeHtml(text);
}
export function noop() {}
export /* Example usages of 'trimContent' are shown below:
child.children.forEach(trimContent);
*/
function trimContent(child) {
if (child.content) {
child.content = child.content.trim();
} else if (child.children) {
child.children.forEach(trimContent);
}
}
|
a1216f54bc5b761bb2aa7dcb6a8926a311b0fa74 | 4,696 | ts | TypeScript | src/CppGenerators.ts | dams333/CPP_Class_Generator | 26ea24d0578ce637fb0b1faf43c18d8699b36ef3 | [
"MIT"
] | 2 | 2022-02-12T13:11:09.000Z | 2022-02-12T13:20:03.000Z | src/CppGenerators.ts | dams333/CPP_Class_Generator | 26ea24d0578ce637fb0b1faf43c18d8699b36ef3 | [
"MIT"
] | 1 | 2022-02-12T13:15:39.000Z | 2022-02-12T19:15:59.000Z | src/CppGenerators.ts | dams333/CPP_Class_Generator | 26ea24d0578ce637fb0b1faf43c18d8699b36ef3 | [
"MIT"
] | null | null | null | export function getCppConstructors(message: any)
{
let text = "// Constructors\n";
text += message.className + "::" + message.className + "()\n{\n";
for(let i = 0; i < message.fields.length; i++)
{
text += "\t" + "_" + message.fields[i].field_name + " = " + message.fields[i].default + ";\n";
}
if(message.debug)
{
text += "\tstd::cout << \"\\e[0;33mDefault Constructor called of " + message.className + "\\e[0m\" << std::endl;\n";
}
text += "}\n\n";
text += message.className + "::" + message.className + "(const " + message.className + " ©)\n{\n";
if(message.fields.length === 0)
{
text += "\t(void) copy;\n";
}
for(let i = 0; i < message.fields.length; i++)
{
text += "\t" + "_" + message.fields[i].field_name + " = copy.get" + message.fields[i].field_name[0].toUpperCase() + message.fields[i].field_name.slice(1) + "();\n";
}
if(message.debug)
{
text += "\tstd::cout << \"\\e[0;33mCopy Constructor called of " + message.className + "\\e[0m\" << std::endl;\n";
}
text += "}\n\n";
if(message.fields.length > 0)
{
text += message.className + "::" + message.className + "(";
for(let i = 0; i < message.fields.length; i++)
{
if(i !== 0)
{
text += ", ";
}
text += message.fields[i].field_type + " " + message.fields[i].field_name;
}
text += ")\n{\n";
for(let i = 0; i < message.fields.length; i++)
{
text += "\t" + "_" + message.fields[i].field_name + " = " + message.fields[i].field_name + ";\n";
}
if(message.debug)
{
text += "\tstd::cout << \"\\e[0;33mFields Constructor called of " + message.className + "\\e[0m\" << std::endl;\n";
}
text += "}\n\n";
}
return text;
}
export function getCppDestructors(message: any)
{
let text = "\n// Destructor\n";
text += message.className + "::" + "~" + message.className + "()\n{\n";
if(message.debug)
{
text += "\tstd::cout << \"\\e[0;31mDestructor called of " + message.className + "\\e[0m\" << std::endl;\n";
}
text += "}\n\n";
return text;
}
export function getCppOperators(message: any)
{
let text = "\n// Operators\n";
text += message.className + " & " + message.className + "::operator=(const " + message.className + " &assign)\n{\n";
if(message.fields.length === 0)
{
text += "\t(void) assign;\n";
}
for(let i = 0; i < message.fields.length; i++)
{
text += "\t" + "_" + message.fields[i].field_name + " = assign.get" + message.fields[i].field_name[0].toUpperCase() + message.fields[i].field_name.slice(1) + "();\n";
}
text += "\treturn *this;\n}\n\n";
return text;
}
export function getCppGettersSetters(message: any)
{
let text = "";
if(message.fields.length > 0)
{
text += "\n// Getters / Setters\n";
for(let i = 0; i < message.fields.length; i++)
{
if(message.fields[i].getter)
{
text += message.fields[i].field_type + " " + message.className + "::get" + message.fields[i].field_name[0].toUpperCase() + message.fields[i].field_name.slice(1) + "() const\n{\n";
text += "\treturn _" + message.fields[i].field_name + ";\n}\n";
}
if(message.fields[i].setter)
{
text += "void " + message.className + "::set" + message.fields[i].field_name[0].toUpperCase() + message.fields[i].field_name.slice(1) + "(" + message.fields[i].field_type + " " + message.fields[i].field_name + ")\n{\n";
text += "\t_" + message.fields[i].field_name + " = " + message.fields[i].field_name + ";\n}\n\n";
}
}
}
return text;
}
export function getCppExceptions(message: any)
{
let text = "";
if(message.classExceptions.length > 0)
{
text += "\n\n// Exceptions\n";
for(let i = 0; i < message.classExceptions.length; i++)
{
text += "const char * " + message.className + "::" + message.classExceptions[i].exception_name + "::what() const throw()\n{\n";
text += "\treturn \"" + message.classExceptions[i].exception_what + "\";\n}\n";
}
}
return text;
}
export function getCppStreamOperator(message: any)
{
let text = "";
if(message.format !== "")
{
let format = message.format;
for(let i = 0; i < message.fields.length; i++)
{
let toReplace = "${" + message.fields[i].field_name + "}";
let replacement = "\" << object.get" + message.fields[i].field_name[0].toUpperCase() + message.fields[i].field_name.slice(1) + "()" + " << \"";
format = format.replaceAll(toReplace, replacement);
}
text += "\n\n// Stream operators\n";
text += "std::ostream & operator<<(std::ostream &stream, const " + message.className + " &object)\n{\n";
text += "\tstream << \"" + format + "\" << std::endl;\n";
text += "\treturn stream;\n}\n";
}
return text;
} | 34.028986 | 224 | 0.571337 | 132 | 6 | 0 | 6 | 17 | 0 | 0 | 6 | 0 | 0 | 0 | 19 | 1,710 | 0.007018 | 0.009942 | 0 | 0 | 0 | 0.206897 | 0 | 0.215687 | export function getCppConstructors(message)
{
let text = "// Constructors\n";
text += message.className + "::" + message.className + "()\n{\n";
for(let i = 0; i < message.fields.length; i++)
{
text += "\t" + "_" + message.fields[i].field_name + " = " + message.fields[i].default + ";\n";
}
if(message.debug)
{
text += "\tstd::cout << \"\\e[0;33mDefault Constructor called of " + message.className + "\\e[0m\" << std::endl;\n";
}
text += "}\n\n";
text += message.className + "::" + message.className + "(const " + message.className + " ©)\n{\n";
if(message.fields.length === 0)
{
text += "\t(void) copy;\n";
}
for(let i = 0; i < message.fields.length; i++)
{
text += "\t" + "_" + message.fields[i].field_name + " = copy.get" + message.fields[i].field_name[0].toUpperCase() + message.fields[i].field_name.slice(1) + "();\n";
}
if(message.debug)
{
text += "\tstd::cout << \"\\e[0;33mCopy Constructor called of " + message.className + "\\e[0m\" << std::endl;\n";
}
text += "}\n\n";
if(message.fields.length > 0)
{
text += message.className + "::" + message.className + "(";
for(let i = 0; i < message.fields.length; i++)
{
if(i !== 0)
{
text += ", ";
}
text += message.fields[i].field_type + " " + message.fields[i].field_name;
}
text += ")\n{\n";
for(let i = 0; i < message.fields.length; i++)
{
text += "\t" + "_" + message.fields[i].field_name + " = " + message.fields[i].field_name + ";\n";
}
if(message.debug)
{
text += "\tstd::cout << \"\\e[0;33mFields Constructor called of " + message.className + "\\e[0m\" << std::endl;\n";
}
text += "}\n\n";
}
return text;
}
export function getCppDestructors(message)
{
let text = "\n// Destructor\n";
text += message.className + "::" + "~" + message.className + "()\n{\n";
if(message.debug)
{
text += "\tstd::cout << \"\\e[0;31mDestructor called of " + message.className + "\\e[0m\" << std::endl;\n";
}
text += "}\n\n";
return text;
}
export function getCppOperators(message)
{
let text = "\n// Operators\n";
text += message.className + " & " + message.className + "::operator=(const " + message.className + " &assign)\n{\n";
if(message.fields.length === 0)
{
text += "\t(void) assign;\n";
}
for(let i = 0; i < message.fields.length; i++)
{
text += "\t" + "_" + message.fields[i].field_name + " = assign.get" + message.fields[i].field_name[0].toUpperCase() + message.fields[i].field_name.slice(1) + "();\n";
}
text += "\treturn *this;\n}\n\n";
return text;
}
export function getCppGettersSetters(message)
{
let text = "";
if(message.fields.length > 0)
{
text += "\n// Getters / Setters\n";
for(let i = 0; i < message.fields.length; i++)
{
if(message.fields[i].getter)
{
text += message.fields[i].field_type + " " + message.className + "::get" + message.fields[i].field_name[0].toUpperCase() + message.fields[i].field_name.slice(1) + "() const\n{\n";
text += "\treturn _" + message.fields[i].field_name + ";\n}\n";
}
if(message.fields[i].setter)
{
text += "void " + message.className + "::set" + message.fields[i].field_name[0].toUpperCase() + message.fields[i].field_name.slice(1) + "(" + message.fields[i].field_type + " " + message.fields[i].field_name + ")\n{\n";
text += "\t_" + message.fields[i].field_name + " = " + message.fields[i].field_name + ";\n}\n\n";
}
}
}
return text;
}
export function getCppExceptions(message)
{
let text = "";
if(message.classExceptions.length > 0)
{
text += "\n\n// Exceptions\n";
for(let i = 0; i < message.classExceptions.length; i++)
{
text += "const char * " + message.className + "::" + message.classExceptions[i].exception_name + "::what() const throw()\n{\n";
text += "\treturn \"" + message.classExceptions[i].exception_what + "\";\n}\n";
}
}
return text;
}
export function getCppStreamOperator(message)
{
let text = "";
if(message.format !== "")
{
let format = message.format;
for(let i = 0; i < message.fields.length; i++)
{
let toReplace = "${" + message.fields[i].field_name + "}";
let replacement = "\" << object.get" + message.fields[i].field_name[0].toUpperCase() + message.fields[i].field_name.slice(1) + "()" + " << \"";
format = format.replaceAll(toReplace, replacement);
}
text += "\n\n// Stream operators\n";
text += "std::ostream & operator<<(std::ostream &stream, const " + message.className + " &object)\n{\n";
text += "\tstream << \"" + format + "\" << std::endl;\n";
text += "\treturn stream;\n}\n";
}
return text;
} |
a13214bda5e8edb1adf08c2ce923ac6d5b8c1707 | 1,656 | ts | TypeScript | apps/history_app/src/propUtil.ts | dstanesc/FluidPatterns | 5fe829e36c6bafaceaf54144bb7760bdd1c52a25 | [
"MIT"
] | 1 | 2022-03-17T01:04:36.000Z | 2022-03-17T01:04:36.000Z | apps/schema-evolution/src/propUtil.ts | dstanesc/FluidPatterns | 5fe829e36c6bafaceaf54144bb7760bdd1c52a25 | [
"MIT"
] | null | null | null | apps/schema-evolution/src/propUtil.ts | dstanesc/FluidPatterns | 5fe829e36c6bafaceaf54144bb7760bdd1c52a25 | [
"MIT"
] | null | null | null | /* eslint-disable prefer-template */
/* eslint-disable @typescript-eslint/restrict-plus-operands */
/* eslint-disable @typescript-eslint/no-unsafe-return */
export function serializeToArray(map: Map<string,any>): any[] {
const str: any[] = [];
map.forEach((value, key)=>
{
if(value instanceof Map) {
str.push([key,serializeToArray(value as Map<string,any>)]);
}
else{
str.push([key,value]);
}
},
);
return str;
}
export function deserializeFromArray(arr: any[]): Map<string,any> {
const map: Map<string,any> = new Map();
if(arr.length === 2 && !Array.isArray(arr[0])) {
if(!Array.isArray(arr[1])) {
map.set(arr[0],arr[1]);
}
else if(Array.isArray(arr[1])) {
map.set(arr[0], deserializeFromArray(arr[1]));
}
}
else{
arr.forEach((value,index)=> {
deserializeFromArray(value as any[]).forEach((value2,key)=>{
map.set(key,value2);
},
);
},
);
}
return map;
}
export function serializeNestedMap(map: Map<string,any>): string {
const serializedMap: string = JSON.stringify(serializeToArray(map));
return serializedMap;
}
export function deserializeNestedMap(serializedMap: string): Map<string,any> {
if(serializedMap.length > 0) {
return deserializeFromArray(JSON.parse(serializedMap));
}
else{
return new Map();
}
}
export function cloneMap(map: Map<string,any>): Map<string,any> {
return deserializeNestedMap(serializeNestedMap(map));
}
| 25.875 | 79 | 0.574879 | 50 | 8 | 0 | 11 | 3 | 0 | 4 | 12 | 11 | 0 | 3 | 6.375 | 438 | 0.043379 | 0.006849 | 0 | 0 | 0.006849 | 0.545455 | 0.5 | 0.284608 | /* eslint-disable prefer-template */
/* eslint-disable @typescript-eslint/restrict-plus-operands */
/* eslint-disable @typescript-eslint/no-unsafe-return */
export /* Example usages of 'serializeToArray' are shown below:
serializeToArray(value as Map<string, any>);
JSON.stringify(serializeToArray(map));
*/
function serializeToArray(map) {
const str = [];
map.forEach((value, key)=>
{
if(value instanceof Map) {
str.push([key,serializeToArray(value as Map<string,any>)]);
}
else{
str.push([key,value]);
}
},
);
return str;
}
export /* Example usages of 'deserializeFromArray' are shown below:
map.set(arr[0], deserializeFromArray(arr[1]));
deserializeFromArray(value as any[]).forEach((value2, key) => {
map.set(key, value2);
});
deserializeFromArray(JSON.parse(serializedMap));
*/
function deserializeFromArray(arr) {
const map = new Map();
if(arr.length === 2 && !Array.isArray(arr[0])) {
if(!Array.isArray(arr[1])) {
map.set(arr[0],arr[1]);
}
else if(Array.isArray(arr[1])) {
map.set(arr[0], deserializeFromArray(arr[1]));
}
}
else{
arr.forEach((value,index)=> {
deserializeFromArray(value as any[]).forEach((value2,key)=>{
map.set(key,value2);
},
);
},
);
}
return map;
}
export /* Example usages of 'serializeNestedMap' are shown below:
deserializeNestedMap(serializeNestedMap(map));
*/
function serializeNestedMap(map) {
const serializedMap = JSON.stringify(serializeToArray(map));
return serializedMap;
}
export /* Example usages of 'deserializeNestedMap' are shown below:
deserializeNestedMap(serializeNestedMap(map));
*/
function deserializeNestedMap(serializedMap) {
if(serializedMap.length > 0) {
return deserializeFromArray(JSON.parse(serializedMap));
}
else{
return new Map();
}
}
export function cloneMap(map) {
return deserializeNestedMap(serializeNestedMap(map));
}
|
a14ca499907d3bcee7b77c7c69299953529e5a86 | 2,677 | ts | TypeScript | libs/clsPrefixEnhanced.ts | guibwl/cls-prefix | 91bcd953cd81ac875b62e75c5128a80e1fb7176e | [
"MIT"
] | null | null | null | libs/clsPrefixEnhanced.ts | guibwl/cls-prefix | 91bcd953cd81ac875b62e75c5128a80e1fb7176e | [
"MIT"
] | 1 | 2022-03-26T04:17:58.000Z | 2022-03-26T04:17:58.000Z | libs/clsPrefixEnhanced.ts | guibwl/cls-prefix | 91bcd953cd81ac875b62e75c5128a80e1fb7176e | [
"MIT"
] | null | null | null |
export default class clsPrefixHandler {
clsPrefix: string;
constructor(clsPrefix: string) {
this.clsPrefix = clsPrefix;
}
err = (str: string) => {throw new Error(str)}
objectHandler = (strs: any) => {
const clsList = Object.keys(strs);
if (!clsList.length) {
this.err('Type Object expect at least 1 value');
}
let enhancedCls:string = '';
clsList.forEach((key, i) => {
const judgedCls = strs[key] ? key : '';
if (!judgedCls) return;
const spacing = enhancedCls ? ' ' : '';
if (this.clsPrefix) {
enhancedCls += `${spacing}${this.clsPrefix}-${judgedCls}`
} else {
enhancedCls += `${spacing}${judgedCls}`
}
})
return enhancedCls;
}
arrayHandler = (strs: string[]) => {
// 禁止使用空数组
if (strs.length === 0 || !strs.find(Boolean)) {
this.err('Type Array expect at least 1 `true` value');
}
// 禁止数组的值禁止使用非字符串类型
if (strs.some(el => typeof el !== 'string')) {
this.err('Type Array value only expect string');
}
// 禁止数组的值存在两个及以上的空字符串
if (strs.filter(el => !el).length >= 2) {
this.err('Type Array only can set 1 empty string');
}
if (strs.length === 1) {
return this.clsPrefix ? `${this.clsPrefix}-${strs[0]}` : strs[0];
}
return strs.reduce(
(current: string, next: string, i: number) => {
if (!this.clsPrefix) return `${current} ${next}`;
const index_0: string = i === 0 ? `${this.clsPrefix}-` : '';
if (!current) return `${this.clsPrefix} ${this.clsPrefix}-${next}`;
if (!next) return `${index_0}${current} ${this.clsPrefix}`;
return `${index_0}${current} ${this.clsPrefix}-${next}`;
})
}
stringHandler = (str: string) => {
if (!this.clsPrefix) return str;
return str ? `${this.clsPrefix}-${str}` : this.clsPrefix;
}
// 拼接 class, 这里面只做 args 的数量判断
splice = (...args: any[]) => {
if (args.length > 1) {
return args.reduce((cur?: any, next?: any) =>
`${this.typeJudgeHandler(cur)} ${this.typeJudgeHandler(next)}`)
}
if (args.length === 1) {
return this.typeJudgeHandler(args[0]);
}
if (args.length === 0) {
return this.clsPrefix;
}
};
// 类型判断
typeJudgeHandler = (data: any) => {
if (typeof data === 'string' || !data) {
return this.stringHandler(data ? data : '')
}
if (data instanceof Array) {
return this.arrayHandler(data)
}
if (Object.prototype.toString.call(data) === '[object Object]') {
return this.objectHandler(data)
}
this.err('Type error, expect string|Array|Object|undefined');
}
}
| 23.077586 | 77 | 0.559582 | 75 | 12 | 0 | 16 | 5 | 7 | 0 | 5 | 10 | 1 | 3 | 6.333333 | 792 | 0.035354 | 0.006313 | 0.008838 | 0.001263 | 0.003788 | 0.125 | 0.25 | 0.272552 |
export default class clsPrefixHandler {
clsPrefix;
constructor(clsPrefix) {
this.clsPrefix = clsPrefix;
}
err = (str) => {throw new Error(str)}
objectHandler = (strs) => {
const clsList = Object.keys(strs);
if (!clsList.length) {
this.err('Type Object expect at least 1 value');
}
let enhancedCls = '';
clsList.forEach((key, i) => {
const judgedCls = strs[key] ? key : '';
if (!judgedCls) return;
const spacing = enhancedCls ? ' ' : '';
if (this.clsPrefix) {
enhancedCls += `${spacing}${this.clsPrefix}-${judgedCls}`
} else {
enhancedCls += `${spacing}${judgedCls}`
}
})
return enhancedCls;
}
arrayHandler = (strs) => {
// 禁止使用空数组
if (strs.length === 0 || !strs.find(Boolean)) {
this.err('Type Array expect at least 1 `true` value');
}
// 禁止数组的值禁止使用非字符串类型
if (strs.some(el => typeof el !== 'string')) {
this.err('Type Array value only expect string');
}
// 禁止数组的值存在两个及以上的空字符串
if (strs.filter(el => !el).length >= 2) {
this.err('Type Array only can set 1 empty string');
}
if (strs.length === 1) {
return this.clsPrefix ? `${this.clsPrefix}-${strs[0]}` : strs[0];
}
return strs.reduce(
(current, next, i) => {
if (!this.clsPrefix) return `${current} ${next}`;
const index_0 = i === 0 ? `${this.clsPrefix}-` : '';
if (!current) return `${this.clsPrefix} ${this.clsPrefix}-${next}`;
if (!next) return `${index_0}${current} ${this.clsPrefix}`;
return `${index_0}${current} ${this.clsPrefix}-${next}`;
})
}
stringHandler = (str) => {
if (!this.clsPrefix) return str;
return str ? `${this.clsPrefix}-${str}` : this.clsPrefix;
}
// 拼接 class, 这里面只做 args 的数量判断
splice = (...args) => {
if (args.length > 1) {
return args.reduce((cur?, next?) =>
`${this.typeJudgeHandler(cur)} ${this.typeJudgeHandler(next)}`)
}
if (args.length === 1) {
return this.typeJudgeHandler(args[0]);
}
if (args.length === 0) {
return this.clsPrefix;
}
};
// 类型判断
typeJudgeHandler = (data) => {
if (typeof data === 'string' || !data) {
return this.stringHandler(data ? data : '')
}
if (data instanceof Array) {
return this.arrayHandler(data)
}
if (Object.prototype.toString.call(data) === '[object Object]') {
return this.objectHandler(data)
}
this.err('Type error, expect string|Array|Object|undefined');
}
}
|
a1f6ec861b45c16bbae0491aecd82d1040fc18c1 | 2,963 | ts | TypeScript | packages/pyroscope-flamegraph/src/FlameGraph/FlameGraphComponent/murmur3.ts | BearerPipelineTest/pyroscope | 6fa15c02e36156115d35b96f6a57a39d3e3d04d3 | [
"Apache-2.0"
] | 2 | 2022-01-03T01:01:13.000Z | 2022-01-03T21:30:01.000Z | packages/pyroscope-flamegraph/src/FlameGraph/FlameGraphComponent/murmur3.ts | omarabid/pyroscope | 3bb4014c9b938e6b3dd961cdba2cf16068a8c559 | [
"Apache-2.0"
] | 2 | 2022-02-19T11:02:31.000Z | 2022-02-20T07:13:17.000Z | packages/pyroscope-flamegraph/src/FlameGraph/FlameGraphComponent/murmur3.ts | omarabid/pyroscope | 3bb4014c9b938e6b3dd961cdba2cf16068a8c559 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) 2011 Gary Court
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* eslint-disable no-plusplus */
/* eslint-disable prefer-const */
/* eslint-disable no-bitwise */
/* eslint-disable camelcase */
export default function murmurhash3_32_gc(key: string, seed = 0) {
let remainder;
let bytes;
let h1;
let h1b;
let c1;
let c2;
let k1;
let i;
remainder = key.length & 3; // key.length % 4
bytes = key.length - remainder;
h1 = seed;
c1 = 0xcc9e2d51;
c2 = 0x1b873593;
i = 0;
while (i < bytes) {
k1 =
(key.charCodeAt(i) & 0xff) |
((key.charCodeAt(++i) & 0xff) << 8) |
((key.charCodeAt(++i) & 0xff) << 16) |
((key.charCodeAt(++i) & 0xff) << 24);
++i;
k1 =
((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 =
((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;
h1 ^= k1;
h1 = (h1 << 13) | (h1 >>> 19);
h1b =
((h1 & 0xffff) * 5 + ((((h1 >>> 16) * 5) & 0xffff) << 16)) & 0xffffffff;
h1 = (h1b & 0xffff) + 0x6b64 + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16);
}
k1 = 0;
switch (remainder) {
case 3:
k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
break;
case 2:
k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
break;
default:
k1 ^= key.charCodeAt(i) & 0xff;
k1 =
((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) &
0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 =
((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) &
0xffffffff;
h1 ^= k1;
}
h1 ^= key.length;
h1 ^= h1 >>> 16;
h1 =
((h1 & 0xffff) * 0x85ebca6b +
((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) &
0xffffffff;
h1 ^= h1 >>> 13;
h1 =
((h1 & 0xffff) * 0xc2b2ae35 +
((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16)) &
0xffffffff;
h1 ^= h1 >>> 16;
return h1 >>> 0;
}
| 31.521277 | 460 | 0.581168 | 66 | 1 | 0 | 2 | 8 | 0 | 0 | 0 | 1 | 0 | 0 | 64 | 1,095 | 0.00274 | 0.007306 | 0 | 0 | 0 | 0 | 0.090909 | 0.200446 | /*
Copyright (c) 2011 Gary Court
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* eslint-disable no-plusplus */
/* eslint-disable prefer-const */
/* eslint-disable no-bitwise */
/* eslint-disable camelcase */
export default function murmurhash3_32_gc(key, seed = 0) {
let remainder;
let bytes;
let h1;
let h1b;
let c1;
let c2;
let k1;
let i;
remainder = key.length & 3; // key.length % 4
bytes = key.length - remainder;
h1 = seed;
c1 = 0xcc9e2d51;
c2 = 0x1b873593;
i = 0;
while (i < bytes) {
k1 =
(key.charCodeAt(i) & 0xff) |
((key.charCodeAt(++i) & 0xff) << 8) |
((key.charCodeAt(++i) & 0xff) << 16) |
((key.charCodeAt(++i) & 0xff) << 24);
++i;
k1 =
((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 =
((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;
h1 ^= k1;
h1 = (h1 << 13) | (h1 >>> 19);
h1b =
((h1 & 0xffff) * 5 + ((((h1 >>> 16) * 5) & 0xffff) << 16)) & 0xffffffff;
h1 = (h1b & 0xffff) + 0x6b64 + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16);
}
k1 = 0;
switch (remainder) {
case 3:
k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
break;
case 2:
k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
break;
default:
k1 ^= key.charCodeAt(i) & 0xff;
k1 =
((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) &
0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 =
((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) &
0xffffffff;
h1 ^= k1;
}
h1 ^= key.length;
h1 ^= h1 >>> 16;
h1 =
((h1 & 0xffff) * 0x85ebca6b +
((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) &
0xffffffff;
h1 ^= h1 >>> 13;
h1 =
((h1 & 0xffff) * 0xc2b2ae35 +
((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16)) &
0xffffffff;
h1 ^= h1 >>> 16;
return h1 >>> 0;
}
|
0a0578f02f1f4dbcce027490256f9986580348db | 2,445 | ts | TypeScript | src/kindtocs/global.ts | jesuserro/kindtocs | 9ec3571b72b3c07ca6ec80224b295e731ae3bead | [
"MIT"
] | null | null | null | src/kindtocs/global.ts | jesuserro/kindtocs | 9ec3571b72b3c07ca6ec80224b295e731ae3bead | [
"MIT"
] | 1 | 2022-01-13T10:53:31.000Z | 2022-01-13T10:53:31.000Z | src/kindtocs/global.ts | jesuserro/kindtocs | 9ec3571b72b3c07ca6ec80224b295e731ae3bead | [
"MIT"
] | null | null | null | /**
* "note": ".h4 .patata\nLínea 1.\nLínea número 2.\nLínea número 3.",
* Descartar primera línea de tags con puntos.
* @param note: string
* @returns
*/
export function getNoteText (note: string): string {
const refs = note.match(/(.*?)\n|(.*\s)/);
let text = "";
let lines = [];
if(refs && refs.input){
// console.log("refs", refs);
text = refs.input;
lines = text.split("\n");
const regex = /\.([a-zA-Z0-9ñÑáéíóúÁÉÍÓÚüÜçÇ]+)\s?/gm;
const subst = `[[$1]] `;
let newLine = lines.shift();
newLine = newLine.replace(regex, subst);
lines.unshift(newLine);
text = lines.join("\n ");
return text.trim() + "<span></span> ";
}
return "";
}
/**
* "note": ".h7 [[Gn-01#v1]] [[Gn-02#v4a]]\nAquí se explica la creación del universo.",
* @param note: string
* @returns
*/
export function getRef (note: string): string {
const refs = note.match(/\.h[0-9]{1} (\[\[.*\]\] \[\[.*\]\])/);
if(refs){
return refs[1];
}
return "";
}
export function getTabHeader (header: string): string {
const headers = {
h1: '##',
h2: '###',
h3: '####',
h4: '#####',
h5: '######',
h6: '*',
h7: " *",
h8: " *"
};
return "\n"+headers[header];
}
// Para la Biblia
export function getTabHeaderChapter (header: string): string {
const headers = {
h4: '#',
h5: '##',
h6: '###',
h7: "####",
h8: "#####"
};
return "\n"+headers[header];
}
export function getTabHeaderSimple (header: string): string {
const headers = {
h1: '#',
h2: '##',
h3: '###',
h4: '####',
h5: '#####',
h6: '######',
h7: "*",
h8: " *"
};
return "\n"+headers[header];
}
export function getColorIcon (color: string): string {
const colors = {
pink: "🟥",
orange: "🟧",
blue: "🟦",
default: "🟨"
};
return colors[color] || colors['default'];
}
export function getColorIconSimple (header: string): string {
const colors = {
h7: " ",
h8: " ",
default: ""
};
return colors[header] || colors['default'];
}
export function getIsFavorite (note: string): string {
const isFavorite = note.match(/\.[favoritos|favoritosBiblia]/);
if(isFavorite){
return "❤️";
}
return "";
}
export function getHeader (note: string): string {
const headers = note.match(/\.(h[0-9]{1})/);
if(note && headers && headers.length > 0){
return headers[1];
}
return "";
}
| 21.077586 | 87 | 0.528425 | 91 | 9 | 0 | 9 | 14 | 0 | 0 | 0 | 18 | 0 | 0 | 8.111111 | 850 | 0.021176 | 0.016471 | 0 | 0 | 0 | 0 | 0.5625 | 0.272688 | /**
* "note": ".h4 .patata\nLínea 1.\nLínea número 2.\nLínea número 3.",
* Descartar primera línea de tags con puntos.
* @param note: string
* @returns
*/
export function getNoteText (note) {
const refs = note.match(/(.*?)\n|(.*\s)/);
let text = "";
let lines = [];
if(refs && refs.input){
// console.log("refs", refs);
text = refs.input;
lines = text.split("\n");
const regex = /\.([a-zA-Z0-9ñÑáéíóúÁÉÍÓÚüÜçÇ]+)\s?/gm;
const subst = `[[$1]] `;
let newLine = lines.shift();
newLine = newLine.replace(regex, subst);
lines.unshift(newLine);
text = lines.join("\n ");
return text.trim() + "<span></span> ";
}
return "";
}
/**
* "note": ".h7 [[Gn-01#v1]] [[Gn-02#v4a]]\nAquí se explica la creación del universo.",
* @param note: string
* @returns
*/
export function getRef (note) {
const refs = note.match(/\.h[0-9]{1} (\[\[.*\]\] \[\[.*\]\])/);
if(refs){
return refs[1];
}
return "";
}
export function getTabHeader (header) {
const headers = {
h1: '##',
h2: '###',
h3: '####',
h4: '#####',
h5: '######',
h6: '*',
h7: " *",
h8: " *"
};
return "\n"+headers[header];
}
// Para la Biblia
export function getTabHeaderChapter (header) {
const headers = {
h4: '#',
h5: '##',
h6: '###',
h7: "####",
h8: "#####"
};
return "\n"+headers[header];
}
export function getTabHeaderSimple (header) {
const headers = {
h1: '#',
h2: '##',
h3: '###',
h4: '####',
h5: '#####',
h6: '######',
h7: "*",
h8: " *"
};
return "\n"+headers[header];
}
export function getColorIcon (color) {
const colors = {
pink: "🟥",
orange: "🟧",
blue: "🟦",
default: "🟨"
};
return colors[color] || colors['default'];
}
export function getColorIconSimple (header) {
const colors = {
h7: " ",
h8: " ",
default: ""
};
return colors[header] || colors['default'];
}
export function getIsFavorite (note) {
const isFavorite = note.match(/\.[favoritos|favoritosBiblia]/);
if(isFavorite){
return "❤️";
}
return "";
}
export function getHeader (note) {
const headers = note.match(/\.(h[0-9]{1})/);
if(note && headers && headers.length > 0){
return headers[1];
}
return "";
}
|
0a16fcadcae6b37d4e03cfab51755d1accf91b9b | 1,858 | ts | TypeScript | src/components/myPage/usePagination.ts | sysmetic/globalnewsSearchWeb | ac98f5393599b30006cce674684c4bb100911ef5 | [
"Apache-2.0"
] | null | null | null | src/components/myPage/usePagination.ts | sysmetic/globalnewsSearchWeb | ac98f5393599b30006cce674684c4bb100911ef5 | [
"Apache-2.0"
] | 1 | 2022-03-02T18:21:02.000Z | 2022-03-02T18:21:02.000Z | src/components/myPage/usePagination.ts | sysmetic/globalnewsSearchWeb | ac98f5393599b30006cce674684c4bb100911ef5 | [
"Apache-2.0"
] | 3 | 2022-03-03T04:08:55.000Z | 2022-03-03T05:02:43.000Z | interface UsePaginationProps {
count: number;
page: number;
onPageChange: (page: number) => void;
disabled?: boolean;
siblingCount?: number;
boundaryCount?: number;
}
const usePagination = ({
count,
page,
onPageChange,
disabled,
siblingCount = 1,
boundaryCount = 1
}: UsePaginationProps) => {
const range = (start: number, end: number) => {
const length = end - start + 1;
return Array.from({ length }).map((_, index) => index + start);
};
const startPage = 1;
const endPage = count;
const startPages = range(startPage, Math.min(boundaryCount, count));
const endPages = range(Math.max(count - boundaryCount + 1, boundaryCount + 1), count);
const siblingsStart = Math.max(
Math.min(
page + 1 - siblingCount,
count - boundaryCount - siblingCount * 2 - 1,
),
boundaryCount
);
const siblingsEnd = Math.min(
Math.max(
page + siblingCount,
boundaryCount + siblingCount,
),
endPages.length > 0 ? endPages[0] - 2 : endPage - 1,
);
const itemList = [
...startPages,
'prev',
...range(siblingsStart, siblingsEnd),
...(siblingsEnd < count - boundaryCount - 1 ? ['end-ellipsis'] : count - boundaryCount > boundaryCount ? [count - boundaryCount] : []),
...endPages,
'next',
...endPages
];
const items = itemList.map((item, index) =>
(typeof item === 'number' ? {
key: index,
onClick: () => onPageChange(item - 1),
disabled,
selected: item - 1 === page,
item,
} :
{
key: index,
onClick: () => onPageChange(item === 'next' ? page + 1 : page - 1),
disabled: disabled || item.indexOf('ellipsis') > -1 || (item === 'next' ? page >= count - 1 : page - 1 < 0),
selected: false,
item,
}
));
return {
items,
}
}
export default usePagination;
| 23.225 | 139 | 0.585038 | 68 | 6 | 0 | 7 | 11 | 6 | 1 | 0 | 9 | 1 | 1 | 11.666667 | 527 | 0.024668 | 0.020873 | 0.011385 | 0.001898 | 0.001898 | 0 | 0.3 | 0.298634 | interface UsePaginationProps {
count;
page;
onPageChange;
disabled?;
siblingCount?;
boundaryCount?;
}
/* Example usages of 'usePagination' are shown below:
;
*/
const usePagination = ({
count,
page,
onPageChange,
disabled,
siblingCount = 1,
boundaryCount = 1
}) => {
/* Example usages of 'range' are shown below:
range(startPage, Math.min(boundaryCount, count));
range(Math.max(count - boundaryCount + 1, boundaryCount + 1), count);
range(siblingsStart, siblingsEnd);
*/
const range = (start, end) => {
const length = end - start + 1;
return Array.from({ length }).map((_, index) => index + start);
};
const startPage = 1;
const endPage = count;
const startPages = range(startPage, Math.min(boundaryCount, count));
const endPages = range(Math.max(count - boundaryCount + 1, boundaryCount + 1), count);
const siblingsStart = Math.max(
Math.min(
page + 1 - siblingCount,
count - boundaryCount - siblingCount * 2 - 1,
),
boundaryCount
);
const siblingsEnd = Math.min(
Math.max(
page + siblingCount,
boundaryCount + siblingCount,
),
endPages.length > 0 ? endPages[0] - 2 : endPage - 1,
);
const itemList = [
...startPages,
'prev',
...range(siblingsStart, siblingsEnd),
...(siblingsEnd < count - boundaryCount - 1 ? ['end-ellipsis'] : count - boundaryCount > boundaryCount ? [count - boundaryCount] : []),
...endPages,
'next',
...endPages
];
const items = itemList.map((item, index) =>
(typeof item === 'number' ? {
key: index,
onClick: () => onPageChange(item - 1),
disabled,
selected: item - 1 === page,
item,
} :
{
key: index,
onClick: () => onPageChange(item === 'next' ? page + 1 : page - 1),
disabled: disabled || item.indexOf('ellipsis') > -1 || (item === 'next' ? page >= count - 1 : page - 1 < 0),
selected: false,
item,
}
));
return {
items,
}
}
export default usePagination;
|
0a28ed6a0c81d3c60cca92c33eb09539db5b919e | 13,927 | ts | TypeScript | packages/crypto/src/macs/poly1305.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/macs/poly1305.ts | eike-hass/iota.js | 18ddf1ab7ffdd2ef59c6b345fe9ec70a4629bb48 | [
"Apache-2.0"
] | null | null | null | packages/crypto/src/macs/poly1305.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 */
// https://www.ietf.org/rfc/rfc8439.html
/**
* Implementation of Poly1305.
*/
export class Poly1305 {
/**
* The buffer for storing the ongoing calculation.
* @internal
*/
private _buffer: Uint8Array;
/**
* The r buffer for storing the ongoing calculation.
* @internal
*/
private readonly _r: Uint16Array;
/**
* The h buffer for storing the ongoing calculation.
* @internal
*/
private _h: Uint16Array;
/**
* The pad buffer for storing the ongoing calculation.
* @internal
*/
private readonly _pad: Uint16Array;
/**
* The leftover count.
* @internal
*/
private _leftover: number;
/**
* The final value.
* @internal
*/
private _fin: number;
/**
* The mac generated from finish.
* @internal
*/
private _finishedMac: Uint8Array;
/**
* Create a new instance of Poly1305.
* @param key The key.
*/
constructor(key: Uint8Array) {
this._buffer = new Uint8Array(16);
this._r = new Uint16Array(10);
this._h = new Uint16Array(10);
this._pad = new Uint16Array(8);
this._leftover = 0;
this._fin = 0;
this._finishedMac = new Uint8Array(1);
const t0 = key[0] | (key[1] << 8);
this._r[0] = t0 & 0x1fff;
const t1 = key[2] | (key[3] << 8);
this._r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
const t2 = key[4] | (key[5] << 8);
this._r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
const t3 = key[6] | (key[7] << 8);
this._r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
const t4 = key[8] | (key[9] << 8);
this._r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
this._r[5] = (t4 >>> 1) & 0x1ffe;
const t5 = key[10] | (key[11] << 8);
this._r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
const t6 = key[12] | (key[13] << 8);
this._r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
const t7 = key[14] | (key[15] << 8);
this._r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
this._r[9] = (t7 >>> 5) & 0x007f;
this._pad[0] = key[16] | (key[17] << 8);
this._pad[1] = key[18] | (key[19] << 8);
this._pad[2] = key[20] | (key[21] << 8);
this._pad[3] = key[22] | (key[23] << 8);
this._pad[4] = key[24] | (key[25] << 8);
this._pad[5] = key[26] | (key[27] << 8);
this._pad[6] = key[28] | (key[29] << 8);
this._pad[7] = key[30] | (key[31] << 8);
}
/**
* Finished the mac.
*/
public finish(): void {
const g = new Uint16Array(10);
let c: number;
let mask: number;
let f: number;
let i: number;
if (this._leftover) {
i = this._leftover;
this._buffer[i++] = 1;
for (; i < 16; i++) {
this._buffer[i] = 0;
}
this._fin = 1;
this.blocks(this._buffer, 0, 16);
}
c = this._h[1] >>> 13;
this._h[1] &= 0x1fff;
for (i = 2; i < 10; i++) {
this._h[i] += c;
c = this._h[i] >>> 13;
this._h[i] &= 0x1fff;
}
this._h[0] += c * 5;
c = this._h[0] >>> 13;
this._h[0] &= 0x1fff;
this._h[1] += c;
c = this._h[1] >>> 13;
this._h[1] &= 0x1fff;
this._h[2] += c;
g[0] = this._h[0] + 5;
c = g[0] >>> 13;
g[0] &= 0x1fff;
for (i = 1; i < 10; i++) {
g[i] = this._h[i] + c;
c = g[i] >>> 13;
g[i] &= 0x1fff;
}
g[9] -= 1 << 13;
mask = (c ^ 1) - 1;
for (i = 0; i < 10; i++) {
g[i] &= mask;
}
mask = ~mask;
for (i = 0; i < 10; i++) {
this._h[i] = (this._h[i] & mask) | g[i];
}
this._h[0] = (this._h[0] | (this._h[1] << 13)) & 0xffff;
this._h[1] = ((this._h[1] >>> 3) | (this._h[2] << 10)) & 0xffff;
this._h[2] = ((this._h[2] >>> 6) | (this._h[3] << 7)) & 0xffff;
this._h[3] = ((this._h[3] >>> 9) | (this._h[4] << 4)) & 0xffff;
this._h[4] = ((this._h[4] >>> 12) | (this._h[5] << 1) | (this._h[6] << 14)) & 0xffff;
this._h[5] = ((this._h[6] >>> 2) | (this._h[7] << 11)) & 0xffff;
this._h[6] = ((this._h[7] >>> 5) | (this._h[8] << 8)) & 0xffff;
this._h[7] = ((this._h[8] >>> 8) | (this._h[9] << 5)) & 0xffff;
f = this._h[0] + this._pad[0];
this._h[0] = f & 0xffff;
for (i = 1; i < 8; i++) {
f = Math.trunc(Math.trunc(this._h[i] + this._pad[i]) + (f >>> 16));
this._h[i] = f & 0xffff;
}
this._finishedMac = new Uint8Array(16);
this._finishedMac[0] = this._h[0] >>> 0;
this._finishedMac[1] = this._h[0] >>> 8;
this._finishedMac[2] = this._h[1] >>> 0;
this._finishedMac[3] = this._h[1] >>> 8;
this._finishedMac[4] = this._h[2] >>> 0;
this._finishedMac[5] = this._h[2] >>> 8;
this._finishedMac[6] = this._h[3] >>> 0;
this._finishedMac[7] = this._h[3] >>> 8;
this._finishedMac[8] = this._h[4] >>> 0;
this._finishedMac[9] = this._h[4] >>> 8;
this._finishedMac[10] = this._h[5] >>> 0;
this._finishedMac[11] = this._h[5] >>> 8;
this._finishedMac[12] = this._h[6] >>> 0;
this._finishedMac[13] = this._h[6] >>> 8;
this._finishedMac[14] = this._h[7] >>> 0;
this._finishedMac[15] = this._h[7] >>> 8;
}
/**
* Update the hash.
* @param input The data to update with.
* @returns Hasher instance.
*/
public update(input: Uint8Array): Poly1305 {
let mpos = 0;
let bytes = input.length;
let want: number;
if (this._leftover) {
want = 16 - this._leftover;
if (want > bytes) {
want = bytes;
}
for (let i = 0; i < want; i++) {
this._buffer[this._leftover + i] = input[mpos + i];
}
bytes -= want;
mpos += want;
this._leftover += want;
if (this._leftover < 16) {
return this;
}
this.blocks(this._buffer, 0, 16);
this._leftover = 0;
}
if (bytes >= 16) {
want = bytes - (bytes % 16);
this.blocks(input, mpos, want);
mpos += want;
bytes -= want;
}
if (bytes) {
for (let i = 0; i < bytes; i++) {
this._buffer[this._leftover + i] = input[mpos + i];
}
this._leftover += bytes;
}
return this;
}
/**
* Get the digest for the hash.
* @returns The mac.
*/
public digest(): Uint8Array {
if (!this._finishedMac) {
this.finish();
}
return this._finishedMac;
}
/**
* Perform the block operations.
* @param m The data,
* @param mpos The index in the data,
* @param bytes The number of bytes.
* @internal
*/
private blocks(m: Uint8Array, mpos: number, bytes: number) {
const hibit = this._fin ? 0 : 1 << 11;
let h0 = this._h[0];
let h1 = this._h[1];
let h2 = this._h[2];
let h3 = this._h[3];
let h4 = this._h[4];
let h5 = this._h[5];
let h6 = this._h[6];
let h7 = this._h[7];
let h8 = this._h[8];
let h9 = this._h[9];
const r0 = this._r[0];
const r1 = this._r[1];
const r2 = this._r[2];
const r3 = this._r[3];
const r4 = this._r[4];
const r5 = this._r[5];
const r6 = this._r[6];
const r7 = this._r[7];
const r8 = this._r[8];
const r9 = this._r[9];
while (bytes >= 16) {
const t0 = m[mpos + 0] | (m[mpos + 1] << 8);
h0 += t0 & 0x1fff;
const t1 = m[mpos + 2] | (m[mpos + 3] << 8);
h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
const t2 = m[mpos + 4] | (m[mpos + 5] << 8);
h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;
const t3 = m[mpos + 6] | (m[mpos + 7] << 8);
h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
const t4 = m[mpos + 8] | (m[mpos + 9] << 8);
h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;
h5 += (t4 >>> 1) & 0x1fff;
const t5 = m[mpos + 10] | (m[mpos + 11] << 8);
h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
const t6 = m[mpos + 12] | (m[mpos + 13] << 8);
h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;
const t7 = m[mpos + 14] | (m[mpos + 15] << 8);
h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
h9 += (t7 >>> 5) | hibit;
let c = 0;
let d0 = c;
d0 += h0 * r0;
d0 += h1 * (5 * r9);
d0 += h2 * (5 * r8);
d0 += h3 * (5 * r7);
d0 += h4 * (5 * r6);
c = d0 >>> 13;
d0 &= 0x1fff;
d0 += h5 * (5 * r5);
d0 += h6 * (5 * r4);
d0 += h7 * (5 * r3);
d0 += h8 * (5 * r2);
d0 += h9 * (5 * r1);
c += d0 >>> 13;
d0 &= 0x1fff;
let d1 = c;
d1 += h0 * r1;
d1 += h1 * r0;
d1 += h2 * (5 * r9);
d1 += h3 * (5 * r8);
d1 += h4 * (5 * r7);
c = d1 >>> 13;
d1 &= 0x1fff;
d1 += h5 * (5 * r6);
d1 += h6 * (5 * r5);
d1 += h7 * (5 * r4);
d1 += h8 * (5 * r3);
d1 += h9 * (5 * r2);
c += d1 >>> 13;
d1 &= 0x1fff;
let d2 = c;
d2 += h0 * r2;
d2 += h1 * r1;
d2 += h2 * r0;
d2 += h3 * (5 * r9);
d2 += h4 * (5 * r8);
c = d2 >>> 13;
d2 &= 0x1fff;
d2 += h5 * (5 * r7);
d2 += h6 * (5 * r6);
d2 += h7 * (5 * r5);
d2 += h8 * (5 * r4);
d2 += h9 * (5 * r3);
c += d2 >>> 13;
d2 &= 0x1fff;
let d3 = c;
d3 += h0 * r3;
d3 += h1 * r2;
d3 += h2 * r1;
d3 += h3 * r0;
d3 += h4 * (5 * r9);
c = d3 >>> 13;
d3 &= 0x1fff;
d3 += h5 * (5 * r8);
d3 += h6 * (5 * r7);
d3 += h7 * (5 * r6);
d3 += h8 * (5 * r5);
d3 += h9 * (5 * r4);
c += d3 >>> 13;
d3 &= 0x1fff;
let d4 = c;
d4 += h0 * r4;
d4 += h1 * r3;
d4 += h2 * r2;
d4 += h3 * r1;
d4 += h4 * r0;
c = d4 >>> 13;
d4 &= 0x1fff;
d4 += h5 * (5 * r9);
d4 += h6 * (5 * r8);
d4 += h7 * (5 * r7);
d4 += h8 * (5 * r6);
d4 += h9 * (5 * r5);
c += d4 >>> 13;
d4 &= 0x1fff;
let d5 = c;
d5 += h0 * r5;
d5 += h1 * r4;
d5 += h2 * r3;
d5 += h3 * r2;
d5 += h4 * r1;
c = d5 >>> 13;
d5 &= 0x1fff;
d5 += h5 * r0;
d5 += h6 * (5 * r9);
d5 += h7 * (5 * r8);
d5 += h8 * (5 * r7);
d5 += h9 * (5 * r6);
c += d5 >>> 13;
d5 &= 0x1fff;
let d6 = c;
d6 += h0 * r6;
d6 += h1 * r5;
d6 += h2 * r4;
d6 += h3 * r3;
d6 += h4 * r2;
c = d6 >>> 13;
d6 &= 0x1fff;
d6 += h5 * r1;
d6 += h6 * r0;
d6 += h7 * (5 * r9);
d6 += h8 * (5 * r8);
d6 += h9 * (5 * r7);
c += d6 >>> 13;
d6 &= 0x1fff;
let d7 = c;
d7 += h0 * r7;
d7 += h1 * r6;
d7 += h2 * r5;
d7 += h3 * r4;
d7 += h4 * r3;
c = d7 >>> 13;
d7 &= 0x1fff;
d7 += h5 * r2;
d7 += h6 * r1;
d7 += h7 * r0;
d7 += h8 * (5 * r9);
d7 += h9 * (5 * r8);
c += d7 >>> 13;
d7 &= 0x1fff;
let d8 = c;
d8 += h0 * r8;
d8 += h1 * r7;
d8 += h2 * r6;
d8 += h3 * r5;
d8 += h4 * r4;
c = d8 >>> 13;
d8 &= 0x1fff;
d8 += h5 * r3;
d8 += h6 * r2;
d8 += h7 * r1;
d8 += h8 * r0;
d8 += h9 * (5 * r9);
c += d8 >>> 13;
d8 &= 0x1fff;
let d9 = c;
d9 += h0 * r9;
d9 += h1 * r8;
d9 += h2 * r7;
d9 += h3 * r6;
d9 += h4 * r5;
c = d9 >>> 13;
d9 &= 0x1fff;
d9 += h5 * r4;
d9 += h6 * r3;
d9 += h7 * r2;
d9 += h8 * r1;
d9 += h9 * r0;
c += d9 >>> 13;
d9 &= 0x1fff;
c = Math.trunc((c << 2) + c);
c = Math.trunc(c + d0);
d0 = c & 0x1fff;
c >>>= 13;
d1 += c;
h0 = d0;
h1 = d1;
h2 = d2;
h3 = d3;
h4 = d4;
h5 = d5;
h6 = d6;
h7 = d7;
h8 = d8;
h9 = d9;
mpos += 16;
bytes -= 16;
}
this._h[0] = h0;
this._h[1] = h1;
this._h[2] = h2;
this._h[3] = h3;
this._h[4] = h4;
this._h[5] = h5;
this._h[6] = h6;
this._h[7] = h7;
this._h[8] = h8;
this._h[9] = h9;
}
}
| 28.715464 | 93 | 0.358081 | 384 | 5 | 0 | 5 | 58 | 7 | 2 | 0 | 10 | 1 | 0 | 73 | 5,265 | 0.001899 | 0.011016 | 0.00133 | 0.00019 | 0 | 0 | 0.133333 | 0.21141 | // Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
/* eslint-disable no-bitwise */
// https://www.ietf.org/rfc/rfc8439.html
/**
* Implementation of Poly1305.
*/
export class Poly1305 {
/**
* The buffer for storing the ongoing calculation.
* @internal
*/
private _buffer;
/**
* The r buffer for storing the ongoing calculation.
* @internal
*/
private readonly _r;
/**
* The h buffer for storing the ongoing calculation.
* @internal
*/
private _h;
/**
* The pad buffer for storing the ongoing calculation.
* @internal
*/
private readonly _pad;
/**
* The leftover count.
* @internal
*/
private _leftover;
/**
* The final value.
* @internal
*/
private _fin;
/**
* The mac generated from finish.
* @internal
*/
private _finishedMac;
/**
* Create a new instance of Poly1305.
* @param key The key.
*/
constructor(key) {
this._buffer = new Uint8Array(16);
this._r = new Uint16Array(10);
this._h = new Uint16Array(10);
this._pad = new Uint16Array(8);
this._leftover = 0;
this._fin = 0;
this._finishedMac = new Uint8Array(1);
const t0 = key[0] | (key[1] << 8);
this._r[0] = t0 & 0x1fff;
const t1 = key[2] | (key[3] << 8);
this._r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
const t2 = key[4] | (key[5] << 8);
this._r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
const t3 = key[6] | (key[7] << 8);
this._r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
const t4 = key[8] | (key[9] << 8);
this._r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
this._r[5] = (t4 >>> 1) & 0x1ffe;
const t5 = key[10] | (key[11] << 8);
this._r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
const t6 = key[12] | (key[13] << 8);
this._r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
const t7 = key[14] | (key[15] << 8);
this._r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
this._r[9] = (t7 >>> 5) & 0x007f;
this._pad[0] = key[16] | (key[17] << 8);
this._pad[1] = key[18] | (key[19] << 8);
this._pad[2] = key[20] | (key[21] << 8);
this._pad[3] = key[22] | (key[23] << 8);
this._pad[4] = key[24] | (key[25] << 8);
this._pad[5] = key[26] | (key[27] << 8);
this._pad[6] = key[28] | (key[29] << 8);
this._pad[7] = key[30] | (key[31] << 8);
}
/**
* Finished the mac.
*/
public finish() {
const g = new Uint16Array(10);
let c;
let mask;
let f;
let i;
if (this._leftover) {
i = this._leftover;
this._buffer[i++] = 1;
for (; i < 16; i++) {
this._buffer[i] = 0;
}
this._fin = 1;
this.blocks(this._buffer, 0, 16);
}
c = this._h[1] >>> 13;
this._h[1] &= 0x1fff;
for (i = 2; i < 10; i++) {
this._h[i] += c;
c = this._h[i] >>> 13;
this._h[i] &= 0x1fff;
}
this._h[0] += c * 5;
c = this._h[0] >>> 13;
this._h[0] &= 0x1fff;
this._h[1] += c;
c = this._h[1] >>> 13;
this._h[1] &= 0x1fff;
this._h[2] += c;
g[0] = this._h[0] + 5;
c = g[0] >>> 13;
g[0] &= 0x1fff;
for (i = 1; i < 10; i++) {
g[i] = this._h[i] + c;
c = g[i] >>> 13;
g[i] &= 0x1fff;
}
g[9] -= 1 << 13;
mask = (c ^ 1) - 1;
for (i = 0; i < 10; i++) {
g[i] &= mask;
}
mask = ~mask;
for (i = 0; i < 10; i++) {
this._h[i] = (this._h[i] & mask) | g[i];
}
this._h[0] = (this._h[0] | (this._h[1] << 13)) & 0xffff;
this._h[1] = ((this._h[1] >>> 3) | (this._h[2] << 10)) & 0xffff;
this._h[2] = ((this._h[2] >>> 6) | (this._h[3] << 7)) & 0xffff;
this._h[3] = ((this._h[3] >>> 9) | (this._h[4] << 4)) & 0xffff;
this._h[4] = ((this._h[4] >>> 12) | (this._h[5] << 1) | (this._h[6] << 14)) & 0xffff;
this._h[5] = ((this._h[6] >>> 2) | (this._h[7] << 11)) & 0xffff;
this._h[6] = ((this._h[7] >>> 5) | (this._h[8] << 8)) & 0xffff;
this._h[7] = ((this._h[8] >>> 8) | (this._h[9] << 5)) & 0xffff;
f = this._h[0] + this._pad[0];
this._h[0] = f & 0xffff;
for (i = 1; i < 8; i++) {
f = Math.trunc(Math.trunc(this._h[i] + this._pad[i]) + (f >>> 16));
this._h[i] = f & 0xffff;
}
this._finishedMac = new Uint8Array(16);
this._finishedMac[0] = this._h[0] >>> 0;
this._finishedMac[1] = this._h[0] >>> 8;
this._finishedMac[2] = this._h[1] >>> 0;
this._finishedMac[3] = this._h[1] >>> 8;
this._finishedMac[4] = this._h[2] >>> 0;
this._finishedMac[5] = this._h[2] >>> 8;
this._finishedMac[6] = this._h[3] >>> 0;
this._finishedMac[7] = this._h[3] >>> 8;
this._finishedMac[8] = this._h[4] >>> 0;
this._finishedMac[9] = this._h[4] >>> 8;
this._finishedMac[10] = this._h[5] >>> 0;
this._finishedMac[11] = this._h[5] >>> 8;
this._finishedMac[12] = this._h[6] >>> 0;
this._finishedMac[13] = this._h[6] >>> 8;
this._finishedMac[14] = this._h[7] >>> 0;
this._finishedMac[15] = this._h[7] >>> 8;
}
/**
* Update the hash.
* @param input The data to update with.
* @returns Hasher instance.
*/
public update(input) {
let mpos = 0;
let bytes = input.length;
let want;
if (this._leftover) {
want = 16 - this._leftover;
if (want > bytes) {
want = bytes;
}
for (let i = 0; i < want; i++) {
this._buffer[this._leftover + i] = input[mpos + i];
}
bytes -= want;
mpos += want;
this._leftover += want;
if (this._leftover < 16) {
return this;
}
this.blocks(this._buffer, 0, 16);
this._leftover = 0;
}
if (bytes >= 16) {
want = bytes - (bytes % 16);
this.blocks(input, mpos, want);
mpos += want;
bytes -= want;
}
if (bytes) {
for (let i = 0; i < bytes; i++) {
this._buffer[this._leftover + i] = input[mpos + i];
}
this._leftover += bytes;
}
return this;
}
/**
* Get the digest for the hash.
* @returns The mac.
*/
public digest() {
if (!this._finishedMac) {
this.finish();
}
return this._finishedMac;
}
/**
* Perform the block operations.
* @param m The data,
* @param mpos The index in the data,
* @param bytes The number of bytes.
* @internal
*/
private blocks(m, mpos, bytes) {
const hibit = this._fin ? 0 : 1 << 11;
let h0 = this._h[0];
let h1 = this._h[1];
let h2 = this._h[2];
let h3 = this._h[3];
let h4 = this._h[4];
let h5 = this._h[5];
let h6 = this._h[6];
let h7 = this._h[7];
let h8 = this._h[8];
let h9 = this._h[9];
const r0 = this._r[0];
const r1 = this._r[1];
const r2 = this._r[2];
const r3 = this._r[3];
const r4 = this._r[4];
const r5 = this._r[5];
const r6 = this._r[6];
const r7 = this._r[7];
const r8 = this._r[8];
const r9 = this._r[9];
while (bytes >= 16) {
const t0 = m[mpos + 0] | (m[mpos + 1] << 8);
h0 += t0 & 0x1fff;
const t1 = m[mpos + 2] | (m[mpos + 3] << 8);
h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
const t2 = m[mpos + 4] | (m[mpos + 5] << 8);
h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;
const t3 = m[mpos + 6] | (m[mpos + 7] << 8);
h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
const t4 = m[mpos + 8] | (m[mpos + 9] << 8);
h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;
h5 += (t4 >>> 1) & 0x1fff;
const t5 = m[mpos + 10] | (m[mpos + 11] << 8);
h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
const t6 = m[mpos + 12] | (m[mpos + 13] << 8);
h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;
const t7 = m[mpos + 14] | (m[mpos + 15] << 8);
h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
h9 += (t7 >>> 5) | hibit;
let c = 0;
let d0 = c;
d0 += h0 * r0;
d0 += h1 * (5 * r9);
d0 += h2 * (5 * r8);
d0 += h3 * (5 * r7);
d0 += h4 * (5 * r6);
c = d0 >>> 13;
d0 &= 0x1fff;
d0 += h5 * (5 * r5);
d0 += h6 * (5 * r4);
d0 += h7 * (5 * r3);
d0 += h8 * (5 * r2);
d0 += h9 * (5 * r1);
c += d0 >>> 13;
d0 &= 0x1fff;
let d1 = c;
d1 += h0 * r1;
d1 += h1 * r0;
d1 += h2 * (5 * r9);
d1 += h3 * (5 * r8);
d1 += h4 * (5 * r7);
c = d1 >>> 13;
d1 &= 0x1fff;
d1 += h5 * (5 * r6);
d1 += h6 * (5 * r5);
d1 += h7 * (5 * r4);
d1 += h8 * (5 * r3);
d1 += h9 * (5 * r2);
c += d1 >>> 13;
d1 &= 0x1fff;
let d2 = c;
d2 += h0 * r2;
d2 += h1 * r1;
d2 += h2 * r0;
d2 += h3 * (5 * r9);
d2 += h4 * (5 * r8);
c = d2 >>> 13;
d2 &= 0x1fff;
d2 += h5 * (5 * r7);
d2 += h6 * (5 * r6);
d2 += h7 * (5 * r5);
d2 += h8 * (5 * r4);
d2 += h9 * (5 * r3);
c += d2 >>> 13;
d2 &= 0x1fff;
let d3 = c;
d3 += h0 * r3;
d3 += h1 * r2;
d3 += h2 * r1;
d3 += h3 * r0;
d3 += h4 * (5 * r9);
c = d3 >>> 13;
d3 &= 0x1fff;
d3 += h5 * (5 * r8);
d3 += h6 * (5 * r7);
d3 += h7 * (5 * r6);
d3 += h8 * (5 * r5);
d3 += h9 * (5 * r4);
c += d3 >>> 13;
d3 &= 0x1fff;
let d4 = c;
d4 += h0 * r4;
d4 += h1 * r3;
d4 += h2 * r2;
d4 += h3 * r1;
d4 += h4 * r0;
c = d4 >>> 13;
d4 &= 0x1fff;
d4 += h5 * (5 * r9);
d4 += h6 * (5 * r8);
d4 += h7 * (5 * r7);
d4 += h8 * (5 * r6);
d4 += h9 * (5 * r5);
c += d4 >>> 13;
d4 &= 0x1fff;
let d5 = c;
d5 += h0 * r5;
d5 += h1 * r4;
d5 += h2 * r3;
d5 += h3 * r2;
d5 += h4 * r1;
c = d5 >>> 13;
d5 &= 0x1fff;
d5 += h5 * r0;
d5 += h6 * (5 * r9);
d5 += h7 * (5 * r8);
d5 += h8 * (5 * r7);
d5 += h9 * (5 * r6);
c += d5 >>> 13;
d5 &= 0x1fff;
let d6 = c;
d6 += h0 * r6;
d6 += h1 * r5;
d6 += h2 * r4;
d6 += h3 * r3;
d6 += h4 * r2;
c = d6 >>> 13;
d6 &= 0x1fff;
d6 += h5 * r1;
d6 += h6 * r0;
d6 += h7 * (5 * r9);
d6 += h8 * (5 * r8);
d6 += h9 * (5 * r7);
c += d6 >>> 13;
d6 &= 0x1fff;
let d7 = c;
d7 += h0 * r7;
d7 += h1 * r6;
d7 += h2 * r5;
d7 += h3 * r4;
d7 += h4 * r3;
c = d7 >>> 13;
d7 &= 0x1fff;
d7 += h5 * r2;
d7 += h6 * r1;
d7 += h7 * r0;
d7 += h8 * (5 * r9);
d7 += h9 * (5 * r8);
c += d7 >>> 13;
d7 &= 0x1fff;
let d8 = c;
d8 += h0 * r8;
d8 += h1 * r7;
d8 += h2 * r6;
d8 += h3 * r5;
d8 += h4 * r4;
c = d8 >>> 13;
d8 &= 0x1fff;
d8 += h5 * r3;
d8 += h6 * r2;
d8 += h7 * r1;
d8 += h8 * r0;
d8 += h9 * (5 * r9);
c += d8 >>> 13;
d8 &= 0x1fff;
let d9 = c;
d9 += h0 * r9;
d9 += h1 * r8;
d9 += h2 * r7;
d9 += h3 * r6;
d9 += h4 * r5;
c = d9 >>> 13;
d9 &= 0x1fff;
d9 += h5 * r4;
d9 += h6 * r3;
d9 += h7 * r2;
d9 += h8 * r1;
d9 += h9 * r0;
c += d9 >>> 13;
d9 &= 0x1fff;
c = Math.trunc((c << 2) + c);
c = Math.trunc(c + d0);
d0 = c & 0x1fff;
c >>>= 13;
d1 += c;
h0 = d0;
h1 = d1;
h2 = d2;
h3 = d3;
h4 = d4;
h5 = d5;
h6 = d6;
h7 = d7;
h8 = d8;
h9 = d9;
mpos += 16;
bytes -= 16;
}
this._h[0] = h0;
this._h[1] = h1;
this._h[2] = h2;
this._h[3] = h3;
this._h[4] = h4;
this._h[5] = h5;
this._h[6] = h6;
this._h[7] = h7;
this._h[8] = h8;
this._h[9] = h9;
}
}
|
0a839d8cc97ab10756fcc443e8ca34cbe2a96f10 | 3,035 | ts | TypeScript | packages/pyroscope-flamegraph/src/fitMode/fitMode.ts | BearerPipelineTest/pyroscope | 6fa15c02e36156115d35b96f6a57a39d3e3d04d3 | [
"Apache-2.0"
] | 2 | 2022-01-03T01:01:13.000Z | 2022-01-03T21:30:01.000Z | packages/pyroscope-flamegraph/src/fitMode/fitMode.ts | omarabid/pyroscope | 3bb4014c9b938e6b3dd961cdba2cf16068a8c559 | [
"Apache-2.0"
] | 2 | 2022-02-19T11:02:31.000Z | 2022-02-20T07:13:17.000Z | packages/pyroscope-flamegraph/src/fitMode/fitMode.ts | omarabid/pyroscope | 3bb4014c9b938e6b3dd961cdba2cf16068a8c559 | [
"Apache-2.0"
] | null | null | null | export const TailMode = 'TAIL';
export const HeadMode = 'HEAD';
export type FitModes = typeof TailMode | typeof HeadMode;
const margin = 3;
/**
* Returns a text and margin left used to write text into a canvas rectangle
*
* @param {FitModes} mode -
* @param {number} charSize - Size in pixels of an individual character. Assumes it's a monospace font.
* @param {number} rectWidth - Width in pixels of the rectangle
* @param {string} fullText - The text that will be first tried.
* @param {string} shortText - The text that willbe used when fullText can't fit. It's normally a substring of the original text.
*/
interface fitToCanvasRectProps {
mode: FitModes;
/** charSize - Size in pixels of an individual character. Assumes it's a monospace font. */
charSize: number;
/** Width in pixels of the rectangle */
rectWidth: number;
/** The text that will be first tried to fit */
fullText: string;
/** The text that willbe used when fullText can't fit. It's normally a substring of the original text. */
shortText: string;
}
export function fitToCanvasRect({
mode,
charSize,
rectWidth,
fullText,
shortText,
}: fitToCanvasRectProps) {
switch (mode) {
case TailMode:
// Case 1:
// content fits rectangle width
// | rectangle |
// | text |
if (charSize * fullText.length <= rectWidth) {
// assume it's a monospaced font
return {
mode,
text: fullText,
marginLeft: margin,
};
}
// assume it's a monospaced font
// if not the case, use
// ctx.measureText(shortName).width
const shortTextWidth = charSize * shortText.length;
// Case 2:
// short text fits rectangle width
// | rectangle |
// | long_text_text |
// | shorttext |
if (shortTextWidth <= rectWidth) {
// assume it's a monospaced font
return {
mode,
text: shortText,
marginLeft: margin,
};
}
// Case 3:
// short text is bigger than rectangle width
// add a negative margin left
// so that the 'tail' of the string is visible
// | rectangle |
// | my_short_text |
return {
mode,
text: shortText,
marginLeft: -(shortTextWidth - rectWidth + margin),
};
// Case 3:
// Normal
case HeadMode:
default:
return {
mode,
text: fullText,
marginLeft: margin,
};
}
}
/**
* Returns an inline style in React format
* used to fit the content into a table cell
* or an empty object if not applicable.
* @param {FitModes} mode - The mode
*/
export function fitIntoTableCell(mode: FitModes) {
switch (mode) {
case TailMode:
return {
// prints from right to left
direction: 'rtl',
overflow: 'hidden',
textOverflow: 'ellipsis',
};
case HeadMode:
default:
return {
overflow: 'hidden',
textOverflow: 'ellipsis',
};
}
}
| 24.674797 | 129 | 0.600988 | 65 | 2 | 0 | 2 | 4 | 5 | 0 | 0 | 4 | 2 | 0 | 22 | 763 | 0.005242 | 0.005242 | 0.006553 | 0.002621 | 0 | 0 | 0.307692 | 0.203315 | export const TailMode = 'TAIL';
export const HeadMode = 'HEAD';
export type FitModes = typeof TailMode | typeof HeadMode;
const margin = 3;
/**
* Returns a text and margin left used to write text into a canvas rectangle
*
* @param {FitModes} mode -
* @param {number} charSize - Size in pixels of an individual character. Assumes it's a monospace font.
* @param {number} rectWidth - Width in pixels of the rectangle
* @param {string} fullText - The text that will be first tried.
* @param {string} shortText - The text that willbe used when fullText can't fit. It's normally a substring of the original text.
*/
interface fitToCanvasRectProps {
mode;
/** charSize - Size in pixels of an individual character. Assumes it's a monospace font. */
charSize;
/** Width in pixels of the rectangle */
rectWidth;
/** The text that will be first tried to fit */
fullText;
/** The text that willbe used when fullText can't fit. It's normally a substring of the original text. */
shortText;
}
export function fitToCanvasRect({
mode,
charSize,
rectWidth,
fullText,
shortText,
}) {
switch (mode) {
case TailMode:
// Case 1:
// content fits rectangle width
// | rectangle |
// | text |
if (charSize * fullText.length <= rectWidth) {
// assume it's a monospaced font
return {
mode,
text: fullText,
marginLeft: margin,
};
}
// assume it's a monospaced font
// if not the case, use
// ctx.measureText(shortName).width
const shortTextWidth = charSize * shortText.length;
// Case 2:
// short text fits rectangle width
// | rectangle |
// | long_text_text |
// | shorttext |
if (shortTextWidth <= rectWidth) {
// assume it's a monospaced font
return {
mode,
text: shortText,
marginLeft: margin,
};
}
// Case 3:
// short text is bigger than rectangle width
// add a negative margin left
// so that the 'tail' of the string is visible
// | rectangle |
// | my_short_text |
return {
mode,
text: shortText,
marginLeft: -(shortTextWidth - rectWidth + margin),
};
// Case 3:
// Normal
case HeadMode:
default:
return {
mode,
text: fullText,
marginLeft: margin,
};
}
}
/**
* Returns an inline style in React format
* used to fit the content into a table cell
* or an empty object if not applicable.
* @param {FitModes} mode - The mode
*/
export function fitIntoTableCell(mode) {
switch (mode) {
case TailMode:
return {
// prints from right to left
direction: 'rtl',
overflow: 'hidden',
textOverflow: 'ellipsis',
};
case HeadMode:
default:
return {
overflow: 'hidden',
textOverflow: 'ellipsis',
};
}
}
|
0a93fbe05d1cd76f3e516c2c4797c5d2f936cbf9 | 1,516 | ts | TypeScript | src/utilities.ts | KillerJulian/node-anemometer | 90bdb1742775c1ad355a4f81f04e863db82f8300 | [
"MIT"
] | null | null | null | src/utilities.ts | KillerJulian/node-anemometer | 90bdb1742775c1ad355a4f81f04e863db82f8300 | [
"MIT"
] | 1 | 2022-01-28T19:59:45.000Z | 2022-02-06T11:12:38.000Z | src/utilities.ts | KillerJulian/node-anemometer | 90bdb1742775c1ad355a4f81f04e863db82f8300 | [
"MIT"
] | null | null | null | export enum WindSpeedUnits {
kilometersPerHour = 'km/h',
metersPerSecond = 'm/s',
knots = 'kn'
}
export class WindSpeed {
constructor(readonly value: number, readonly unit: WindSpeedUnits) {}
rounded(decimalPlaces = 1) {
return round(this.value, decimalPlaces);
}
toKilometersPerHour() {
switch (this.unit) {
case WindSpeedUnits.metersPerSecond: {
return new WindSpeed(this.value * 3.6, WindSpeedUnits.kilometersPerHour);
}
case WindSpeedUnits.knots: {
return new WindSpeed(this.value * 1.852, WindSpeedUnits.kilometersPerHour);
}
default:
return this;
}
}
toMetersPerSecond() {
switch (this.unit) {
case WindSpeedUnits.kilometersPerHour: {
return new WindSpeed(this.value / 3.6, WindSpeedUnits.metersPerSecond);
}
case WindSpeedUnits.knots: {
return new WindSpeed(this.value / 1.944, WindSpeedUnits.metersPerSecond);
}
default:
return this;
}
}
toKnots() {
switch (this.unit) {
case WindSpeedUnits.kilometersPerHour: {
return new WindSpeed(this.value / 1.852, WindSpeedUnits.knots);
}
case WindSpeedUnits.metersPerSecond: {
return new WindSpeed(this.value * 1.944, WindSpeedUnits.knots);
}
default:
return this;
}
}
}
export function round(value: number, decimalPlaces: number) {
if (value % 1 != 0) {
return Number(value.toFixed(decimalPlaces));
}
return value;
}
export function calcFactor(radius: number, adjustment: number) {
return ((2 * Math.PI * radius) / 100000) * 3600 * adjustment;
}
| 23.323077 | 79 | 0.694591 | 56 | 7 | 0 | 7 | 0 | 0 | 1 | 0 | 5 | 1 | 0 | 5.142857 | 523 | 0.026769 | 0 | 0 | 0.001912 | 0 | 0 | 0.357143 | 0.235543 | export enum WindSpeedUnits {
kilometersPerHour = 'km/h',
metersPerSecond = 'm/s',
knots = 'kn'
}
export class WindSpeed {
constructor(readonly value, readonly unit) {}
rounded(decimalPlaces = 1) {
return round(this.value, decimalPlaces);
}
toKilometersPerHour() {
switch (this.unit) {
case WindSpeedUnits.metersPerSecond: {
return new WindSpeed(this.value * 3.6, WindSpeedUnits.kilometersPerHour);
}
case WindSpeedUnits.knots: {
return new WindSpeed(this.value * 1.852, WindSpeedUnits.kilometersPerHour);
}
default:
return this;
}
}
toMetersPerSecond() {
switch (this.unit) {
case WindSpeedUnits.kilometersPerHour: {
return new WindSpeed(this.value / 3.6, WindSpeedUnits.metersPerSecond);
}
case WindSpeedUnits.knots: {
return new WindSpeed(this.value / 1.944, WindSpeedUnits.metersPerSecond);
}
default:
return this;
}
}
toKnots() {
switch (this.unit) {
case WindSpeedUnits.kilometersPerHour: {
return new WindSpeed(this.value / 1.852, WindSpeedUnits.knots);
}
case WindSpeedUnits.metersPerSecond: {
return new WindSpeed(this.value * 1.944, WindSpeedUnits.knots);
}
default:
return this;
}
}
}
export /* Example usages of 'round' are shown below:
round(this.value, decimalPlaces);
*/
function round(value, decimalPlaces) {
if (value % 1 != 0) {
return Number(value.toFixed(decimalPlaces));
}
return value;
}
export function calcFactor(radius, adjustment) {
return ((2 * Math.PI * radius) / 100000) * 3600 * adjustment;
}
|
0a9c7bb10e758660ff826c2f8d9ba0c28d2bde3c | 3,758 | ts | TypeScript | src/physics/vectors.ts | donatto-minaya/ax-calculator | 1b015e2e58796b76bd40fa3055b8709e51137a08 | [
"Apache-2.0"
] | 3 | 2022-01-04T20:01:33.000Z | 2022-02-24T03:27:24.000Z | src/physics/vectors.ts | donatto22/ax-calculator | 1b015e2e58796b76bd40fa3055b8709e51137a08 | [
"Apache-2.0"
] | null | null | null | src/physics/vectors.ts | donatto22/ax-calculator | 1b015e2e58796b76bd40fa3055b8709e51137a08 | [
"Apache-2.0"
] | 1 | 2022-02-15T23:35:52.000Z | 2022-02-15T23:35:52.000Z | export const Vectors = {
sum: function(...vectors: Array<Array<number>>): string | object {
var arr_x = [], arr_y = [];
for(var i = 0; i <= vectors.length - 1; i++) {
if(typeof vectors[i] != 'object') {
return "Only objects"
}
else if(typeof vectors[i][0] != 'number' || typeof vectors[i][1] != 'number') {
return "Only numbers in the objects"
}
else {
arr_x.push(vectors[i][0])
arr_y.push(vectors[i][1])
}
}
var x = arr_x.reduce(_sum)
var y = arr_y.reduce(_sum)
var expression = validateExpression(x, y)
var cartesian = [x, y]
var unit_vector = unitVector(x, y)
return {
x, y, expression, cartesian, unit_vector
}
},
substract: function(...vectors: Array<Array<number>>): string | object {
var arr_x = [], arr_y = [];
for(var i = 0; i <= vectors.length - 1; i++) {
if(typeof vectors[i] != 'object') {
return "Only objects"
}
else if(typeof vectors[i][0] != 'number' || typeof vectors[i][1] != 'number') {
return "Only numbers in the objects"
}
else {
arr_x.push(vectors[i][0])
arr_y.push(vectors[i][1])
}
}
var x = arr_x.reduce(_substract)
var y = arr_y.reduce(_substract)
var expression = validateExpression(x, y)
var cartesian = [x, y]
var unit_vector = unitVector(x, y)
return {
x, y, expression, cartesian, unit_vector
}
},
product: function(...vectors: Array<Array<number>>): string | number {
var arr_x =[], arr_y = [];
for(var i = 0; i <= vectors.length - 1; i++) {
if(typeof vectors[i] != 'object') {
return "Only objects"
}
else if(typeof vectors[i][0] != 'number' || typeof vectors[i][1] != 'number') {
return "Only numbers in the objects"
}
else {
arr_x.push(vectors[i][0])
arr_y.push(vectors[i][1])
}
}
var x = arr_x.reduce(_product)
var y = arr_y.reduce(_product)
return x + y;
},
unitVector: function(vector: Array<number>) {
return unitVector(vector[0], vector[1]);
}
}
const _sum = (accumulator: any, curr: any) => accumulator + curr;
const _substract = (accumulator: number, curr: number) => accumulator - curr;
const _product = (accumulator: number, curr: number) => accumulator * curr;
function validateExpression(x: string | number, y: string | number) {
let expression
if(x == 0)
x = ''
if(y == 0)
y = ''
if(x == 1)
x = 'i'
if(y == 1)
y = 'i'
if(x > 1)
x = `${x}i`
if(y > 1)
y = `${y}j`
if(y < 0)
expression = `${x} - ${Number.parseInt(String(y)) * -1}j`
else if(x < 0)
expression = `-${Number.parseInt(String(x)) * -1}i + ${y}`
else if(x < 0 && y < 0)
expression = `-${Number.parseInt(String(x)) * -1}i - ${Number.parseInt(String(y)) * -1}j`
else
expression = `${x} + ${y}`
return expression;
}
function unitVector(x: number, y: number) {
var module = ((x ** 2) + (y ** 2)) ** (1/2);
let x2 = Number.parseFloat((Number.parseFloat((x / module).toString())).toString().match(/^-?\d+(?:\.\d{0,2})?/)![0])
let y2 = Number.parseFloat((Number.parseFloat((y / module).toString())).toString().match(/^-?\d+(?:\.\d{0,2})?/)![0])
return [x2, y2]
} | 26.842857 | 121 | 0.480841 | 102 | 9 | 0 | 14 | 29 | 0 | 2 | 2 | 20 | 0 | 9 | 9.777778 | 1,076 | 0.021375 | 0.026952 | 0 | 0 | 0.008364 | 0.038462 | 0.384615 | 0.306281 | export const Vectors = {
sum: function(...vectors) {
var arr_x = [], arr_y = [];
for(var i = 0; i <= vectors.length - 1; i++) {
if(typeof vectors[i] != 'object') {
return "Only objects"
}
else if(typeof vectors[i][0] != 'number' || typeof vectors[i][1] != 'number') {
return "Only numbers in the objects"
}
else {
arr_x.push(vectors[i][0])
arr_y.push(vectors[i][1])
}
}
var x = arr_x.reduce(_sum)
var y = arr_y.reduce(_sum)
var expression = validateExpression(x, y)
var cartesian = [x, y]
var unit_vector = unitVector(x, y)
return {
x, y, expression, cartesian, unit_vector
}
},
substract: function(...vectors) {
var arr_x = [], arr_y = [];
for(var i = 0; i <= vectors.length - 1; i++) {
if(typeof vectors[i] != 'object') {
return "Only objects"
}
else if(typeof vectors[i][0] != 'number' || typeof vectors[i][1] != 'number') {
return "Only numbers in the objects"
}
else {
arr_x.push(vectors[i][0])
arr_y.push(vectors[i][1])
}
}
var x = arr_x.reduce(_substract)
var y = arr_y.reduce(_substract)
var expression = validateExpression(x, y)
var cartesian = [x, y]
var unit_vector = unitVector(x, y)
return {
x, y, expression, cartesian, unit_vector
}
},
product: function(...vectors) {
var arr_x =[], arr_y = [];
for(var i = 0; i <= vectors.length - 1; i++) {
if(typeof vectors[i] != 'object') {
return "Only objects"
}
else if(typeof vectors[i][0] != 'number' || typeof vectors[i][1] != 'number') {
return "Only numbers in the objects"
}
else {
arr_x.push(vectors[i][0])
arr_y.push(vectors[i][1])
}
}
var x = arr_x.reduce(_product)
var y = arr_y.reduce(_product)
return x + y;
},
unitVector: function(vector) {
return unitVector(vector[0], vector[1]);
}
}
/* Example usages of '_sum' are shown below:
arr_x.reduce(_sum);
arr_y.reduce(_sum);
*/
const _sum = (accumulator, curr) => accumulator + curr;
/* Example usages of '_substract' are shown below:
arr_x.reduce(_substract);
arr_y.reduce(_substract);
*/
const _substract = (accumulator, curr) => accumulator - curr;
/* Example usages of '_product' are shown below:
arr_x.reduce(_product);
arr_y.reduce(_product);
*/
const _product = (accumulator, curr) => accumulator * curr;
/* Example usages of 'validateExpression' are shown below:
validateExpression(x, y);
*/
function validateExpression(x, y) {
let expression
if(x == 0)
x = ''
if(y == 0)
y = ''
if(x == 1)
x = 'i'
if(y == 1)
y = 'i'
if(x > 1)
x = `${x}i`
if(y > 1)
y = `${y}j`
if(y < 0)
expression = `${x} - ${Number.parseInt(String(y)) * -1}j`
else if(x < 0)
expression = `-${Number.parseInt(String(x)) * -1}i + ${y}`
else if(x < 0 && y < 0)
expression = `-${Number.parseInt(String(x)) * -1}i - ${Number.parseInt(String(y)) * -1}j`
else
expression = `${x} + ${y}`
return expression;
}
/* Example usages of 'unitVector' are shown below:
unitVector(x, y);
;
unitVector(vector[0], vector[1]);
*/
function unitVector(x, y) {
var module = ((x ** 2) + (y ** 2)) ** (1/2);
let x2 = Number.parseFloat((Number.parseFloat((x / module).toString())).toString().match(/^-?\d+(?:\.\d{0,2})?/)![0])
let y2 = Number.parseFloat((Number.parseFloat((y / module).toString())).toString().match(/^-?\d+(?:\.\d{0,2})?/)![0])
return [x2, y2]
} |
0ac468cdf3c8d2136343160aa7b224310a7ba0b6 | 10,011 | ts | TypeScript | src/chromatic/lib/jsdom-shims.ts | Red-Folder/chromatic-core | ba8824bf4084c7b98bc38930b151d0b664211f76 | [
"MIT"
] | null | null | null | src/chromatic/lib/jsdom-shims.ts | Red-Folder/chromatic-core | ba8824bf4084c7b98bc38930b151d0b664211f76 | [
"MIT"
] | 1 | 2022-01-22T12:07:16.000Z | 2022-01-22T12:07:16.000Z | src/chromatic/lib/jsdom-shims.ts | Red-Folder/chromatic-core | ba8824bf4084c7b98bc38930b151d0b664211f76 | [
"MIT"
] | null | null | null | /* eslint-disable @typescript-eslint/no-empty-function, max-classes-per-file, no-param-reassign */
const alwaysFn = (C: any): any => {
// Search up the prototype chain until we hit base. The base class of Class has no name I guess.
const classHierarchy = [];
for (let curr = C; curr.name; curr = Object.getPrototypeOf(curr)) {
classHierarchy.push(curr);
}
// Get all static methods defined on any ancestor
const statics = classHierarchy
.map(klass => Object.getOwnPropertyNames(klass))
.reduce((a, b) => [...a, ...b], []) // flatten
.filter(n => typeof C[n] === 'function')
.reduce((acc: any, name) => {
acc[name] = C[name];
return acc;
}, {});
return Object.assign(
// eslint-disable-next-line func-names
function() {
return new C();
},
C,
statics
);
};
// Add canvas mock based on this comment: https://github.com/jsdom/jsdom/issues/1782#issuecomment-337656878
function mockCanvas(window: any) {
window.HTMLCanvasElement.prototype.getContext = () => ({
fillRect: () => ({}),
clearRect: () => ({}),
getImageData: (_x: number, _y: number, w: number, h: number) => ({ data: new Array(w * h * 4) }),
putImageData: () => ({}),
createImageData: () => [],
setTransform: () => ({}),
drawImage: () => ({}),
save: () => ({}),
fillText: () => ({}),
restore: () => ({}),
beginPath: () => ({}),
moveTo: () => ({}),
lineTo: () => ({}),
closePath: () => ({}),
stroke: () => ({}),
translate: () => ({}),
scale: () => ({}),
rotate: () => ({}),
arc: () => ({}),
fill: () => ({}),
measureText: () => ({ width: 0 }),
transform: () => ({}),
rect: () => ({}),
clip: () => ({}),
});
window.HTMLCanvasElement.prototype.toDataURL = () => '';
}
function mockIntl(window: any) {
if (!window.Intl) {
class IntlMock {
static supportedLocalesOf() {
return [];
}
resolvedOptions() {
return {};
}
}
class IntlFormatMock extends IntlMock {
format() {
return '';
}
formatToParts() {
return [];
}
}
class IntlCollatorMock extends IntlMock {
compare() {
return 0;
}
}
class IntlPluralRulesMock extends IntlMock {
select() {
return '';
}
}
class IntlDateTimeFormatMock extends IntlFormatMock {}
class IntlNumberFormatMock extends IntlFormatMock {}
class IntlListFormatMock extends IntlFormatMock {}
class IntlRelativeTimeFormatMock extends IntlFormatMock {}
Object.defineProperty(window, 'Intl', {
value: {
Collator: alwaysFn(IntlCollatorMock),
DateTimeFormat: alwaysFn(IntlDateTimeFormatMock),
ListFormat: alwaysFn(IntlListFormatMock),
NumberFormat: alwaysFn(IntlNumberFormatMock),
PluralRules: alwaysFn(IntlPluralRulesMock),
RelativeTimeFormat: alwaysFn(IntlRelativeTimeFormatMock),
},
writable: true,
});
}
}
function mockMatchMedia(window: any) {
if (!window.matchMedia) {
Object.defineProperty(window, 'matchMedia', {
value: () => ({
matches: true,
addListener: () => {},
removeListener: () => {},
}),
writable: true,
});
}
}
function mockLocalStorage(window: any) {
if (!window.localStorage) {
class LocalStorageMock {
store: any;
constructor() {
this.store = {};
}
getItem(key: any): any {
return this.store[key];
}
removeItem(key: any) {
delete this.store[key];
}
setItem(key: any, value: any) {
this.store[key] = value.toString();
}
clear() {
this.store = {};
}
}
Object.defineProperty(window, 'localStorage', {
value: new LocalStorageMock(),
writable: true,
});
}
}
function mockWebWorker(window: any) {
if (!window.Worker) {
class WorkerMock {
addEventListener() {}
removeEventLister() {}
postMessage() {}
terminate() {}
}
Object.defineProperty(window, 'Worker', {
value: WorkerMock,
writable: true,
});
}
}
function mockCrypto(window: any) {
if (!window.crypto) {
Object.defineProperty(window, 'crypto', {
value: {
getRandomValues: (arr: any) => arr.fill(0),
},
writable: true,
});
}
}
function mockMimeTypes(window: any) {
if (!window.navigator.mimeTypes) {
Object.defineProperty(window.navigator, 'mimeTypes', {
value: () => [],
writable: true,
});
}
}
function mockFetch(window: any) {
// issue: https://github.com/chromaui/chromatic-cli/issues/14
Object.defineProperty(window, 'fetch', {
value: () =>
new Promise((_res, _rej) => {
// we just let this never resolve
}),
writable: true,
});
}
function mockObjectURL(window: any) {
if (!window.URL.createObjectURL) {
Object.defineProperty(window.URL, 'createObjectURL', { value: () => {}, writable: true });
}
if (!window.URL.revokeObjectURL) {
Object.defineProperty(window.URL, 'revokeObjectURL', { value: () => {}, writable: true });
}
}
function mockMutationObserver(window: any) {
if (!window.MutationObserver) {
// We have to do this in this screwy way because Angular does some monkey patching
// expects an non-es2015 class here.
// eslint-disable-next-line no-inner-declarations
// @ts-ignore
function MutationObserverMock() {}
MutationObserverMock.prototype = {
observe() {
return [];
},
takeRecords() {
return [];
},
disconnect() {},
};
Object.defineProperty(window, 'MutationObserver', {
value: MutationObserverMock,
writable: true,
});
}
}
function mockSVG(window: any) {
// issue: https://github.com/chromaui/chromatic-cli/issues/27
// solution found here: https://github.com/facebook/jest/issues/5379#issuecomment-360044161
// not incuded in jsdom yet: https://github.com/jsdom/jsdom/issues/2128
const svgElements = [
'SVGAElement',
'SVGAltGlyphElement',
'SVGAngle',
'SVGAnimateColorElement',
'SVGAnimateElement',
'SVGAnimateMotionElement',
'SVGAnimateTransformElement',
'SVGAnimatedAngle',
'SVGAnimatedBoolean',
'SVGAnimatedEnumeration',
'SVGAnimatedInteger',
'SVGAnimatedLength',
'SVGAnimatedLengthList',
'SVGAnimatedNumber',
'SVGAnimatedNumberList',
'SVGAnimatedPoints',
'SVGAnimatedPreserveAspectRatio',
'SVGAnimatedRect',
'SVGAnimatedString',
'SVGAnimatedTransformList',
'SVGAnimationElement',
'SVGCircleElement',
'SVGClipPathElement',
'SVGComponentTransferFunctionElement',
'SVGCursorElement',
'SVGDefsElement',
'SVGDescElement',
'SVGDocument',
'SVGElement',
'SVGEllipseElement',
'SVGFEBlendElement',
'SVGFEColorMatrixElement',
'SVGFEComponentTransferElement',
'SVGFECompositeElement',
'SVGFEConvolveMatrixElement',
'SVGFEDiffuseLightingElement',
'SVGFEDisplacementMapElement',
'SVGFEDistantLightElement',
'SVGFEDropShadowElement',
'SVGFEFloodElement',
'SVGFEFuncAElement',
'SVGFEFuncBElement',
'SVGFEFuncGElement',
'SVGFEFuncRElement',
'SVGFEGaussianBlurElement',
'SVGFEImageElement',
'SVGFEMergeElement',
'SVGFEMergeNodeElement',
'SVGFEMorphologyElement',
'SVGFEOffsetElement',
'SVGFEPointLightElement',
'SVGFESpecularLightingElement',
'SVGFESpotLightElement',
'SVGFETileElement',
'SVGFETurbulenceElement',
'SVGFilterElement',
'SVGFilterPrimitiveStandardAttributes',
'SVGFontElement',
'SVGFontFaceElement',
'SVGFontFaceFormatElement',
'SVGFontFaceNameElement',
'SVGFontFaceSrcElement',
'SVGFontFaceUriElement',
'SVGForeignObjectElement',
'SVGGElement',
'SVGGlyphElement',
'SVGGradientElement',
'SVGGraphicsElement',
'SVGHKernElement',
'SVGImageElement',
'SVGLength',
'SVGLengthList',
'SVGLineElement',
'SVGLinearGradientElement',
'SVGMPathElement',
'SVGMaskElement',
'SVGMatrix',
'SVGMetadataElement',
'SVGMissingGlyphElement',
'SVGNumber',
'SVGNumberList',
'SVGPathElement',
'SVGPatternElement',
'SVGPoint',
'SVGPolylineElement',
'SVGPreserveAspectRatio',
'SVGRadialGradientElement',
'SVGRect',
'SVGRectElement',
'SVGSVGElement',
'SVGScriptElement',
'SVGSetElement',
'SVGStopElement',
'SVGStringList',
'SVGStylable',
'SVGStyleElement',
'SVGSwitchElement',
'SVGSymbolElement',
'SVGTRefElement',
'SVGTSpanElement',
'SVGTests',
'SVGTextContentElement',
'SVGTextElement',
'SVGTextPathElement',
'SVGTextPositioningElement',
'SVGTitleElement',
'SVGTransform',
'SVGTransformList',
'SVGTransformable',
'SVGURIReference',
'SVGUnitTypes',
'SVGUseElement',
'SVGVKernElement',
'SVGViewElement',
'SVGZoomAndPan',
];
svgElements.forEach(e => {
if (!window[e]) {
// eslint-disable-next-line no-eval
const Value = eval(`(class ${e} extends window.HTMLElement {})`);
Object.defineProperty(window, e, {
value: Value,
writable: true,
});
}
});
}
export function addShimsToJSDOM(window: any) {
mockSVG(window);
mockMutationObserver(window);
mockObjectURL(window);
mockFetch(window);
mockMimeTypes(window);
mockCrypto(window);
mockWebWorker(window);
mockLocalStorage(window);
mockMatchMedia(window);
mockIntl(window);
mockCanvas(window);
}
| 26.002597 | 108 | 0.59095 | 340 | 73 | 0 | 31 | 6 | 1 | 12 | 22 | 4 | 10 | 2 | 5.479452 | 2,590 | 0.040154 | 0.002317 | 0.000386 | 0.003861 | 0.000772 | 0.198198 | 0.036036 | 0.277554 | /* eslint-disable @typescript-eslint/no-empty-function, max-classes-per-file, no-param-reassign */
/* Example usages of 'alwaysFn' are shown below:
alwaysFn(IntlCollatorMock);
alwaysFn(IntlDateTimeFormatMock);
alwaysFn(IntlListFormatMock);
alwaysFn(IntlNumberFormatMock);
alwaysFn(IntlPluralRulesMock);
alwaysFn(IntlRelativeTimeFormatMock);
*/
const alwaysFn = (C) => {
// Search up the prototype chain until we hit base. The base class of Class has no name I guess.
const classHierarchy = [];
for (let curr = C; curr.name; curr = Object.getPrototypeOf(curr)) {
classHierarchy.push(curr);
}
// Get all static methods defined on any ancestor
const statics = classHierarchy
.map(klass => Object.getOwnPropertyNames(klass))
.reduce((a, b) => [...a, ...b], []) // flatten
.filter(n => typeof C[n] === 'function')
.reduce((acc, name) => {
acc[name] = C[name];
return acc;
}, {});
return Object.assign(
// eslint-disable-next-line func-names
function() {
return new C();
},
C,
statics
);
};
// Add canvas mock based on this comment: https://github.com/jsdom/jsdom/issues/1782#issuecomment-337656878
/* Example usages of 'mockCanvas' are shown below:
mockCanvas(window);
*/
function mockCanvas(window) {
window.HTMLCanvasElement.prototype.getContext = () => ({
fillRect: () => ({}),
clearRect: () => ({}),
getImageData: (_x, _y, w, h) => ({ data: new Array(w * h * 4) }),
putImageData: () => ({}),
createImageData: () => [],
setTransform: () => ({}),
drawImage: () => ({}),
save: () => ({}),
fillText: () => ({}),
restore: () => ({}),
beginPath: () => ({}),
moveTo: () => ({}),
lineTo: () => ({}),
closePath: () => ({}),
stroke: () => ({}),
translate: () => ({}),
scale: () => ({}),
rotate: () => ({}),
arc: () => ({}),
fill: () => ({}),
measureText: () => ({ width: 0 }),
transform: () => ({}),
rect: () => ({}),
clip: () => ({}),
});
window.HTMLCanvasElement.prototype.toDataURL = () => '';
}
/* Example usages of 'mockIntl' are shown below:
mockIntl(window);
*/
function mockIntl(window) {
if (!window.Intl) {
class IntlMock {
static supportedLocalesOf() {
return [];
}
resolvedOptions() {
return {};
}
}
class IntlFormatMock extends IntlMock {
format() {
return '';
}
formatToParts() {
return [];
}
}
class IntlCollatorMock extends IntlMock {
compare() {
return 0;
}
}
class IntlPluralRulesMock extends IntlMock {
select() {
return '';
}
}
class IntlDateTimeFormatMock extends IntlFormatMock {}
class IntlNumberFormatMock extends IntlFormatMock {}
class IntlListFormatMock extends IntlFormatMock {}
class IntlRelativeTimeFormatMock extends IntlFormatMock {}
Object.defineProperty(window, 'Intl', {
value: {
Collator: alwaysFn(IntlCollatorMock),
DateTimeFormat: alwaysFn(IntlDateTimeFormatMock),
ListFormat: alwaysFn(IntlListFormatMock),
NumberFormat: alwaysFn(IntlNumberFormatMock),
PluralRules: alwaysFn(IntlPluralRulesMock),
RelativeTimeFormat: alwaysFn(IntlRelativeTimeFormatMock),
},
writable: true,
});
}
}
/* Example usages of 'mockMatchMedia' are shown below:
mockMatchMedia(window);
*/
function mockMatchMedia(window) {
if (!window.matchMedia) {
Object.defineProperty(window, 'matchMedia', {
value: () => ({
matches: true,
addListener: () => {},
removeListener: () => {},
}),
writable: true,
});
}
}
/* Example usages of 'mockLocalStorage' are shown below:
mockLocalStorage(window);
*/
function mockLocalStorage(window) {
if (!window.localStorage) {
class LocalStorageMock {
store;
constructor() {
this.store = {};
}
getItem(key) {
return this.store[key];
}
removeItem(key) {
delete this.store[key];
}
setItem(key, value) {
this.store[key] = value.toString();
}
clear() {
this.store = {};
}
}
Object.defineProperty(window, 'localStorage', {
value: new LocalStorageMock(),
writable: true,
});
}
}
/* Example usages of 'mockWebWorker' are shown below:
mockWebWorker(window);
*/
function mockWebWorker(window) {
if (!window.Worker) {
class WorkerMock {
addEventListener() {}
removeEventLister() {}
postMessage() {}
terminate() {}
}
Object.defineProperty(window, 'Worker', {
value: WorkerMock,
writable: true,
});
}
}
/* Example usages of 'mockCrypto' are shown below:
mockCrypto(window);
*/
function mockCrypto(window) {
if (!window.crypto) {
Object.defineProperty(window, 'crypto', {
value: {
getRandomValues: (arr) => arr.fill(0),
},
writable: true,
});
}
}
/* Example usages of 'mockMimeTypes' are shown below:
mockMimeTypes(window);
*/
function mockMimeTypes(window) {
if (!window.navigator.mimeTypes) {
Object.defineProperty(window.navigator, 'mimeTypes', {
value: () => [],
writable: true,
});
}
}
/* Example usages of 'mockFetch' are shown below:
mockFetch(window);
*/
function mockFetch(window) {
// issue: https://github.com/chromaui/chromatic-cli/issues/14
Object.defineProperty(window, 'fetch', {
value: () =>
new Promise((_res, _rej) => {
// we just let this never resolve
}),
writable: true,
});
}
/* Example usages of 'mockObjectURL' are shown below:
mockObjectURL(window);
*/
function mockObjectURL(window) {
if (!window.URL.createObjectURL) {
Object.defineProperty(window.URL, 'createObjectURL', { value: () => {}, writable: true });
}
if (!window.URL.revokeObjectURL) {
Object.defineProperty(window.URL, 'revokeObjectURL', { value: () => {}, writable: true });
}
}
/* Example usages of 'mockMutationObserver' are shown below:
mockMutationObserver(window);
*/
function mockMutationObserver(window) {
if (!window.MutationObserver) {
// We have to do this in this screwy way because Angular does some monkey patching
// expects an non-es2015 class here.
// eslint-disable-next-line no-inner-declarations
// @ts-ignore
/* Example usages of 'MutationObserverMock' are shown below:
MutationObserverMock.prototype = {
observe() {
return [];
},
takeRecords() {
return [];
},
disconnect() { },
};
;
*/
function MutationObserverMock() {}
MutationObserverMock.prototype = {
observe() {
return [];
},
takeRecords() {
return [];
},
disconnect() {},
};
Object.defineProperty(window, 'MutationObserver', {
value: MutationObserverMock,
writable: true,
});
}
}
/* Example usages of 'mockSVG' are shown below:
mockSVG(window);
*/
function mockSVG(window) {
// issue: https://github.com/chromaui/chromatic-cli/issues/27
// solution found here: https://github.com/facebook/jest/issues/5379#issuecomment-360044161
// not incuded in jsdom yet: https://github.com/jsdom/jsdom/issues/2128
const svgElements = [
'SVGAElement',
'SVGAltGlyphElement',
'SVGAngle',
'SVGAnimateColorElement',
'SVGAnimateElement',
'SVGAnimateMotionElement',
'SVGAnimateTransformElement',
'SVGAnimatedAngle',
'SVGAnimatedBoolean',
'SVGAnimatedEnumeration',
'SVGAnimatedInteger',
'SVGAnimatedLength',
'SVGAnimatedLengthList',
'SVGAnimatedNumber',
'SVGAnimatedNumberList',
'SVGAnimatedPoints',
'SVGAnimatedPreserveAspectRatio',
'SVGAnimatedRect',
'SVGAnimatedString',
'SVGAnimatedTransformList',
'SVGAnimationElement',
'SVGCircleElement',
'SVGClipPathElement',
'SVGComponentTransferFunctionElement',
'SVGCursorElement',
'SVGDefsElement',
'SVGDescElement',
'SVGDocument',
'SVGElement',
'SVGEllipseElement',
'SVGFEBlendElement',
'SVGFEColorMatrixElement',
'SVGFEComponentTransferElement',
'SVGFECompositeElement',
'SVGFEConvolveMatrixElement',
'SVGFEDiffuseLightingElement',
'SVGFEDisplacementMapElement',
'SVGFEDistantLightElement',
'SVGFEDropShadowElement',
'SVGFEFloodElement',
'SVGFEFuncAElement',
'SVGFEFuncBElement',
'SVGFEFuncGElement',
'SVGFEFuncRElement',
'SVGFEGaussianBlurElement',
'SVGFEImageElement',
'SVGFEMergeElement',
'SVGFEMergeNodeElement',
'SVGFEMorphologyElement',
'SVGFEOffsetElement',
'SVGFEPointLightElement',
'SVGFESpecularLightingElement',
'SVGFESpotLightElement',
'SVGFETileElement',
'SVGFETurbulenceElement',
'SVGFilterElement',
'SVGFilterPrimitiveStandardAttributes',
'SVGFontElement',
'SVGFontFaceElement',
'SVGFontFaceFormatElement',
'SVGFontFaceNameElement',
'SVGFontFaceSrcElement',
'SVGFontFaceUriElement',
'SVGForeignObjectElement',
'SVGGElement',
'SVGGlyphElement',
'SVGGradientElement',
'SVGGraphicsElement',
'SVGHKernElement',
'SVGImageElement',
'SVGLength',
'SVGLengthList',
'SVGLineElement',
'SVGLinearGradientElement',
'SVGMPathElement',
'SVGMaskElement',
'SVGMatrix',
'SVGMetadataElement',
'SVGMissingGlyphElement',
'SVGNumber',
'SVGNumberList',
'SVGPathElement',
'SVGPatternElement',
'SVGPoint',
'SVGPolylineElement',
'SVGPreserveAspectRatio',
'SVGRadialGradientElement',
'SVGRect',
'SVGRectElement',
'SVGSVGElement',
'SVGScriptElement',
'SVGSetElement',
'SVGStopElement',
'SVGStringList',
'SVGStylable',
'SVGStyleElement',
'SVGSwitchElement',
'SVGSymbolElement',
'SVGTRefElement',
'SVGTSpanElement',
'SVGTests',
'SVGTextContentElement',
'SVGTextElement',
'SVGTextPathElement',
'SVGTextPositioningElement',
'SVGTitleElement',
'SVGTransform',
'SVGTransformList',
'SVGTransformable',
'SVGURIReference',
'SVGUnitTypes',
'SVGUseElement',
'SVGVKernElement',
'SVGViewElement',
'SVGZoomAndPan',
];
svgElements.forEach(e => {
if (!window[e]) {
// eslint-disable-next-line no-eval
const Value = eval(`(class ${e} extends window.HTMLElement {})`);
Object.defineProperty(window, e, {
value: Value,
writable: true,
});
}
});
}
export function addShimsToJSDOM(window) {
mockSVG(window);
mockMutationObserver(window);
mockObjectURL(window);
mockFetch(window);
mockMimeTypes(window);
mockCrypto(window);
mockWebWorker(window);
mockLocalStorage(window);
mockMatchMedia(window);
mockIntl(window);
mockCanvas(window);
}
|
0ac7f06fab3e6c96afdb4f4fd1f32942b98e0e8c | 11,313 | ts | TypeScript | src/utils/game.ts | muhelen/cross-wordle | e3ce60004301c4725af28e1fb2e24f02f465cb97 | [
"MIT"
] | 7 | 2022-02-05T22:57:45.000Z | 2022-02-14T20:45:04.000Z | src/utils/game.ts | muhelen/cross-wordle | e3ce60004301c4725af28e1fb2e24f02f465cb97 | [
"MIT"
] | 2 | 2022-02-09T03:09:47.000Z | 2022-03-11T06:43:06.000Z | src/utils/game.ts | muhelen/cross-wordle | e3ce60004301c4725af28e1fb2e24f02f465cb97 | [
"MIT"
] | 2 | 2022-02-09T04:10:19.000Z | 2022-02-09T16:55:15.000Z | export const Config = {
MaxLetters: 20,
TileCount: 6,
TileSize: 60,
TileSpacing: 10,
};
export enum Directions {
Up,
Left,
Down,
Right,
}
export enum CursorDirections {
LeftToRight = "left-to-right",
TopToBottom = "top-to-bottom",
}
type Cursor = {
row: number;
col: number;
direction: CursorDirections;
};
export type Letter = {
id: string;
letter: string; // TODO: refactor to `char`
};
export enum TileState {
IDLE = "idle",
VALID = "valid",
INVALID = "invalid",
MIXED = "mixed",
}
export enum TileChangeReason {
MOVED = "moved",
LETTER = "letter",
}
export type Tile = {
id: string;
row: number;
col: number;
letter: Letter | null;
state: TileState;
changeReason: TileChangeReason | undefined;
};
export type Board = {
tiles: Tile[][];
cursor: Cursor;
};
// https://en.wikipedia.org/wiki/Bananagrams#cite_note-7
const Letters = [
"J",
"K",
"Q",
"X",
"Z",
"J",
"K",
"Q",
"X",
"Z",
"B",
"C",
"F",
"H",
"M",
"P",
"V",
"W",
"Y",
"B",
"C",
"F",
"H",
"M",
"P",
"V",
"W",
"Y",
"B",
"C",
"F",
"H",
"M",
"P",
"V",
"W",
"Y",
"G",
"G",
"G",
"G",
"L",
"L",
"L",
"L",
"L",
"D",
"S",
"U",
"D",
"S",
"U",
"D",
"S",
"U",
"D",
"S",
"U",
"D",
"S",
"U",
"D",
"S",
"U",
"N",
"N",
"N",
"N",
"N",
"N",
"N",
"N",
"T",
"R",
"T",
"R",
"T",
"R",
"T",
"R",
"T",
"R",
"T",
"R",
"T",
"R",
"T",
"R",
"T",
"R",
"O",
"O",
"O",
"O",
"O",
"O",
"O",
"O",
"O",
"O",
"O",
"I",
"I",
"I",
"I",
"I",
"I",
"I",
"I",
"I",
"I",
"I",
"I",
"A",
"A",
"A",
"A",
"A",
"A",
"A",
"A",
"A",
"A",
"A",
"A",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
];
// @TODO use a seeded randomizer so we can get one combo per day.
function getRandom<T>(arr: T[], n: number) {
var result = new Array(n),
len = arr.length,
taken = new Array(len);
if (n > len) throw new RangeError("getRandom: more elements taken than available");
while (n--) {
var x = Math.floor(Math.random() * len);
result[n] = arr[x in taken ? taken[x] : x];
taken[x] = --len in taken ? taken[len] : len;
}
return result;
}
export function shuffle<T>(arr: T[]): T[] {
return getRandom(arr, arr.length);
}
export function getRandomLetters(n: number) {
return getRandom(Letters, n);
}
export function wrapCursor(board: Board, cursor: Cursor): Cursor {
const maxRow = board.tiles.length;
const maxCol = board.tiles[0].length;
const rowOverflow = Math.floor(cursor.row / maxRow);
const colOverflow = Math.floor(cursor.col / maxCol);
// Simple case, just bring back to reality.
if (rowOverflow && colOverflow) {
return {
row: cursor.row % maxRow,
col: cursor.col % maxCol,
direction: cursor.direction,
};
}
// If only the row is overflowing, increment as needed.
if (rowOverflow > 0) {
return {
row: cursor.row % maxRow,
col: (cursor.col + rowOverflow) % maxCol,
direction: cursor.direction,
};
}
// If only the col is overflowing, increment as needed.
if (colOverflow > 0) {
return {
row: (cursor.row + colOverflow) % maxRow,
col: (maxCol + cursor.col) % maxCol,
direction: cursor.direction,
};
}
// If only the row is underflowing, increment as needed.
if (rowOverflow < 0) {
return {
row: (maxRow + cursor.row) % maxRow,
col: (maxCol + cursor.col + rowOverflow) % maxCol,
direction: cursor.direction,
};
}
// If only the col is underflowing, increment as needed.
if (colOverflow < 0) {
return {
row: (maxRow + cursor.row + colOverflow) % maxRow,
col: (maxCol + cursor.col) % maxCol,
direction: cursor.direction,
};
}
return cursor;
}
export function incrementCursor(board: Board): Cursor {
return moveBoardCursorToNextEmptyTile(board) || board.cursor;
}
function moveBoardCursorToNextEmptyTile(board: Board) {
const { row, col, direction } = board.cursor;
switch (direction) {
case CursorDirections.LeftToRight: {
// If we're on a letter, always just move forward 1.
if (getTileAtCursor(board).letter) {
return wrapCursor(board, {
row,
col: col + 1,
direction,
});
}
// Otherwise, move to next empty square.
let nextCursor;
// Max 36 attempts. Kinda jank but guarentees no infinte loop.
for (let i = 1; i < 36; i++) {
nextCursor = wrapCursor(board, {
row,
col: col + i,
direction,
});
if (!getTileAtCursor(board, nextCursor).letter) {
return nextCursor;
}
}
return nextCursor;
}
case CursorDirections.TopToBottom: {
// If we're on a letter, always just move forward 1.
if (getTileAtCursor(board).letter) {
return wrapCursor(board, {
row: row + 1,
col,
direction,
});
}
// Otherwise, move to next empty square.
let nextCursor;
// Max 36 attempts. Kinda jank but guarentees no infinte loop.
for (let i = 1; i < 36; i++) {
nextCursor = wrapCursor(board, {
row: row + i,
col,
direction,
});
if (!getTileAtCursor(board, nextCursor).letter) {
return nextCursor;
}
}
return nextCursor;
}
}
}
export function getTileAtCursor(board: Board, cursor?: Cursor): Tile {
const c = cursor || board.cursor;
return board.tiles[c.row][c.col];
}
export function updateCursorInDirection(board: Board, direction: Directions): Board {
switch (direction) {
case Directions.Down:
return {
...board,
cursor: wrapCursor(board, {
row: board.cursor.row + 1,
col: board.cursor.col,
direction: board.cursor.direction,
}),
};
case Directions.Up:
return {
...board,
cursor: wrapCursor(board, {
row: board.cursor.row - 1,
col: board.cursor.col,
direction: board.cursor.direction,
}),
};
case Directions.Left:
return {
...board,
cursor: wrapCursor(board, {
row: board.cursor.row,
col: board.cursor.col - 1,
direction: board.cursor.direction,
}),
};
case Directions.Right:
return {
...board,
cursor: wrapCursor(board, {
row: board.cursor.row,
col: board.cursor.col + 1,
direction: board.cursor.direction,
}),
};
}
}
export function decrementCursor(board: Board): Cursor {
const cursor = board.cursor;
switch (cursor.direction) {
case CursorDirections.LeftToRight:
return wrapCursor(board, {
row: cursor.row,
col: cursor.col - 1,
direction: cursor.direction,
});
case CursorDirections.TopToBottom:
return wrapCursor(board, {
row: cursor.row - 1,
col: cursor.col,
direction: cursor.direction,
});
}
}
function shiftBoardUp(board: Board): Board {
const topRow = board.tiles[0];
// Don't move board in this direction if it'd overflow.
if (topRow.some((tile) => tile.letter !== null)) {
return board;
}
const newLetterPositions = [...board.tiles.slice(1), topRow].map((row) =>
row.map((tile) => tile.letter),
);
const newTiles = board.tiles.slice();
for (let r = 0; r < board.tiles.length; r++) {
for (let c = 0; c < board.tiles[0].length; c++) {
newTiles[r][c] = {
...newTiles[r][c],
letter: newLetterPositions[r][c],
changeReason: TileChangeReason.MOVED,
};
}
}
return {
...board,
tiles: newTiles,
};
}
function shiftBoardDown(board: Board): Board {
const bottomRow = board.tiles[board.tiles.length - 1];
// Don't move board in this direction if it'd overflow.
if (bottomRow.some((tile) => tile.letter !== null)) {
return board;
}
const newLetterPositions = [bottomRow, ...board.tiles.slice(0, board.tiles.length - 1)].map(
(row) => row.map((tile) => tile.letter),
);
const newTiles = board.tiles.slice();
for (let r = 0; r < board.tiles.length; r++) {
for (let c = 0; c < board.tiles[0].length; c++) {
newTiles[r][c] = {
...newTiles[r][c],
letter: newLetterPositions[r][c],
changeReason: TileChangeReason.MOVED,
};
}
}
return {
...board,
tiles: newTiles,
};
}
function shiftBoardLeft(board: Board): Board {
const maxC = board.tiles[0].length;
const leftRow = board.tiles.map((row) => row[0]).flat();
// Don't move board in this direction if it'd overflow.
if (leftRow.some((tile) => tile.letter !== null)) {
return board;
}
const prevLetterPositions = board.tiles.map((row) => row.map((tile) => tile.letter));
const newLetterPositions = prevLetterPositions.map((_) => []) as (Letter | null)[][];
for (let r = 0; r < board.tiles.length; r++) {
for (let c = 0; c < board.tiles[0].length; c++) {
newLetterPositions[r][c] = prevLetterPositions[r][(maxC + c + 1) % maxC];
}
}
const newTiles = board.tiles.slice();
for (let r = 0; r < board.tiles.length; r++) {
for (let c = 0; c < board.tiles[0].length; c++) {
newTiles[r][c] = {
...newTiles[r][c],
letter: newLetterPositions[r][c],
changeReason: TileChangeReason.MOVED,
};
}
}
return {
...board,
tiles: newTiles,
};
}
function shiftBoardRight(board: Board): Board {
const maxC = board.tiles[0].length;
const rightRow = board.tiles.map((row) => row[row.length - 1]).flat();
// Don't move board in this direction if it'd overflow.
if (rightRow.some((tile) => tile.letter !== null)) {
return board;
}
const prevLetterPositions = board.tiles.map((row) => row.map((tile) => tile.letter));
const newLetterPositions = prevLetterPositions.map((_) => []) as (Letter | null)[][];
for (let r = 0; r < board.tiles.length; r++) {
for (let c = 0; c < board.tiles[0].length; c++) {
newLetterPositions[r][c] = prevLetterPositions[r][(maxC + c - 1) % maxC];
}
}
const newTiles = board.tiles.slice();
for (let r = 0; r < board.tiles.length; r++) {
for (let c = 0; c < board.tiles[0].length; c++) {
newTiles[r][c] = {
...newTiles[r][c],
letter: newLetterPositions[r][c],
changeReason: TileChangeReason.MOVED,
};
}
}
return {
...board,
tiles: newTiles,
};
}
export function moveBoard(board: Board, direction: Directions): Board {
switch (direction) {
case Directions.Up:
return shiftBoardUp(board);
case Directions.Down:
return shiftBoardDown(board);
case Directions.Left:
return shiftBoardLeft(board);
case Directions.Right:
return shiftBoardRight(board);
}
}
export function getPuzzleNumber() {
const now = new Date();
const start = new Date(now.getFullYear(), 0, 0);
const diff = now.getTime() - start.getTime();
const oneDay = 1000 * 60 * 60 * 24;
const day = Math.floor(diff / oneDay);
return day;
}
| 20.094139 | 94 | 0.553434 | 485 | 31 | 0 | 35 | 50 | 13 | 8 | 0 | 9 | 4 | 2 | 9 | 3,596 | 0.018354 | 0.013904 | 0.003615 | 0.001112 | 0.000556 | 0 | 0.069767 | 0.262087 | export const Config = {
MaxLetters: 20,
TileCount: 6,
TileSize: 60,
TileSpacing: 10,
};
export enum Directions {
Up,
Left,
Down,
Right,
}
export enum CursorDirections {
LeftToRight = "left-to-right",
TopToBottom = "top-to-bottom",
}
type Cursor = {
row;
col;
direction;
};
export type Letter = {
id;
letter; // TODO: refactor to `char`
};
export enum TileState {
IDLE = "idle",
VALID = "valid",
INVALID = "invalid",
MIXED = "mixed",
}
export enum TileChangeReason {
MOVED = "moved",
LETTER = "letter",
}
export type Tile = {
id;
row;
col;
letter;
state;
changeReason;
};
export type Board = {
tiles;
cursor;
};
// https://en.wikipedia.org/wiki/Bananagrams#cite_note-7
const Letters = [
"J",
"K",
"Q",
"X",
"Z",
"J",
"K",
"Q",
"X",
"Z",
"B",
"C",
"F",
"H",
"M",
"P",
"V",
"W",
"Y",
"B",
"C",
"F",
"H",
"M",
"P",
"V",
"W",
"Y",
"B",
"C",
"F",
"H",
"M",
"P",
"V",
"W",
"Y",
"G",
"G",
"G",
"G",
"L",
"L",
"L",
"L",
"L",
"D",
"S",
"U",
"D",
"S",
"U",
"D",
"S",
"U",
"D",
"S",
"U",
"D",
"S",
"U",
"D",
"S",
"U",
"N",
"N",
"N",
"N",
"N",
"N",
"N",
"N",
"T",
"R",
"T",
"R",
"T",
"R",
"T",
"R",
"T",
"R",
"T",
"R",
"T",
"R",
"T",
"R",
"T",
"R",
"O",
"O",
"O",
"O",
"O",
"O",
"O",
"O",
"O",
"O",
"O",
"I",
"I",
"I",
"I",
"I",
"I",
"I",
"I",
"I",
"I",
"I",
"I",
"A",
"A",
"A",
"A",
"A",
"A",
"A",
"A",
"A",
"A",
"A",
"A",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
"E",
];
// @TODO use a seeded randomizer so we can get one combo per day.
/* Example usages of 'getRandom' are shown below:
getRandom(arr, arr.length);
getRandom(Letters, n);
*/
function getRandom<T>(arr, n) {
var result = new Array(n),
len = arr.length,
taken = new Array(len);
if (n > len) throw new RangeError("getRandom: more elements taken than available");
while (n--) {
var x = Math.floor(Math.random() * len);
result[n] = arr[x in taken ? taken[x] : x];
taken[x] = --len in taken ? taken[len] : len;
}
return result;
}
export function shuffle<T>(arr) {
return getRandom(arr, arr.length);
}
export function getRandomLetters(n) {
return getRandom(Letters, n);
}
export /* Example usages of 'wrapCursor' are shown below:
wrapCursor(board, {
row,
col: col + 1,
direction,
});
nextCursor = wrapCursor(board, {
row,
col: col + i,
direction,
});
wrapCursor(board, {
row: row + 1,
col,
direction,
});
nextCursor = wrapCursor(board, {
row: row + i,
col,
direction,
});
wrapCursor(board, {
row: board.cursor.row + 1,
col: board.cursor.col,
direction: board.cursor.direction,
});
wrapCursor(board, {
row: board.cursor.row - 1,
col: board.cursor.col,
direction: board.cursor.direction,
});
wrapCursor(board, {
row: board.cursor.row,
col: board.cursor.col - 1,
direction: board.cursor.direction,
});
wrapCursor(board, {
row: board.cursor.row,
col: board.cursor.col + 1,
direction: board.cursor.direction,
});
wrapCursor(board, {
row: cursor.row,
col: cursor.col - 1,
direction: cursor.direction,
});
wrapCursor(board, {
row: cursor.row - 1,
col: cursor.col,
direction: cursor.direction,
});
*/
function wrapCursor(board, cursor) {
const maxRow = board.tiles.length;
const maxCol = board.tiles[0].length;
const rowOverflow = Math.floor(cursor.row / maxRow);
const colOverflow = Math.floor(cursor.col / maxCol);
// Simple case, just bring back to reality.
if (rowOverflow && colOverflow) {
return {
row: cursor.row % maxRow,
col: cursor.col % maxCol,
direction: cursor.direction,
};
}
// If only the row is overflowing, increment as needed.
if (rowOverflow > 0) {
return {
row: cursor.row % maxRow,
col: (cursor.col + rowOverflow) % maxCol,
direction: cursor.direction,
};
}
// If only the col is overflowing, increment as needed.
if (colOverflow > 0) {
return {
row: (cursor.row + colOverflow) % maxRow,
col: (maxCol + cursor.col) % maxCol,
direction: cursor.direction,
};
}
// If only the row is underflowing, increment as needed.
if (rowOverflow < 0) {
return {
row: (maxRow + cursor.row) % maxRow,
col: (maxCol + cursor.col + rowOverflow) % maxCol,
direction: cursor.direction,
};
}
// If only the col is underflowing, increment as needed.
if (colOverflow < 0) {
return {
row: (maxRow + cursor.row + colOverflow) % maxRow,
col: (maxCol + cursor.col) % maxCol,
direction: cursor.direction,
};
}
return cursor;
}
export function incrementCursor(board) {
return moveBoardCursorToNextEmptyTile(board) || board.cursor;
}
/* Example usages of 'moveBoardCursorToNextEmptyTile' are shown below:
moveBoardCursorToNextEmptyTile(board) || board.cursor;
*/
function moveBoardCursorToNextEmptyTile(board) {
const { row, col, direction } = board.cursor;
switch (direction) {
case CursorDirections.LeftToRight: {
// If we're on a letter, always just move forward 1.
if (getTileAtCursor(board).letter) {
return wrapCursor(board, {
row,
col: col + 1,
direction,
});
}
// Otherwise, move to next empty square.
let nextCursor;
// Max 36 attempts. Kinda jank but guarentees no infinte loop.
for (let i = 1; i < 36; i++) {
nextCursor = wrapCursor(board, {
row,
col: col + i,
direction,
});
if (!getTileAtCursor(board, nextCursor).letter) {
return nextCursor;
}
}
return nextCursor;
}
case CursorDirections.TopToBottom: {
// If we're on a letter, always just move forward 1.
if (getTileAtCursor(board).letter) {
return wrapCursor(board, {
row: row + 1,
col,
direction,
});
}
// Otherwise, move to next empty square.
let nextCursor;
// Max 36 attempts. Kinda jank but guarentees no infinte loop.
for (let i = 1; i < 36; i++) {
nextCursor = wrapCursor(board, {
row: row + i,
col,
direction,
});
if (!getTileAtCursor(board, nextCursor).letter) {
return nextCursor;
}
}
return nextCursor;
}
}
}
export /* Example usages of 'getTileAtCursor' are shown below:
getTileAtCursor(board).letter;
!getTileAtCursor(board, nextCursor).letter;
*/
function getTileAtCursor(board, cursor?) {
const c = cursor || board.cursor;
return board.tiles[c.row][c.col];
}
export function updateCursorInDirection(board, direction) {
switch (direction) {
case Directions.Down:
return {
...board,
cursor: wrapCursor(board, {
row: board.cursor.row + 1,
col: board.cursor.col,
direction: board.cursor.direction,
}),
};
case Directions.Up:
return {
...board,
cursor: wrapCursor(board, {
row: board.cursor.row - 1,
col: board.cursor.col,
direction: board.cursor.direction,
}),
};
case Directions.Left:
return {
...board,
cursor: wrapCursor(board, {
row: board.cursor.row,
col: board.cursor.col - 1,
direction: board.cursor.direction,
}),
};
case Directions.Right:
return {
...board,
cursor: wrapCursor(board, {
row: board.cursor.row,
col: board.cursor.col + 1,
direction: board.cursor.direction,
}),
};
}
}
export function decrementCursor(board) {
const cursor = board.cursor;
switch (cursor.direction) {
case CursorDirections.LeftToRight:
return wrapCursor(board, {
row: cursor.row,
col: cursor.col - 1,
direction: cursor.direction,
});
case CursorDirections.TopToBottom:
return wrapCursor(board, {
row: cursor.row - 1,
col: cursor.col,
direction: cursor.direction,
});
}
}
/* Example usages of 'shiftBoardUp' are shown below:
shiftBoardUp(board);
*/
function shiftBoardUp(board) {
const topRow = board.tiles[0];
// Don't move board in this direction if it'd overflow.
if (topRow.some((tile) => tile.letter !== null)) {
return board;
}
const newLetterPositions = [...board.tiles.slice(1), topRow].map((row) =>
row.map((tile) => tile.letter),
);
const newTiles = board.tiles.slice();
for (let r = 0; r < board.tiles.length; r++) {
for (let c = 0; c < board.tiles[0].length; c++) {
newTiles[r][c] = {
...newTiles[r][c],
letter: newLetterPositions[r][c],
changeReason: TileChangeReason.MOVED,
};
}
}
return {
...board,
tiles: newTiles,
};
}
/* Example usages of 'shiftBoardDown' are shown below:
shiftBoardDown(board);
*/
function shiftBoardDown(board) {
const bottomRow = board.tiles[board.tiles.length - 1];
// Don't move board in this direction if it'd overflow.
if (bottomRow.some((tile) => tile.letter !== null)) {
return board;
}
const newLetterPositions = [bottomRow, ...board.tiles.slice(0, board.tiles.length - 1)].map(
(row) => row.map((tile) => tile.letter),
);
const newTiles = board.tiles.slice();
for (let r = 0; r < board.tiles.length; r++) {
for (let c = 0; c < board.tiles[0].length; c++) {
newTiles[r][c] = {
...newTiles[r][c],
letter: newLetterPositions[r][c],
changeReason: TileChangeReason.MOVED,
};
}
}
return {
...board,
tiles: newTiles,
};
}
/* Example usages of 'shiftBoardLeft' are shown below:
shiftBoardLeft(board);
*/
function shiftBoardLeft(board) {
const maxC = board.tiles[0].length;
const leftRow = board.tiles.map((row) => row[0]).flat();
// Don't move board in this direction if it'd overflow.
if (leftRow.some((tile) => tile.letter !== null)) {
return board;
}
const prevLetterPositions = board.tiles.map((row) => row.map((tile) => tile.letter));
const newLetterPositions = prevLetterPositions.map((_) => []) as (Letter | null)[][];
for (let r = 0; r < board.tiles.length; r++) {
for (let c = 0; c < board.tiles[0].length; c++) {
newLetterPositions[r][c] = prevLetterPositions[r][(maxC + c + 1) % maxC];
}
}
const newTiles = board.tiles.slice();
for (let r = 0; r < board.tiles.length; r++) {
for (let c = 0; c < board.tiles[0].length; c++) {
newTiles[r][c] = {
...newTiles[r][c],
letter: newLetterPositions[r][c],
changeReason: TileChangeReason.MOVED,
};
}
}
return {
...board,
tiles: newTiles,
};
}
/* Example usages of 'shiftBoardRight' are shown below:
shiftBoardRight(board);
*/
function shiftBoardRight(board) {
const maxC = board.tiles[0].length;
const rightRow = board.tiles.map((row) => row[row.length - 1]).flat();
// Don't move board in this direction if it'd overflow.
if (rightRow.some((tile) => tile.letter !== null)) {
return board;
}
const prevLetterPositions = board.tiles.map((row) => row.map((tile) => tile.letter));
const newLetterPositions = prevLetterPositions.map((_) => []) as (Letter | null)[][];
for (let r = 0; r < board.tiles.length; r++) {
for (let c = 0; c < board.tiles[0].length; c++) {
newLetterPositions[r][c] = prevLetterPositions[r][(maxC + c - 1) % maxC];
}
}
const newTiles = board.tiles.slice();
for (let r = 0; r < board.tiles.length; r++) {
for (let c = 0; c < board.tiles[0].length; c++) {
newTiles[r][c] = {
...newTiles[r][c],
letter: newLetterPositions[r][c],
changeReason: TileChangeReason.MOVED,
};
}
}
return {
...board,
tiles: newTiles,
};
}
export function moveBoard(board, direction) {
switch (direction) {
case Directions.Up:
return shiftBoardUp(board);
case Directions.Down:
return shiftBoardDown(board);
case Directions.Left:
return shiftBoardLeft(board);
case Directions.Right:
return shiftBoardRight(board);
}
}
export function getPuzzleNumber() {
const now = new Date();
const start = new Date(now.getFullYear(), 0, 0);
const diff = now.getTime() - start.getTime();
const oneDay = 1000 * 60 * 60 * 24;
const day = Math.floor(diff / oneDay);
return day;
}
|
4d568f231b2e1ee427398a5ede4616cdfb47140b | 1,954 | ts | TypeScript | source/common/annotations/create.ts | lindylearn/reader-extension | 49c1c4d769da4d5234e7a23988e981e5e7b28716 | [
"MIT"
] | 1 | 2022-03-14T11:45:29.000Z | 2022-03-14T11:45:29.000Z | source/common/annotations/create.ts | lindylearn/reader-extension | 49c1c4d769da4d5234e7a23988e981e5e7b28716 | [
"MIT"
] | null | null | null | source/common/annotations/create.ts | lindylearn/reader-extension | 49c1c4d769da4d5234e7a23988e981e5e7b28716 | [
"MIT"
] | null | null | null | export function createDraftAnnotation(url, selector): LindyAnnotation {
const id = `draft_${Math.random().toString(36).slice(-5)}`;
return {
id: id,
localId: id,
url,
quote_text: selector?.[2]?.exact || "_",
text: "",
author: { username: "" },
quote_html_selector: selector,
platform: "ll",
link: id,
reply_count: null,
is_draft: true,
isMyAnnotation: true,
isPublic: false,
upvote_count: 0,
tags: [],
created_at: new Date().toISOString(),
replies: [],
user_upvoted: false,
};
}
export interface LindyAnnotation {
id: string;
author: { username: string };
platform: "h" | "hn" | "ll";
link: string;
created_at: string;
reply_count: number;
quote_text: string;
text: string;
replies: LindyAnnotation[];
upvote_count: number;
tags: string[];
quote_html_selector: object;
user_upvoted: boolean;
isPublic: boolean;
// local state
is_draft?: boolean; // created highlight but not yet shown in sidebar
localId?: string; // local id until synced
url?: string;
isMyAnnotation?: boolean;
displayOffset?: number;
}
export function hypothesisToLindyFormat(annotation): LindyAnnotation {
return {
id: annotation.id,
author: annotation.user.match(/([^:]+)@/)[1],
platform: "h",
link: `https://hypothes.is/a/${annotation.id}`,
created_at: annotation.created,
reply_count: 0,
quote_text: annotation.target?.[0].selector?.filter(
(s) => s.type == "TextQuoteSelector"
)[0].exact,
text: annotation.text,
replies: [],
upvote_count: 0,
tags: annotation.tags,
quote_html_selector: annotation.target[0].selector,
user_upvoted: false,
isPublic: annotation.permissions.read[0] === "__world__",
};
}
| 28.318841 | 73 | 0.586489 | 64 | 3 | 0 | 4 | 1 | 19 | 0 | 0 | 17 | 1 | 0 | 13.333333 | 520 | 0.013462 | 0.001923 | 0.036538 | 0.001923 | 0 | 0 | 0.62963 | 0.210128 | export function createDraftAnnotation(url, selector) {
const id = `draft_${Math.random().toString(36).slice(-5)}`;
return {
id: id,
localId: id,
url,
quote_text: selector?.[2]?.exact || "_",
text: "",
author: { username: "" },
quote_html_selector: selector,
platform: "ll",
link: id,
reply_count: null,
is_draft: true,
isMyAnnotation: true,
isPublic: false,
upvote_count: 0,
tags: [],
created_at: new Date().toISOString(),
replies: [],
user_upvoted: false,
};
}
export interface LindyAnnotation {
id;
author;
platform;
link;
created_at;
reply_count;
quote_text;
text;
replies;
upvote_count;
tags;
quote_html_selector;
user_upvoted;
isPublic;
// local state
is_draft?; // created highlight but not yet shown in sidebar
localId?; // local id until synced
url?;
isMyAnnotation?;
displayOffset?;
}
export function hypothesisToLindyFormat(annotation) {
return {
id: annotation.id,
author: annotation.user.match(/([^:]+)@/)[1],
platform: "h",
link: `https://hypothes.is/a/${annotation.id}`,
created_at: annotation.created,
reply_count: 0,
quote_text: annotation.target?.[0].selector?.filter(
(s) => s.type == "TextQuoteSelector"
)[0].exact,
text: annotation.text,
replies: [],
upvote_count: 0,
tags: annotation.tags,
quote_html_selector: annotation.target[0].selector,
user_upvoted: false,
isPublic: annotation.permissions.read[0] === "__world__",
};
}
|
4ddd3014291215f3ada3100bd2e4719511b21daf | 1,193 | ts | TypeScript | packages/neuron-wallet/src/models/multisig-config.ts | Lester-xie/neuron | 33bb20311fdce1e99803104a48492b8863eadaba | [
"MIT"
] | null | null | null | packages/neuron-wallet/src/models/multisig-config.ts | Lester-xie/neuron | 33bb20311fdce1e99803104a48492b8863eadaba | [
"MIT"
] | null | null | null | packages/neuron-wallet/src/models/multisig-config.ts | Lester-xie/neuron | 33bb20311fdce1e99803104a48492b8863eadaba | [
"MIT"
] | 1 | 2022-03-24T04:58:50.000Z | 2022-03-24T04:58:50.000Z | export default class MultisigConfigModel {
public id?: number
public walletId: string
public m: number
public n: number
public r: number
public addresses: string[]
public alias?: string
public fullPayload: string
constructor(
walletId: string,
m: number,
n: number,
r: number,
addresses: string[],
fullPayload: string,
alias?: string,
id?: number
) {
this.walletId = walletId
this.m = m
this.n = n
this.r = r
this.addresses = addresses
this.fullPayload = fullPayload
this.alias = alias
this.id = id
}
public static fromObject(params: {
walletId: string
m: number
n: number
r: number
addresses: string[]
alias: string
fullPayload: string
id?: number
}): MultisigConfigModel {
return new MultisigConfigModel(
params.walletId,
params.m,
params.n,
params.r,
params.addresses,
params.fullPayload,
params.alias,
params.id
)
}
public toJson() {
return {
m: this.m,
n: this.n,
r: this.r,
addresses: this.addresses,
fullPayload: this.fullPayload,
alias: this.alias
}
}
}
| 18.640625 | 42 | 0.604359 | 60 | 3 | 0 | 9 | 0 | 8 | 0 | 0 | 24 | 1 | 0 | 8.666667 | 316 | 0.037975 | 0 | 0.025316 | 0.003165 | 0 | 0 | 1.2 | 0.262478 | export default class MultisigConfigModel {
public id?
public walletId
public m
public n
public r
public addresses
public alias?
public fullPayload
constructor(
walletId,
m,
n,
r,
addresses,
fullPayload,
alias?,
id?
) {
this.walletId = walletId
this.m = m
this.n = n
this.r = r
this.addresses = addresses
this.fullPayload = fullPayload
this.alias = alias
this.id = id
}
public static fromObject(params) {
return new MultisigConfigModel(
params.walletId,
params.m,
params.n,
params.r,
params.addresses,
params.fullPayload,
params.alias,
params.id
)
}
public toJson() {
return {
m: this.m,
n: this.n,
r: this.r,
addresses: this.addresses,
fullPayload: this.fullPayload,
alias: this.alias
}
}
}
|
afb5e034d9b820894fe0c664fed48b1195d19acd | 1,479 | ts | TypeScript | node_modules/@nomiclabs/hardhat-etherscan/src/ABITypes.ts | fkochan/opyn-vaults | a366bf03cc394f02c8daefcd604c3434a9d0e684 | [
"MIT"
] | 1 | 2022-03-29T17:43:15.000Z | 2022-03-29T17:43:15.000Z | node_modules/@nomiclabs/hardhat-etherscan/src/ABITypes.ts | fkochan/opyn-vaults | a366bf03cc394f02c8daefcd604c3434a9d0e684 | [
"MIT"
] | null | null | null | node_modules/@nomiclabs/hardhat-etherscan/src/ABITypes.ts | fkochan/opyn-vaults | a366bf03cc394f02c8daefcd604c3434a9d0e684 | [
"MIT"
] | null | null | null | export interface ABIArgumentLengthError extends Error {
code: "INVALID_ARGUMENT";
count: {
types: number;
values: number;
};
value: {
types: Array<{
name: string;
type: string;
}>;
values: any[];
};
reason: string;
}
export function isABIArgumentLengthError(
error: any
): error is ABIArgumentLengthError {
return (
error.code === "INVALID_ARGUMENT" &&
error.count &&
typeof error.count.types === "number" &&
typeof error.count.values === "number" &&
error.value &&
typeof error.value.types === "object" &&
typeof error.value.values === "object" &&
error instanceof Error
);
}
export interface ABIArgumentTypeError extends Error {
code: "INVALID_ARGUMENT";
argument: string;
value: any;
reason: string;
}
export function isABIArgumentTypeError(
error: any
): error is ABIArgumentTypeError {
return (
error.code === "INVALID_ARGUMENT" &&
typeof error.argument === "string" &&
"value" in error &&
error instanceof Error
);
}
export interface ABIArgumentOverflowError extends Error {
code: "NUMERIC_FAULT";
fault: "overflow";
value: any;
reason: string;
operation: string;
}
export function isABIArgumentOverflowError(
error: any
): error is ABIArgumentOverflowError {
return (
error.code === "NUMERIC_FAULT" &&
error.fault === "overflow" &&
typeof error.operation === "string" &&
"value" in error &&
error instanceof Error
);
}
| 21.434783 | 57 | 0.654496 | 63 | 3 | 0 | 3 | 0 | 13 | 0 | 6 | 9 | 3 | 9 | 7.666667 | 387 | 0.015504 | 0 | 0.033592 | 0.007752 | 0.023256 | 0.315789 | 0.473684 | 0.209677 | export interface ABIArgumentLengthError extends Error {
code;
count;
value;
reason;
}
export function isABIArgumentLengthError(
error
): error is ABIArgumentLengthError {
return (
error.code === "INVALID_ARGUMENT" &&
error.count &&
typeof error.count.types === "number" &&
typeof error.count.values === "number" &&
error.value &&
typeof error.value.types === "object" &&
typeof error.value.values === "object" &&
error instanceof Error
);
}
export interface ABIArgumentTypeError extends Error {
code;
argument;
value;
reason;
}
export function isABIArgumentTypeError(
error
): error is ABIArgumentTypeError {
return (
error.code === "INVALID_ARGUMENT" &&
typeof error.argument === "string" &&
"value" in error &&
error instanceof Error
);
}
export interface ABIArgumentOverflowError extends Error {
code;
fault;
value;
reason;
operation;
}
export function isABIArgumentOverflowError(
error
): error is ABIArgumentOverflowError {
return (
error.code === "NUMERIC_FAULT" &&
error.fault === "overflow" &&
typeof error.operation === "string" &&
"value" in error &&
error instanceof Error
);
}
|
0106ce5a314ca20db80f4d9df08bffd893e8b10d | 6,893 | ts | TypeScript | src/api/graphql/order.graphql.ts | joker-crypto/PUP-Facuty-Workload | 3840e2833c5f50fbdbf9b13ae6214fbb81e8c157 | [
"MIT"
] | null | null | null | src/api/graphql/order.graphql.ts | joker-crypto/PUP-Facuty-Workload | 3840e2833c5f50fbdbf9b13ae6214fbb81e8c157 | [
"MIT"
] | null | null | null | src/api/graphql/order.graphql.ts | joker-crypto/PUP-Facuty-Workload | 3840e2833c5f50fbdbf9b13ae6214fbb81e8c157 | [
"MIT"
] | 1 | 2022-02-12T02:16:15.000Z | 2022-02-12T02:16:15.000Z | /* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable import/prefer-default-export */
export const listPendingTransactionsGQL = () => {
return `
{
transactions(where: { status: "FOR_REVIEW" }) {
id
acctNo
trxnType
trxnRate
source
postedAt
exptGrossAmt
exptShares
addExcess
instructions {
id
}
fund {
id
description
}
account {
customer {
personal_info {
fullName
}
}
}
}
}
`;
};
export const listApprovedTransactionsGQL = () => {
return `
{
transactions(where: { status: "APPROVED" }) {
id
acctNo
trxnType
trxnRate
source
postedAt
approvedAt
exptGrossAmt
exptNetAmt
exptShares
trxnSubType
paymentMode
addExcess
instructions {
instruction
}
fund {
description
currency
acctSettlementNo
acctNo1
acctNo2
holdPeriod
exitRate
}
account {
currency
balance
excess
customer {
customerType
address {
addressLine
town_city
}
personal_info {
fullName
prefix
suffix
birthDate
mobile
email
}
}
}
}
}
`;
};
export const getPendingTransactionsGQL = (id: any) => {
return `
query {
transaction(id: ${id}) {
id
acctNo
paymentMode
postedAt
trxnRate
trxnType
trxnSubType
exptGrossAmt
exptShares
addBalance
addExcess
fund {
id
description
currency
}
instructions {
id
instruction
bankName
bankAcctNo
bankAcctName
repreName
repreContact
shares
fund {
id
description
}
}
account {
acctNo
customer {
id
customerType
personal_info {
fullName
occupation
}
financial_info {
annualIncome
}
professional_info {
position
}
}
}
}
}
`;
};
export const createSubscriptionGQL = (data: any) => {
return `
mutation {
createTransaction(
input: {
data: {
autoCompute: true
acctNo: "${data.acctNo}"
accountType: "${data.accountType}"
trxnType: SUBSCRIPTION
trxnSubType: ${data.trxnSubType}
customerId: ${data.customerId}
addBalance: 0
trxnRate: ${data.trxnRate}
fund: ${data.fund}
exptGrossAmt: ${data.exptGrossAmt}
paymentMode: "${data.paymentMode}"
status: FOR_REVIEW
source: REGISTRY
}
}
) {
transaction {
id
}
}
}
`;
};
export const createRedemptionGQL = (data: any) => {
return `
mutation {
createTransaction(
input: {
data: {
autoCompute: true
acctNo: "${data.acctNo}"
trxnType: REDEMPTION
trxnSubType: ${data.trxnSubType}
customerId: ${data.customerId}
fund: ${data.fund}
exptGrossAmt: ${data.exptGrossAmt}
status: FOR_REVIEW
source: REGISTRY
instructions: [
{
instruction: "${data.instruction}"
bankAcctName: "${data.bankAccountName || ''}"
bankAcctNo: "${data.bankAccountNumber || ''}"
bankName: "${data.bankName || ''}"
repreName: "${data.repreName || ''}"
repreContact: "${data.repreContact || ''}"
shares: ${data.exptGrossAmt}
}
]
}
}
) {
transaction {
id
}
}
}
`;
};
export const createFundSwitchGQL = (data: any) => {
return `
mutation {
createTransaction(
input: {
data: {
autoCompute: true
acctNo: "${data.acctNo}"
trxnType: REDEMPTION
trxnSubType: ${data.trxnSubType}
customerId: ${data.customerId}
fund: ${data.fund}
exptGrossAmt: ${data.exptGrossAmt}
status: FOR_REVIEW
source: REGISTRY
instructions: ${data.instructions}
}
}
) {
transaction {
id
}
}
}
`;
};
export const approvedSubscriptionGQL = (data: any) => {
return `
mutation {
updateTransaction(
input: {
where: { id: ${data.id} }
data: {
autoCompute: true
status: APPROVED
exptGrossAmt: ${data.exptGrossAmt}
fund: ${data.fundInfo}
trxnRate: ${data.trxnRate}
}
}
) {
transaction {
id
}
}
}
`;
};
export const approvedRedemptionGQL = (data: any) => {
return `
mutation {
updateTransaction(
input: {
where: { id: ${data.id} }
data: {
autoCompute: true
status: APPROVED
exptGrossAmt: ${data.exptGrossAmt}
trxnRate: ${data.trxnRate}
}
}
) {
transaction {
id
}
}
}
`;
};
export const matchedTransactionGQL = (data: any) => {
return `
mutation {
updateTransaction(
input: {
where: { id: ${data.id} }
data: {
autoCompute: true
status: MATCHED
actlNetAmt: ${data.actualNetAmt}
actlShares: ${data.actualNOS}
actlNav: ${data.navpu}
}
}
) {
transaction {
id
}
}
}
`;
};
export const archivedTransactionGQL = (data: any) => {
return `
mutation {
updateTransaction(
input: { where: { id: ${data.id} }, data: {
autoCompute: true ,status: ARCHIVED } }
) {
transaction {
id
}
}
}
`;
};
export const cancelledTransactionGQL = (id: any) => {
return `
mutation {
updateTransaction(
input: { where: { id: ${id} }, data: {
autoCompute: true, status: CANCELLED } }
) {
transaction {
id
}
}
}
`;
};
| 20.514881 | 61 | 0.440012 | 323 | 11 | 0 | 9 | 11 | 0 | 0 | 9 | 0 | 0 | 0 | 27.363636 | 1,540 | 0.012987 | 0.007143 | 0 | 0 | 0 | 0.290323 | 0 | 0.219228 | /* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable import/prefer-default-export */
export const listPendingTransactionsGQL = () => {
return `
{
transactions(where: { status: "FOR_REVIEW" }) {
id
acctNo
trxnType
trxnRate
source
postedAt
exptGrossAmt
exptShares
addExcess
instructions {
id
}
fund {
id
description
}
account {
customer {
personal_info {
fullName
}
}
}
}
}
`;
};
export const listApprovedTransactionsGQL = () => {
return `
{
transactions(where: { status: "APPROVED" }) {
id
acctNo
trxnType
trxnRate
source
postedAt
approvedAt
exptGrossAmt
exptNetAmt
exptShares
trxnSubType
paymentMode
addExcess
instructions {
instruction
}
fund {
description
currency
acctSettlementNo
acctNo1
acctNo2
holdPeriod
exitRate
}
account {
currency
balance
excess
customer {
customerType
address {
addressLine
town_city
}
personal_info {
fullName
prefix
suffix
birthDate
mobile
email
}
}
}
}
}
`;
};
export const getPendingTransactionsGQL = (id) => {
return `
query {
transaction(id: ${id}) {
id
acctNo
paymentMode
postedAt
trxnRate
trxnType
trxnSubType
exptGrossAmt
exptShares
addBalance
addExcess
fund {
id
description
currency
}
instructions {
id
instruction
bankName
bankAcctNo
bankAcctName
repreName
repreContact
shares
fund {
id
description
}
}
account {
acctNo
customer {
id
customerType
personal_info {
fullName
occupation
}
financial_info {
annualIncome
}
professional_info {
position
}
}
}
}
}
`;
};
export const createSubscriptionGQL = (data) => {
return `
mutation {
createTransaction(
input: {
data: {
autoCompute: true
acctNo: "${data.acctNo}"
accountType: "${data.accountType}"
trxnType: SUBSCRIPTION
trxnSubType: ${data.trxnSubType}
customerId: ${data.customerId}
addBalance: 0
trxnRate: ${data.trxnRate}
fund: ${data.fund}
exptGrossAmt: ${data.exptGrossAmt}
paymentMode: "${data.paymentMode}"
status: FOR_REVIEW
source: REGISTRY
}
}
) {
transaction {
id
}
}
}
`;
};
export const createRedemptionGQL = (data) => {
return `
mutation {
createTransaction(
input: {
data: {
autoCompute: true
acctNo: "${data.acctNo}"
trxnType: REDEMPTION
trxnSubType: ${data.trxnSubType}
customerId: ${data.customerId}
fund: ${data.fund}
exptGrossAmt: ${data.exptGrossAmt}
status: FOR_REVIEW
source: REGISTRY
instructions: [
{
instruction: "${data.instruction}"
bankAcctName: "${data.bankAccountName || ''}"
bankAcctNo: "${data.bankAccountNumber || ''}"
bankName: "${data.bankName || ''}"
repreName: "${data.repreName || ''}"
repreContact: "${data.repreContact || ''}"
shares: ${data.exptGrossAmt}
}
]
}
}
) {
transaction {
id
}
}
}
`;
};
export const createFundSwitchGQL = (data) => {
return `
mutation {
createTransaction(
input: {
data: {
autoCompute: true
acctNo: "${data.acctNo}"
trxnType: REDEMPTION
trxnSubType: ${data.trxnSubType}
customerId: ${data.customerId}
fund: ${data.fund}
exptGrossAmt: ${data.exptGrossAmt}
status: FOR_REVIEW
source: REGISTRY
instructions: ${data.instructions}
}
}
) {
transaction {
id
}
}
}
`;
};
export const approvedSubscriptionGQL = (data) => {
return `
mutation {
updateTransaction(
input: {
where: { id: ${data.id} }
data: {
autoCompute: true
status: APPROVED
exptGrossAmt: ${data.exptGrossAmt}
fund: ${data.fundInfo}
trxnRate: ${data.trxnRate}
}
}
) {
transaction {
id
}
}
}
`;
};
export const approvedRedemptionGQL = (data) => {
return `
mutation {
updateTransaction(
input: {
where: { id: ${data.id} }
data: {
autoCompute: true
status: APPROVED
exptGrossAmt: ${data.exptGrossAmt}
trxnRate: ${data.trxnRate}
}
}
) {
transaction {
id
}
}
}
`;
};
export const matchedTransactionGQL = (data) => {
return `
mutation {
updateTransaction(
input: {
where: { id: ${data.id} }
data: {
autoCompute: true
status: MATCHED
actlNetAmt: ${data.actualNetAmt}
actlShares: ${data.actualNOS}
actlNav: ${data.navpu}
}
}
) {
transaction {
id
}
}
}
`;
};
export const archivedTransactionGQL = (data) => {
return `
mutation {
updateTransaction(
input: { where: { id: ${data.id} }, data: {
autoCompute: true ,status: ARCHIVED } }
) {
transaction {
id
}
}
}
`;
};
export const cancelledTransactionGQL = (id) => {
return `
mutation {
updateTransaction(
input: { where: { id: ${id} }, data: {
autoCompute: true, status: CANCELLED } }
) {
transaction {
id
}
}
}
`;
};
|
0138e5c81327140dc5820e83db433171ce23fe75 | 1,937 | tsx | TypeScript | src/Map/mapboxStyles.tsx | jonathanengelbert/mapping-app-prototype-live-example | 90b4a93bda5ce5253bcc9c334dced14c8e79487b | [
"MIT"
] | null | null | null | src/Map/mapboxStyles.tsx | jonathanengelbert/mapping-app-prototype-live-example | 90b4a93bda5ce5253bcc9c334dced14c8e79487b | [
"MIT"
] | 1 | 2022-02-10T22:43:19.000Z | 2022-02-10T22:43:19.000Z | src/Map/mapboxStyles.tsx | jonathanengelbert/mapping-app-prototype-live-example | 90b4a93bda5ce5253bcc9c334dced14c8e79487b | [
"MIT"
] | null | null | null | // TODO: darkStyle will be deprecated June 1st. Create a custom style for it
// base styles
const darkStyle = 'mapbox://styles/mapbox/dark-v10';
const customStyle = 'mapbox://styles/jonathanengelbert/ck5egnrfz06cu1iq8x7hyy4uy';
const streetsBasic = 'mapbox://styles/jonathanengelbert/ckc3lta3b0z281io3tl7vmk6i';
// layer styles
// TODO: add active color argument
class PointStyle {
private readonly color: string;
private readonly baseRadius: number;
constructor(color?: string, baseRadius?: number) {
this.color = color || "white";
this.baseRadius = baseRadius || 1.75;
}
generateStyle() {
return {
// [zoomLevel, circleDiameter]
"circle-radius": {
"base": this.baseRadius,
"stops": [
[12, 2],
[16, 15],
[22, 30]
]
},
"circle-color": [
"case",
['boolean', ['feature-state', 'hover'], false],
'blue',
this.color,
]
}
}
}
class PolygonStyle {
private readonly fillColor: string;
private readonly fillOutlineColor: string;
private readonly fillOpacity: number;
constructor(fillColor?: string, fillOpacity?: number, fillOutlineColor?: string) {
this.fillColor = fillColor || "black";
this.fillOutlineColor = fillOutlineColor || 'black';
this.fillOpacity = fillOpacity || 0.5;
}
generateStyle() {
return {
"fill-color": this.fillColor,
"fill-opacity": this.fillOpacity,
"fill-outline-color": this.fillOutlineColor,
}
}
}
export const mapboxStyles = {
// baseStyles
darkStyle: darkStyle,
customStyle: customStyle,
streetsBasic: streetsBasic,
// layerStyles
pointStyle: PointStyle,
polygonStyle: PolygonStyle,
};
| 27.28169 | 86 | 0.577697 | 53 | 4 | 0 | 5 | 4 | 5 | 0 | 0 | 10 | 2 | 0 | 6.5 | 492 | 0.018293 | 0.00813 | 0.010163 | 0.004065 | 0 | 0 | 0.555556 | 0.245242 | // TODO: darkStyle will be deprecated June 1st. Create a custom style for it
// base styles
const darkStyle = 'mapbox://styles/mapbox/dark-v10';
const customStyle = 'mapbox://styles/jonathanengelbert/ck5egnrfz06cu1iq8x7hyy4uy';
const streetsBasic = 'mapbox://styles/jonathanengelbert/ckc3lta3b0z281io3tl7vmk6i';
// layer styles
// TODO: add active color argument
class PointStyle {
private readonly color;
private readonly baseRadius;
constructor(color?, baseRadius?) {
this.color = color || "white";
this.baseRadius = baseRadius || 1.75;
}
generateStyle() {
return {
// [zoomLevel, circleDiameter]
"circle-radius": {
"base": this.baseRadius,
"stops": [
[12, 2],
[16, 15],
[22, 30]
]
},
"circle-color": [
"case",
['boolean', ['feature-state', 'hover'], false],
'blue',
this.color,
]
}
}
}
class PolygonStyle {
private readonly fillColor;
private readonly fillOutlineColor;
private readonly fillOpacity;
constructor(fillColor?, fillOpacity?, fillOutlineColor?) {
this.fillColor = fillColor || "black";
this.fillOutlineColor = fillOutlineColor || 'black';
this.fillOpacity = fillOpacity || 0.5;
}
generateStyle() {
return {
"fill-color": this.fillColor,
"fill-opacity": this.fillOpacity,
"fill-outline-color": this.fillOutlineColor,
}
}
}
export const mapboxStyles = {
// baseStyles
darkStyle: darkStyle,
customStyle: customStyle,
streetsBasic: streetsBasic,
// layerStyles
pointStyle: PointStyle,
polygonStyle: PolygonStyle,
};
|
01bc21618f923031d35fb26e14362ce81746c2c0 | 3,461 | ts | TypeScript | Converge/ClientApp/src/utilities/CachedQuery.ts | microsoft/mwcci-converge | 0fe01a69b9537f4d87017c248b576048f3ec5a63 | [
"MIT"
] | 5 | 2022-01-20T15:37:34.000Z | 2022-02-09T17:50:18.000Z | Converge/ClientApp/src/utilities/CachedQuery.ts | microsoft/mwcci-converge | 0fe01a69b9537f4d87017c248b576048f3ec5a63 | [
"MIT"
] | null | null | null | Converge/ClientApp/src/utilities/CachedQuery.ts | microsoft/mwcci-converge | 0fe01a69b9537f4d87017c248b576048f3ec5a63 | [
"MIT"
] | 1 | 2022-03-02T15:59:45.000Z | 2022-03-02T15:59:45.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export interface CachedQuery<T, P = void> {
getItems: (searchStrings: string[], params: P) => Promise<T[]>,
forceUpdate: (missedKeys: string[], params: P) => Promise<T[]>;
}
/**
* Returns a function that will first search a cache for results
* and then use the given function to find the remaining items
*
* @param generateStoreKey function used to generate the key used to store a new item.
* @param generateRetrievalKey function used to generate the key used to retrieve an item later.
* @param findMisses function called with items not found in the cache.
* @param initialCache Optional structure used to provide initial values in the cache.
* @returns function that searches cache before calling findMisses for remaining values.
*/
function createCachedQuery<T, P = void>(
generateStoreKey: (item: T, params: P) => string,
generateRetrievalKey: (search: string, params: P) => string,
findMisses: (replacedKeys: string[], params: P) => Promise<T[]>,
initialCache?: Record<T[keyof T] & string, T>,
): CachedQuery<T, P> {
const cache: Record<string, T> = { ...initialCache } ?? {};
function addItemsToCache(items: T[], params: P) {
items.forEach((item) => {
const itemKey = generateStoreKey(item, params);
cache[itemKey] = item;
});
}
/**
* function used to retrieve items from cache.
*
* @param searchStrings strings used to generate retrievalKey (usually item's unique identifier)
* @param params custom params shared between searched items (date, location, etc)
* @returns array where first index is found items and second index is cache misses
*/
function getItemsFromCache(searchStrings: string[], params: P): [T[], string[]] {
const cacheHits: T[] = [];
const cacheMisses: string[] = [];
searchStrings.forEach((search) => {
const retrievalKey = generateRetrievalKey(search, params);
if (cache[retrievalKey]) {
cacheHits.push(cache[retrievalKey]);
} else {
cacheMisses.push(search);
}
});
return [
cacheHits,
cacheMisses,
];
}
/**
* Function used to retrieve items and update the cache.
*
* @param searchStrings strings used in searching and to generate keys
* @param params custom params shared between searched items (date, location, etc)
* @returns Returns items using findMisses functions after caching them.
*/
async function updateItems(missedKeys: string[], params: P) {
const retrievedItems = await findMisses(missedKeys, params);
// Add the new items to the cache.
addItemsToCache(retrievedItems, params);
return retrievedItems;
}
/**
* Function used to retrieve items from cache and return any misses
* using findMisses function.
*
* @param searchStrings strings used to generate retrievalKey (usually item's unique identifier)
* @param params custom params shared between searched items (date, location, etc)
* @returns Array of items of type T
*/
async function getItems(searchStrings: string[], params: P) {
const [cacheHits, cacheMisses] = getItemsFromCache(searchStrings, params);
const retrievedItems = cacheMisses.length > 0 ? await updateItems(cacheMisses, params) : [];
return [
...cacheHits,
...retrievedItems,
];
}
return {
getItems,
forceUpdate: updateItems,
};
}
export default createCachedQuery;
| 34.267327 | 98 | 0.690552 | 52 | 7 | 0 | 14 | 8 | 2 | 3 | 0 | 15 | 1 | 0 | 10.714286 | 847 | 0.024793 | 0.009445 | 0.002361 | 0.001181 | 0 | 0 | 0.483871 | 0.260981 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export interface CachedQuery<T, P = void> {
getItems,
forceUpdate;
}
/**
* Returns a function that will first search a cache for results
* and then use the given function to find the remaining items
*
* @param generateStoreKey function used to generate the key used to store a new item.
* @param generateRetrievalKey function used to generate the key used to retrieve an item later.
* @param findMisses function called with items not found in the cache.
* @param initialCache Optional structure used to provide initial values in the cache.
* @returns function that searches cache before calling findMisses for remaining values.
*/
/* Example usages of 'createCachedQuery' are shown below:
;
*/
function createCachedQuery<T, P = void>(
generateStoreKey,
generateRetrievalKey,
findMisses,
initialCache?,
) {
const cache = { ...initialCache } ?? {};
/* Example usages of 'addItemsToCache' are shown below:
// Add the new items to the cache.
addItemsToCache(retrievedItems, params);
*/
function addItemsToCache(items, params) {
items.forEach((item) => {
const itemKey = generateStoreKey(item, params);
cache[itemKey] = item;
});
}
/**
* function used to retrieve items from cache.
*
* @param searchStrings strings used to generate retrievalKey (usually item's unique identifier)
* @param params custom params shared between searched items (date, location, etc)
* @returns array where first index is found items and second index is cache misses
*/
/* Example usages of 'getItemsFromCache' are shown below:
getItemsFromCache(searchStrings, params);
*/
function getItemsFromCache(searchStrings, params) {
const cacheHits = [];
const cacheMisses = [];
searchStrings.forEach((search) => {
const retrievalKey = generateRetrievalKey(search, params);
if (cache[retrievalKey]) {
cacheHits.push(cache[retrievalKey]);
} else {
cacheMisses.push(search);
}
});
return [
cacheHits,
cacheMisses,
];
}
/**
* Function used to retrieve items and update the cache.
*
* @param searchStrings strings used in searching and to generate keys
* @param params custom params shared between searched items (date, location, etc)
* @returns Returns items using findMisses functions after caching them.
*/
/* Example usages of 'updateItems' are shown below:
updateItems(cacheMisses, params);
;
*/
async function updateItems(missedKeys, params) {
const retrievedItems = await findMisses(missedKeys, params);
// Add the new items to the cache.
addItemsToCache(retrievedItems, params);
return retrievedItems;
}
/**
* Function used to retrieve items from cache and return any misses
* using findMisses function.
*
* @param searchStrings strings used to generate retrievalKey (usually item's unique identifier)
* @param params custom params shared between searched items (date, location, etc)
* @returns Array of items of type T
*/
/* Example usages of 'getItems' are shown below:
;
*/
async function getItems(searchStrings, params) {
const [cacheHits, cacheMisses] = getItemsFromCache(searchStrings, params);
const retrievedItems = cacheMisses.length > 0 ? await updateItems(cacheMisses, params) : [];
return [
...cacheHits,
...retrievedItems,
];
}
return {
getItems,
forceUpdate: updateItems,
};
}
export default createCachedQuery;
|
01d0e4018fcb47e28400e63c0da2b24efc24074e | 2,705 | ts | TypeScript | src/@sejasa/utils/index.ts | alidihaw/sejasa | e33433ff4c90149cd71f7cfedceb2ab9628c3e68 | [
"MIT"
] | null | null | null | src/@sejasa/utils/index.ts | alidihaw/sejasa | e33433ff4c90149cd71f7cfedceb2ab9628c3e68 | [
"MIT"
] | 1 | 2022-03-02T07:39:34.000Z | 2022-03-02T07:39:34.000Z | src/@sejasa/utils/index.ts | alidihaw/sejasa | e33433ff4c90149cd71f7cfedceb2ab9628c3e68 | [
"MIT"
] | null | null | null | export class Utils
{
/**
* Filter array by string
*
* @param mainArr
* @param searchText
* @returns {any}
*/
public static filterArrayByString(mainArr, searchText): any
{
if ( searchText === '' )
{
return mainArr;
}
searchText = searchText.toLowerCase();
return mainArr.filter(itemObj => {
return this.searchInObj(itemObj, searchText);
});
}
/**
* Search in object
*
* @param itemObj
* @param searchText
* @returns {boolean}
*/
public static searchInObj(itemObj, searchText): boolean
{
for ( const prop in itemObj )
{
if ( !itemObj.hasOwnProperty(prop) )
{
continue;
}
const value = itemObj[prop];
if ( typeof value === 'string' )
{
if ( this.searchInString(value, searchText) )
{
return true;
}
}
else if ( Array.isArray(value) )
{
if ( this.searchInArray(value, searchText) )
{
return true;
}
}
if ( typeof value === 'object' )
{
if ( this.searchInObj(value, searchText) )
{
return true;
}
}
}
}
/**
* Search in array
*
* @param arr
* @param searchText
* @returns {boolean}
*/
public static searchInArray(arr, searchText): boolean
{
for ( const value of arr )
{
if ( typeof value === 'string' )
{
if ( this.searchInString(value, searchText) )
{
return true;
}
}
if ( typeof value === 'object' )
{
if ( this.searchInObj(value, searchText) )
{
return true;
}
}
}
}
/**
* Search in string
*
* @param value
* @param searchText
* @returns {any}
*/
public static searchInString(value, searchText): any
{
return value.toLowerCase().includes(searchText);
}
/**
* Generate a unique GUID
*
* @returns {string}
*/
public static generateGUID(): string
{
function S4(): string
{
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return S4() + S4();
}
} | 21.64 | 63 | 0.416266 | 80 | 7 | 0 | 9 | 1 | 0 | 4 | 2 | 4 | 1 | 4 | 9.428571 | 583 | 0.027444 | 0.001715 | 0 | 0.001715 | 0.006861 | 0.117647 | 0.235294 | 0.240451 | export class Utils
{
/**
* Filter array by string
*
* @param mainArr
* @param searchText
* @returns {any}
*/
public static filterArrayByString(mainArr, searchText)
{
if ( searchText === '' )
{
return mainArr;
}
searchText = searchText.toLowerCase();
return mainArr.filter(itemObj => {
return this.searchInObj(itemObj, searchText);
});
}
/**
* Search in object
*
* @param itemObj
* @param searchText
* @returns {boolean}
*/
public static searchInObj(itemObj, searchText)
{
for ( const prop in itemObj )
{
if ( !itemObj.hasOwnProperty(prop) )
{
continue;
}
const value = itemObj[prop];
if ( typeof value === 'string' )
{
if ( this.searchInString(value, searchText) )
{
return true;
}
}
else if ( Array.isArray(value) )
{
if ( this.searchInArray(value, searchText) )
{
return true;
}
}
if ( typeof value === 'object' )
{
if ( this.searchInObj(value, searchText) )
{
return true;
}
}
}
}
/**
* Search in array
*
* @param arr
* @param searchText
* @returns {boolean}
*/
public static searchInArray(arr, searchText)
{
for ( const value of arr )
{
if ( typeof value === 'string' )
{
if ( this.searchInString(value, searchText) )
{
return true;
}
}
if ( typeof value === 'object' )
{
if ( this.searchInObj(value, searchText) )
{
return true;
}
}
}
}
/**
* Search in string
*
* @param value
* @param searchText
* @returns {any}
*/
public static searchInString(value, searchText)
{
return value.toLowerCase().includes(searchText);
}
/**
* Generate a unique GUID
*
* @returns {string}
*/
public static generateGUID()
{
/* Example usages of 'S4' are shown below:
S4() + S4();
*/
function S4()
{
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return S4() + S4();
}
} |
7a1b87b7a7dc254ffa57c397521006c2f580a43a | 2,302 | ts | TypeScript | imports/lib/relativeTimeFormat.ts | ebroder/jolly-roger | b2c0a6fc99d4e3237b68993dc113c87a2cc97c04 | [
"MIT"
] | null | null | null | imports/lib/relativeTimeFormat.ts | ebroder/jolly-roger | b2c0a6fc99d4e3237b68993dc113c87a2cc97c04 | [
"MIT"
] | 38 | 2022-01-22T00:50:01.000Z | 2022-03-29T00:55:54.000Z | imports/lib/relativeTimeFormat.ts | ebroder/jolly-roger | b2c0a6fc99d4e3237b68993dc113c87a2cc97c04 | [
"MIT"
] | null | null | null | /* eslint-disable object-curly-newline */
const timeUnits = [
{ millis: 1000, singular: 'second', plural: 'seconds', terse: 's' },
{ millis: 60 * 1000, singular: 'minute', plural: 'minutes', terse: 'm' },
{ millis: 60 * 60 * 1000, singular: 'hour', plural: 'hours', terse: 'h' },
{ millis: 24 * 60 * 60 * 1000, singular: 'day', plural: 'days', terse: 'd' },
{ millis: 365 * 24 * 60 * 60 * 1000, singular: 'year', plural: 'years', terse: 'y' },
].reverse();
/* eslint-enable object-curly-newline */
export function terseRelativeTimeFormat(d: Date, opts: {
minimumUnit?: 'second' | 'minute' | 'hour' | 'day' | 'year',
maxElements?: number
now?: Date,
} = {}) {
const {
minimumUnit = 'seconds',
maxElements = -1,
now = new Date(),
} = opts;
const diff = now.getTime() - d.getTime();
let remainder = Math.abs(diff);
const terms = [] as string[];
let stop = false;
timeUnits.forEach(({ millis, singular, terse }) => {
if (stop) {
return;
}
const count = Math.floor(remainder / millis);
if (count > 0) {
terms.push(`${count}${terse}`);
}
remainder %= millis;
if (minimumUnit === singular) {
stop = true;
}
if (maxElements > 0 && terms.length >= maxElements) {
stop = true;
}
});
if (terms.length === 0) {
return 'now';
}
return terms.join('');
}
export default function relativeTimeFormat(d: Date, opts: {
complete?: boolean,
minimumUnit?: 'second' | 'minute' | 'hour' | 'day' | 'year',
now?: Date,
} = {}) {
const {
complete = false,
minimumUnit = 'seconds',
now = new Date(),
} = opts;
const diff = now.getTime() - d.getTime();
const relative = diff < 0 ? ' from now' : ' ago';
let remainder = Math.abs(diff);
const terms = [] as string[];
let stop = false;
timeUnits.forEach(({ millis, singular, plural }) => {
if (stop) {
return;
}
const count = Math.floor(remainder / millis);
if (count > 0) {
terms.push(`${count} ${count === 1 ? singular : plural}`);
}
remainder %= millis;
if (minimumUnit === singular) {
stop = true;
}
});
if (terms.length === 0) {
return 'just now';
}
if (complete) {
return `${terms.join(', ')}${relative}`;
}
return `${terms[0]}${relative}`;
}
| 24.489362 | 87 | 0.556473 | 78 | 4 | 0 | 6 | 14 | 0 | 0 | 0 | 4 | 0 | 2 | 21 | 735 | 0.013605 | 0.019048 | 0 | 0 | 0.002721 | 0 | 0.166667 | 0.263544 | /* eslint-disable object-curly-newline */
const timeUnits = [
{ millis: 1000, singular: 'second', plural: 'seconds', terse: 's' },
{ millis: 60 * 1000, singular: 'minute', plural: 'minutes', terse: 'm' },
{ millis: 60 * 60 * 1000, singular: 'hour', plural: 'hours', terse: 'h' },
{ millis: 24 * 60 * 60 * 1000, singular: 'day', plural: 'days', terse: 'd' },
{ millis: 365 * 24 * 60 * 60 * 1000, singular: 'year', plural: 'years', terse: 'y' },
].reverse();
/* eslint-enable object-curly-newline */
export function terseRelativeTimeFormat(d, opts = {}) {
const {
minimumUnit = 'seconds',
maxElements = -1,
now = new Date(),
} = opts;
const diff = now.getTime() - d.getTime();
let remainder = Math.abs(diff);
const terms = [] as string[];
let stop = false;
timeUnits.forEach(({ millis, singular, terse }) => {
if (stop) {
return;
}
const count = Math.floor(remainder / millis);
if (count > 0) {
terms.push(`${count}${terse}`);
}
remainder %= millis;
if (minimumUnit === singular) {
stop = true;
}
if (maxElements > 0 && terms.length >= maxElements) {
stop = true;
}
});
if (terms.length === 0) {
return 'now';
}
return terms.join('');
}
export default function relativeTimeFormat(d, opts = {}) {
const {
complete = false,
minimumUnit = 'seconds',
now = new Date(),
} = opts;
const diff = now.getTime() - d.getTime();
const relative = diff < 0 ? ' from now' : ' ago';
let remainder = Math.abs(diff);
const terms = [] as string[];
let stop = false;
timeUnits.forEach(({ millis, singular, plural }) => {
if (stop) {
return;
}
const count = Math.floor(remainder / millis);
if (count > 0) {
terms.push(`${count} ${count === 1 ? singular : plural}`);
}
remainder %= millis;
if (minimumUnit === singular) {
stop = true;
}
});
if (terms.length === 0) {
return 'just now';
}
if (complete) {
return `${terms.join(', ')}${relative}`;
}
return `${terms[0]}${relative}`;
}
|
7a40ffcd76ed6564a5937aaf43b49f671a35f9dc | 3,792 | ts | TypeScript | frontend/src/components/IndexPage/Contact/ValidateInputs.ts | DinosDev/Nystron | 85093d9705c8c0ceed9082534a1d211294d91fc9 | [
"MIT"
] | null | null | null | frontend/src/components/IndexPage/Contact/ValidateInputs.ts | DinosDev/Nystron | 85093d9705c8c0ceed9082534a1d211294d91fc9 | [
"MIT"
] | 6 | 2022-02-26T05:04:46.000Z | 2022-03-23T01:46:52.000Z | frontend/src/components/IndexPage/Contact/ValidateInputs.ts | DinosDev/Nystron | 85093d9705c8c0ceed9082534a1d211294d91fc9 | [
"MIT"
] | 1 | 2022-03-31T00:47:56.000Z | 2022-03-31T00:47:56.000Z | const Errors = [
{
Title: "Name",
Text: {
MinLength: "O Nome - Mínimo 3 caracteres",
MaxLength: "O Nome - Máximo 50 caracteres"
},
Validation: {
MinLength: 3,
MaxLength: 50
}
}, {
Title: "LastName",
Text: {
MinLength: "O Sobrenome - Mínimo 5 caracteres",
MaxLength: "O Sobrenome - Máximo 100 caracteres"
},
Validation: {
MinLength: 5,
MaxLength: 100
}
}, {
Title: "Telephone",
Text: {
MinLength: "O Telefone deve manter os seguintes formatos: +55 (55) xxxxx - xxxx ou +598 xxxxx - xxxx",
MaxLength: "O Telefone deve manter os seguintes formatos: +55 (55) xxxxx - xxxx ou +598 xxxxx - xxxx",
Format: "O Telefone deve manter os seguintes formatos: +55 (55) xxxxx - xxxx ou +598 xxxxx - xxxx"
},
Validation: {
MinLength: 17,
MaxLength: 21,
Format: "\\+([0-9]{2,3})((\\s\\([0-9]{2}\\)\\s)|(\\s))([0-9]{4,5})\\s-\\s([0-9]{4})$"
}
}, {
Title: "Email",
Text: {
MinLength: "O Email - Mínimo 3 caracteres",
MaxLength: "O Email - Máximo 100 caracteres"
},
Validation: {
MinLength: 3,
MaxLength: 100
}
}, {
Title: "Message",
Text: {
MinLength: "A Mensagem - Mínimo 3 caracteres",
MaxLength: "A Mensagem - Máximo 1000 caracteres"
},
Validation: {
MinLength: 3,
MaxLength: 1000
}
}
]
function Length(str: any) { return str.length }
function FirstLetterLowerCase(str: any) {
return str.charAt(0).toLowerCase() + str.slice(1);
}
function CheckMinLength(Error: any, Input: any) {
const MinLength = Error.Validation.MinLength
const ActualLength = Length(Input)
const Check = ActualLength < MinLength
if (Check) {
const MinLengthText = Error.Text.MinLength
return {
Error: true,
Text: MinLengthText
}
}
return { Error: false, }
}
function CheckMaxLength(Error: any, Input: any) {
const MaxLength = Error.Validation.MaxLength
const ActualLength = Length(Input)
const Check = ActualLength > MaxLength
if (Check) {
const MaxLengthText = Error.Text.MaxLength
return {
Error: true,
Text: MaxLengthText
}
}
return { Error: false, }
}
function CheckTelephone(Error: any, Input: any) {
const TelephoneFormat = Error.Validation.Format
const Telephone = Input
const Regex = new RegExp(TelephoneFormat)
const Check = Regex.test(Telephone)
if (Check) { return { Error: false } }
else { return { Error: true, Text: Error.Text.Format } }
}
export default function ValidateInputs(Inputs: any) {
var ValueToReturn: any;
Errors.every((Error: any) => {
const ErrorTitle = Error.Title
const Input = Inputs[FirstLetterLowerCase(ErrorTitle)]
const MinLength = CheckMinLength(Error, Input)
const MaxLength = CheckMaxLength(Error, Input)
if (MinLength.Error) {
ValueToReturn = MinLength.Text
return false
}
else if (MaxLength.Error) {
ValueToReturn = MaxLength.Text
return false
}
else if (Error.Title == "Telephone") {
const Telephone = CheckTelephone(Error, Input)
if (Telephone.Error) {
ValueToReturn = Telephone.Text
}
return Telephone.Error ? false : true
} else { ValueToReturn = true }
return true
})
return ValueToReturn
} | 25.972603 | 114 | 0.545886 | 119 | 7 | 0 | 10 | 19 | 0 | 5 | 11 | 0 | 0 | 0 | 10.571429 | 1,035 | 0.016425 | 0.018357 | 0 | 0 | 0 | 0.305556 | 0 | 0.264884 | const Errors = [
{
Title: "Name",
Text: {
MinLength: "O Nome - Mínimo 3 caracteres",
MaxLength: "O Nome - Máximo 50 caracteres"
},
Validation: {
MinLength: 3,
MaxLength: 50
}
}, {
Title: "LastName",
Text: {
MinLength: "O Sobrenome - Mínimo 5 caracteres",
MaxLength: "O Sobrenome - Máximo 100 caracteres"
},
Validation: {
MinLength: 5,
MaxLength: 100
}
}, {
Title: "Telephone",
Text: {
MinLength: "O Telefone deve manter os seguintes formatos: +55 (55) xxxxx - xxxx ou +598 xxxxx - xxxx",
MaxLength: "O Telefone deve manter os seguintes formatos: +55 (55) xxxxx - xxxx ou +598 xxxxx - xxxx",
Format: "O Telefone deve manter os seguintes formatos: +55 (55) xxxxx - xxxx ou +598 xxxxx - xxxx"
},
Validation: {
MinLength: 17,
MaxLength: 21,
Format: "\\+([0-9]{2,3})((\\s\\([0-9]{2}\\)\\s)|(\\s))([0-9]{4,5})\\s-\\s([0-9]{4})$"
}
}, {
Title: "Email",
Text: {
MinLength: "O Email - Mínimo 3 caracteres",
MaxLength: "O Email - Máximo 100 caracteres"
},
Validation: {
MinLength: 3,
MaxLength: 100
}
}, {
Title: "Message",
Text: {
MinLength: "A Mensagem - Mínimo 3 caracteres",
MaxLength: "A Mensagem - Máximo 1000 caracteres"
},
Validation: {
MinLength: 3,
MaxLength: 1000
}
}
]
/* Example usages of 'Length' are shown below:
Length(Input);
*/
function Length(str) { return str.length }
/* Example usages of 'FirstLetterLowerCase' are shown below:
Inputs[FirstLetterLowerCase(ErrorTitle)];
*/
function FirstLetterLowerCase(str) {
return str.charAt(0).toLowerCase() + str.slice(1);
}
/* Example usages of 'CheckMinLength' are shown below:
CheckMinLength(Error, Input);
*/
function CheckMinLength(Error, Input) {
const MinLength = Error.Validation.MinLength
const ActualLength = Length(Input)
const Check = ActualLength < MinLength
if (Check) {
const MinLengthText = Error.Text.MinLength
return {
Error: true,
Text: MinLengthText
}
}
return { Error: false, }
}
/* Example usages of 'CheckMaxLength' are shown below:
CheckMaxLength(Error, Input);
*/
function CheckMaxLength(Error, Input) {
const MaxLength = Error.Validation.MaxLength
const ActualLength = Length(Input)
const Check = ActualLength > MaxLength
if (Check) {
const MaxLengthText = Error.Text.MaxLength
return {
Error: true,
Text: MaxLengthText
}
}
return { Error: false, }
}
/* Example usages of 'CheckTelephone' are shown below:
CheckTelephone(Error, Input);
*/
function CheckTelephone(Error, Input) {
const TelephoneFormat = Error.Validation.Format
const Telephone = Input
const Regex = new RegExp(TelephoneFormat)
const Check = Regex.test(Telephone)
if (Check) { return { Error: false } }
else { return { Error: true, Text: Error.Text.Format } }
}
export default function ValidateInputs(Inputs) {
var ValueToReturn;
Errors.every((Error) => {
const ErrorTitle = Error.Title
const Input = Inputs[FirstLetterLowerCase(ErrorTitle)]
const MinLength = CheckMinLength(Error, Input)
const MaxLength = CheckMaxLength(Error, Input)
if (MinLength.Error) {
ValueToReturn = MinLength.Text
return false
}
else if (MaxLength.Error) {
ValueToReturn = MaxLength.Text
return false
}
else if (Error.Title == "Telephone") {
const Telephone = CheckTelephone(Error, Input)
if (Telephone.Error) {
ValueToReturn = Telephone.Text
}
return Telephone.Error ? false : true
} else { ValueToReturn = true }
return true
})
return ValueToReturn
} |
7acebb8448be9dfe264aa733096caf95bd007297 | 2,668 | ts | TypeScript | json-form-core/src/core/JsonForm.ts | dustlight-cn/quasar-json-form | 9f58a31de03d90b3f25b34db6cf311cb71958b5a | [
"MIT"
] | 1 | 2022-02-27T12:09:37.000Z | 2022-02-27T12:09:37.000Z | json-form-core/src/core/JsonForm.ts | dustlight-cn/quasar-json-form | 9f58a31de03d90b3f25b34db6cf311cb71958b5a | [
"MIT"
] | null | null | null | json-form-core/src/core/JsonForm.ts | dustlight-cn/quasar-json-form | 9f58a31de03d90b3f25b34db6cf311cb71958b5a | [
"MIT"
] | null | null | null | // @ts-nocheck
class JsonForm {
private schema: object
private additional: object
private data: object
private constructor(schema: object, data?: object | null, additional?: object | null) {
this.schema = schema
this.data = data
this.additional = additional
}
public tree(name) {
return this.listTree(this.schema, name)
}
protected listTree(schema, name) {
if (schema.type == "object") {
let children = []
for (let key in schema.properties) {
children.push(this.listTree(schema.properties[key], key))
}
return {
name: name,
schema: schema,
children: children
}
} else {
return {
name: name,
schema: schema
}
}
}
public render(handler: Function): any {
return this.handle(null, this.schema, handler, this.data, this.additional)
}
protected handle(name: string | null, body: object, handler: Function, data?: object, additional?: object): any {
let type = body['type']
if (type == 'object') {
let properties = body['properties']
let obj = {}
if (properties) {
for (let key in properties) {
obj[key] = this.handle(key, properties[key], handler,
data ? data[key] : undefined,
additional ? additional[key] : undefined)
}
}
return handler(name, body, data, additional, obj)
} else if (type == 'array') {
let items = body['items']
let obj = this.handle(name, items, handler, data, additional)
return handler(name, body, data, additional, obj)
} else {
return handler(name, body, data, additional)
}
}
public static from(schema: String | Promise<String> | object, data?: object | null, additional?: object | null): Promise<JsonForm> {
if (schema instanceof String)
return new Promise<JsonForm>((resolve, reject) => {
try {
// @ts-ignore
resolve(new JsonForm(JSON.parse(schema), data, additional))
} catch (e) {
reject(e)
}
})
else if (schema instanceof Promise) { // @ts-ignore
return schema.then(s => new JsonForm(JSON.parse(s), data, additional))
}
return Promise.resolve(new JsonForm(schema, data, additional))
}
}
export default JsonForm | 33.772152 | 136 | 0.517991 | 70 | 8 | 0 | 18 | 6 | 3 | 2 | 4 | 13 | 1 | 2 | 7.25 | 583 | 0.044597 | 0.010292 | 0.005146 | 0.001715 | 0.003431 | 0.114286 | 0.371429 | 0.308507 | // @ts-nocheck
class JsonForm {
private schema
private additional
private data
private constructor(schema, data?, additional?) {
this.schema = schema
this.data = data
this.additional = additional
}
public tree(name) {
return this.listTree(this.schema, name)
}
protected listTree(schema, name) {
if (schema.type == "object") {
let children = []
for (let key in schema.properties) {
children.push(this.listTree(schema.properties[key], key))
}
return {
name: name,
schema: schema,
children: children
}
} else {
return {
name: name,
schema: schema
}
}
}
public render(handler) {
return this.handle(null, this.schema, handler, this.data, this.additional)
}
protected handle(name, body, handler, data?, additional?) {
let type = body['type']
if (type == 'object') {
let properties = body['properties']
let obj = {}
if (properties) {
for (let key in properties) {
obj[key] = this.handle(key, properties[key], handler,
data ? data[key] : undefined,
additional ? additional[key] : undefined)
}
}
return handler(name, body, data, additional, obj)
} else if (type == 'array') {
let items = body['items']
let obj = this.handle(name, items, handler, data, additional)
return handler(name, body, data, additional, obj)
} else {
return handler(name, body, data, additional)
}
}
public static from(schema, data?, additional?) {
if (schema instanceof String)
return new Promise<JsonForm>((resolve, reject) => {
try {
// @ts-ignore
resolve(new JsonForm(JSON.parse(schema), data, additional))
} catch (e) {
reject(e)
}
})
else if (schema instanceof Promise) { // @ts-ignore
return schema.then(s => new JsonForm(JSON.parse(s), data, additional))
}
return Promise.resolve(new JsonForm(schema, data, additional))
}
}
export default JsonForm |
7ad2a8a2efe8677e2c6113ba5a3697eab2e15d82 | 1,954 | ts | TypeScript | src/lib/compare.ts | Lantern-chat/frontend | 9bf63a15e45329a46415e954efdb263860a22a67 | [
"FSFAP"
] | 4 | 2022-01-26T20:07:24.000Z | 2022-03-23T06:10:08.000Z | src/lib/compare.ts | Lantern-chat/frontend | 9bf63a15e45329a46415e954efdb263860a22a67 | [
"FSFAP"
] | 2 | 2022-01-26T19:27:06.000Z | 2022-02-23T15:53:11.000Z | src/lib/compare.ts | Lantern-chat/frontend | 9bf63a15e45329a46415e954efdb263860a22a67 | [
"FSFAP"
] | null | null | null | export function shallowEqualArrays<T>(
arrA: T[] | null | undefined,
arrB: T[] | null | undefined,
cmp: (a: T, b: T) => boolean = (a, b) => a === b
): boolean {
if(arrA === arrB) {
return true;
}
if(!arrA || !arrB) {
return false;
}
let len = arrA.length;
if(arrB.length !== len) {
return false;
}
for(let i = 0; i < len; i++) {
if(!cmp(arrA[i], arrB[i])) {
return false;
}
}
return true;
}
export function shallowEqualObjects<T>(objA: T | null | undefined, objB: T | null | undefined): boolean {
if(objA === objB) {
return true;
}
if(!objA || !objB) {
return false;
}
let aKeys = Object.keys(objA),
bKeys = Object.keys(objB),
len = aKeys.length;
if(bKeys.length !== len) {
return false;
}
for(let i = 0; i < len; i++) {
let key = aKeys[i];
if(objA[key] !== objB[key] || !Object.prototype.hasOwnProperty.call(objB, key)) {
return false;
}
}
return true;
}
export function shallowEqualObjectsExclude<T>(objA: T | null | undefined, objB: T | null | undefined, e: string[]): boolean {
if(objA === objB) {
return true;
}
if(!objA || !objB) {
return false;
}
let aKeys = Object.keys(objA).filter(key => !e.includes(key)),
bKeys = Object.keys(objB).filter(key => !e.includes(key)),
len = aKeys.length;
if(bKeys.length !== len) {
return false;
}
for(let i = 0; i < len; i++) {
let key = aKeys[i];
if(objA[key] !== objB[key] || !Object.prototype.hasOwnProperty.call(objB, key)) {
return false;
}
}
return true;
}
/// NOTE: Use Intl.Collator for locale-aware comparisons
export function compareString(a: string, b: string): number {
if(a < b) return -1;
else if(a > b) return 1;
else return 0;
} | 21.711111 | 125 | 0.518936 | 69 | 7 | 0 | 14 | 12 | 0 | 0 | 0 | 8 | 0 | 0 | 8.571429 | 613 | 0.034258 | 0.019576 | 0 | 0 | 0 | 0 | 0.242424 | 0.313871 | export function shallowEqualArrays<T>(
arrA,
arrB,
cmp = (a, b) => a === b
) {
if(arrA === arrB) {
return true;
}
if(!arrA || !arrB) {
return false;
}
let len = arrA.length;
if(arrB.length !== len) {
return false;
}
for(let i = 0; i < len; i++) {
if(!cmp(arrA[i], arrB[i])) {
return false;
}
}
return true;
}
export function shallowEqualObjects<T>(objA, objB) {
if(objA === objB) {
return true;
}
if(!objA || !objB) {
return false;
}
let aKeys = Object.keys(objA),
bKeys = Object.keys(objB),
len = aKeys.length;
if(bKeys.length !== len) {
return false;
}
for(let i = 0; i < len; i++) {
let key = aKeys[i];
if(objA[key] !== objB[key] || !Object.prototype.hasOwnProperty.call(objB, key)) {
return false;
}
}
return true;
}
export function shallowEqualObjectsExclude<T>(objA, objB, e) {
if(objA === objB) {
return true;
}
if(!objA || !objB) {
return false;
}
let aKeys = Object.keys(objA).filter(key => !e.includes(key)),
bKeys = Object.keys(objB).filter(key => !e.includes(key)),
len = aKeys.length;
if(bKeys.length !== len) {
return false;
}
for(let i = 0; i < len; i++) {
let key = aKeys[i];
if(objA[key] !== objB[key] || !Object.prototype.hasOwnProperty.call(objB, key)) {
return false;
}
}
return true;
}
/// NOTE: Use Intl.Collator for locale-aware comparisons
export function compareString(a, b) {
if(a < b) return -1;
else if(a > b) return 1;
else return 0;
} |
ee56e2bdaedc6d50312527dc8286b0778d43b9c9 | 2,366 | ts | TypeScript | src/app/src/utils/GithubUtils.ts | vyomea/CMPUT404-project-socialdistribution | 0eb765a09f936009b7e8419abcf48f18ddaf3871 | [
"W3C-20150513"
] | null | null | null | src/app/src/utils/GithubUtils.ts | vyomea/CMPUT404-project-socialdistribution | 0eb765a09f936009b7e8419abcf48f18ddaf3871 | [
"W3C-20150513"
] | 58 | 2022-02-04T04:05:45.000Z | 2022-03-30T21:04:52.000Z | src/app/src/utils/GithubUtils.ts | vyomea/CMPUT404-project-socialdistribution | 0eb765a09f936009b7e8419abcf48f18ddaf3871 | [
"W3C-20150513"
] | null | null | null | let newPayload: any = {};
const getHTMLURLfromSha = (commits: any, size: number) => {
let arr: Array<string> = [];
let url = '';
for (let i = 0; i < commits.length; i++) {
url = commits[i]['url'];
url = url?.replace('api.', '');
url = url?.replace('commits', 'commit');
url = url?.replace('/repos', '');
arr.push(url);
}
return url;
};
const processPayload = (payload: any, type: string) => {
switch (type) {
case 'PullRequestReviewEvent':
newPayload['url'] = payload?.pull_request?.html_url;
newPayload['review'] = {
url: payload?.review?.html_url,
reviewMessage: payload?.review?.body,
state: payload?.review?.state,
};
newPayload['assignee'] = payload?.pull_request?.user?.login;
newPayload['title'] = payload?.pull_request?.title;
break;
case 'PullRequestReviewCommentEvent':
newPayload['action'] = payload?.action;
newPayload['url'] = payload?.comment.html_url;
newPayload['title'] = payload?.pull_request?.title;
newPayload['titleUrl'] = payload?.pull_request?.html_url;
break;
case 'PushEvent':
newPayload['url'] = getHTMLURLfromSha(payload?.commits, payload?.size);
newPayload['branch'] = payload?.ref.split('/')[payload?.ref.split('/').length - 1];
newPayload['size'] = payload?.size;
break;
case 'PullRequestEvent':
newPayload['action'] = payload?.action;
newPayload['url'] = payload?.pull_request?.html_url;
newPayload['title'] = payload?.pull_request?.title;
break;
case 'IssuesEvent':
newPayload['action'] = payload?.action;
newPayload['url'] = payload?.issue?.html_url;
newPayload['title'] = payload?.issue?.title;
break;
case 'IssueCommentEvent':
newPayload['action'] = payload?.action;
newPayload['url'] = payload?.comment.html_url;
newPayload['title'] = payload?.issue?.title;
newPayload['titleUrl'] = payload?.issue?.html_url;
break;
case 'CreateEvent':
newPayload['ref_type'] = payload?.ref_type;
newPayload['ref'] = payload?.ref;
newPayload['descr'] = payload?.description;
break;
case 'DeleteEvent':
newPayload['ref_type'] = payload?.ref_type;
newPayload['ref'] = payload?.ref;
break;
}
return newPayload;
};
export default processPayload;
| 34.289855 | 89 | 0.620034 | 65 | 2 | 0 | 4 | 6 | 0 | 1 | 3 | 3 | 0 | 0 | 29.5 | 635 | 0.009449 | 0.009449 | 0 | 0 | 0 | 0.25 | 0.25 | 0.219068 | let newPayload = {};
/* Example usages of 'getHTMLURLfromSha' are shown below:
newPayload['url'] = getHTMLURLfromSha(payload?.commits, payload?.size);
*/
const getHTMLURLfromSha = (commits, size) => {
let arr = [];
let url = '';
for (let i = 0; i < commits.length; i++) {
url = commits[i]['url'];
url = url?.replace('api.', '');
url = url?.replace('commits', 'commit');
url = url?.replace('/repos', '');
arr.push(url);
}
return url;
};
/* Example usages of 'processPayload' are shown below:
;
*/
const processPayload = (payload, type) => {
switch (type) {
case 'PullRequestReviewEvent':
newPayload['url'] = payload?.pull_request?.html_url;
newPayload['review'] = {
url: payload?.review?.html_url,
reviewMessage: payload?.review?.body,
state: payload?.review?.state,
};
newPayload['assignee'] = payload?.pull_request?.user?.login;
newPayload['title'] = payload?.pull_request?.title;
break;
case 'PullRequestReviewCommentEvent':
newPayload['action'] = payload?.action;
newPayload['url'] = payload?.comment.html_url;
newPayload['title'] = payload?.pull_request?.title;
newPayload['titleUrl'] = payload?.pull_request?.html_url;
break;
case 'PushEvent':
newPayload['url'] = getHTMLURLfromSha(payload?.commits, payload?.size);
newPayload['branch'] = payload?.ref.split('/')[payload?.ref.split('/').length - 1];
newPayload['size'] = payload?.size;
break;
case 'PullRequestEvent':
newPayload['action'] = payload?.action;
newPayload['url'] = payload?.pull_request?.html_url;
newPayload['title'] = payload?.pull_request?.title;
break;
case 'IssuesEvent':
newPayload['action'] = payload?.action;
newPayload['url'] = payload?.issue?.html_url;
newPayload['title'] = payload?.issue?.title;
break;
case 'IssueCommentEvent':
newPayload['action'] = payload?.action;
newPayload['url'] = payload?.comment.html_url;
newPayload['title'] = payload?.issue?.title;
newPayload['titleUrl'] = payload?.issue?.html_url;
break;
case 'CreateEvent':
newPayload['ref_type'] = payload?.ref_type;
newPayload['ref'] = payload?.ref;
newPayload['descr'] = payload?.description;
break;
case 'DeleteEvent':
newPayload['ref_type'] = payload?.ref_type;
newPayload['ref'] = payload?.ref;
break;
}
return newPayload;
};
export default processPayload;
|
eec3a922ad0795f17271ae4b5c7a2b61510e7d3b | 1,734 | ts | TypeScript | src/engine/common.ts | ParentLab/answers | 7b296fcce40e1884c590b888ac1c9253677e29f0 | [
"MIT"
] | null | null | null | src/engine/common.ts | ParentLab/answers | 7b296fcce40e1884c590b888ac1c9253677e29f0 | [
"MIT"
] | 3 | 2022-01-22T11:12:44.000Z | 2022-02-27T01:54:06.000Z | src/engine/common.ts | ParentLab/answers | 7b296fcce40e1884c590b888ac1c9253677e29f0 | [
"MIT"
] | null | null | null | export interface Action<P> {
id?: number;
type: string;
payload: P;
}
export interface ViewItem<P> {
id?: string;
type: string;
payload: P;
}
export const ADD_SELECTED_CHOICE = "ADD_SELECTED_CHOICE";
export interface ChoiceActionPayload {
selectedChoiceIndex: number;
}
export const INFO_VIEW = "INFO_VIEW";
export interface InfoViewPayload {
info: string;
}
export const CUSTOM_VIEW = "CUSTOM_VIEW";
export function addSelectedChoice(
selectedChoiceIndex: number,
): Action<ChoiceActionPayload> {
return {
type: ADD_SELECTED_CHOICE,
payload: {
selectedChoiceIndex
},
};
}
export type ActionHandler<U extends Unit<U>> = (action: Action<any>) => Promise<U | null>;
export type ChoiceCallback<U extends Unit<U>> = (index: number) => Promise<U | null>;
export interface ChoiceItem<U extends Unit<U>> {
text: string;
options?: any;
callback: ChoiceCallback<U>;
}
export interface Choices<U extends Unit<U>> {
choices: ChoiceItem<U>[];
showInHistory?: boolean;
selectedChoiceIndex?: number;
}
export function nextChoices<U extends Unit<U>>(choice: ChoiceItem<U>): Choices<U> {
return {
showInHistory: false,
choices: [choice]
};
}
export interface Unit<U extends Unit<U>> {
// will be managed by Engine
actionId?: number;
isCompleted?: boolean;
views: ViewItem<any>[];
choices?: Choices<U>;
actionHandler?: ActionHandler<U>;
actionable?: boolean;
}
export interface IEngine<U extends Unit<U>> {
getLastUnit(): U | null;
getCurrentActionId(): number;
getAllActions(): Action<any>[];
addAction(action: Action<any>): Promise<boolean>;
getUnits(): U[];
} | 22.815789 | 90 | 0.663206 | 62 | 2 | 5 | 3 | 3 | 20 | 0 | 5 | 16 | 10 | 0 | 5 | 474 | 0.010549 | 0.006329 | 0.042194 | 0.021097 | 0 | 0.151515 | 0.484848 | 0.246392 | export interface Action<P> {
id?;
type;
payload;
}
export interface ViewItem<P> {
id?;
type;
payload;
}
export const ADD_SELECTED_CHOICE = "ADD_SELECTED_CHOICE";
export interface ChoiceActionPayload {
selectedChoiceIndex;
}
export const INFO_VIEW = "INFO_VIEW";
export interface InfoViewPayload {
info;
}
export const CUSTOM_VIEW = "CUSTOM_VIEW";
export function addSelectedChoice(
selectedChoiceIndex,
) {
return {
type: ADD_SELECTED_CHOICE,
payload: {
selectedChoiceIndex
},
};
}
export type ActionHandler<U extends Unit<U>> = (action) => Promise<U | null>;
export type ChoiceCallback<U extends Unit<U>> = (index) => Promise<U | null>;
export interface ChoiceItem<U extends Unit<U>> {
text;
options?;
callback;
}
export interface Choices<U extends Unit<U>> {
choices;
showInHistory?;
selectedChoiceIndex?;
}
export function nextChoices<U extends Unit<U>>(choice) {
return {
showInHistory: false,
choices: [choice]
};
}
export interface Unit<U extends Unit<U>> {
// will be managed by Engine
actionId?;
isCompleted?;
views;
choices?;
actionHandler?;
actionable?;
}
export interface IEngine<U extends Unit<U>> {
getLastUnit();
getCurrentActionId();
getAllActions();
addAction(action);
getUnits();
} |
701844201f67a07ffa7260d8dad3e277b41e6e15 | 7,801 | ts | TypeScript | packages/utils/src/Dot.ts | kodemon/valkyr | 66b02d48b08e2cf5105d164815ae09ae03354c63 | [
"MIT"
] | null | null | null | packages/utils/src/Dot.ts | kodemon/valkyr | 66b02d48b08e2cf5105d164815ae09ae03354c63 | [
"MIT"
] | 4 | 2022-02-07T08:12:10.000Z | 2022-02-07T08:29:40.000Z | packages/utils/src/Dot.ts | kodemon/valkyr | 66b02d48b08e2cf5105d164815ae09ae03354c63 | [
"MIT"
] | null | null | null | // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
// Ported from https://github.com/sindresorhus/dot-prop
const isObject = (value: any) => {
const type = typeof value;
return value !== null && (type === "object" || type === "function");
};
const disallowedKeys = new Set(["__proto__", "prototype", "constructor"]);
const digits = new Set("0123456789");
function getPathSegments(path: string) {
const parts = [];
let currentSegment = "";
let currentPart = "start";
let isIgnoring = false;
for (const character of path) {
switch (character) {
case "\\": {
if (currentPart === "index") {
throw new Error("Invalid character in an index");
}
if (currentPart === "indexEnd") {
throw new Error("Invalid character after an index");
}
if (isIgnoring) {
currentSegment += character;
}
currentPart = "property";
isIgnoring = !isIgnoring;
break;
}
case ".": {
if (currentPart === "index") {
throw new Error("Invalid character in an index");
}
if (currentPart === "indexEnd") {
currentPart = "property";
break;
}
if (isIgnoring) {
isIgnoring = false;
currentSegment += character;
break;
}
if (disallowedKeys.has(currentSegment)) {
return [];
}
parts.push(currentSegment);
currentSegment = "";
currentPart = "property";
break;
}
case "[": {
if (currentPart === "index") {
throw new Error("Invalid character in an index");
}
if (currentPart === "indexEnd") {
currentPart = "index";
break;
}
if (isIgnoring) {
isIgnoring = false;
currentSegment += character;
break;
}
if (currentPart === "property") {
if (disallowedKeys.has(currentSegment)) {
return [];
}
parts.push(currentSegment);
currentSegment = "";
}
currentPart = "index";
break;
}
case "]": {
if (currentPart === "index") {
parts.push(Number.parseInt(currentSegment, 10));
currentSegment = "";
currentPart = "indexEnd";
break;
}
if (currentPart === "indexEnd") {
throw new Error("Invalid character after an index");
}
// Falls through
}
default: {
if (currentPart === "index" && !digits.has(character)) {
throw new Error("Invalid character in an index");
}
if (currentPart === "indexEnd") {
throw new Error("Invalid character after an index");
}
if (currentPart === "start") {
currentPart = "property";
}
if (isIgnoring) {
isIgnoring = false;
currentSegment += "\\";
}
currentSegment += character;
}
}
}
if (isIgnoring) {
currentSegment += "\\";
}
switch (currentPart) {
case "property": {
if (disallowedKeys.has(currentSegment)) {
return [];
}
parts.push(currentSegment);
break;
}
case "index": {
throw new Error("Index was not closed");
}
case "start": {
parts.push("");
break;
}
// No default
}
return parts;
}
function isStringIndex(object: unknown, key: string | number) {
if (typeof key !== "number" && Array.isArray(object)) {
const index = Number.parseInt(key, 10);
return Number.isInteger(index) && object[index] === object[key];
}
return false;
}
function assertNotStringIndex(object: unknown, key: string | number) {
if (isStringIndex(object, key)) {
throw new Error("Cannot use string index");
}
}
export function getProperty<ObjectType, PathType extends string, DefaultValue = undefined>(
object: ObjectType,
path: PathType,
value?: DefaultValue
) {
if (!isObject(object) || typeof path !== "string") {
return value === undefined ? object : value;
}
const pathArray = getPathSegments(path);
if (pathArray.length === 0) {
return value;
}
for (let index = 0; index < pathArray.length; index++) {
const key = pathArray[index];
if (isStringIndex(object, key)) {
object = index === pathArray.length - 1 ? undefined : null;
} else {
object = object[key];
}
if (object === undefined || object === null) {
// `object` is either `undefined` or `null` so we want to stop the loop, and
// if this is not the last bit of the path, and
// if it didn't return `undefined`
// it would return `null` if `object` is `null`
// but we want `get({foo: null}, 'foo.bar')` to equal `undefined`, or the supplied value, not `null`
if (index !== pathArray.length - 1) {
return value;
}
break;
}
}
return object === undefined ? value : object;
}
export function setProperty<ObjectType extends Record<string, any>>(object: ObjectType, path: string, value: unknown) {
if (!isObject(object) || typeof path !== "string") {
return object;
}
const root = object;
const pathArray = getPathSegments(path);
for (let index = 0; index < pathArray.length; index++) {
const key = pathArray[index];
assertNotStringIndex(object, key);
if (index === pathArray.length - 1) {
object[key] = value;
} else if (!isObject(object[key])) {
object[key] = typeof pathArray[index + 1] === "number" ? [] : {};
}
object = object[key];
}
return root;
}
export function deleteProperty(object: Record<string, any>, path: string) {
if (!isObject(object) || typeof path !== "string") {
return false;
}
const pathArray = getPathSegments(path);
for (let index = 0; index < pathArray.length; index++) {
const key = pathArray[index];
assertNotStringIndex(object, key);
if (index === pathArray.length - 1) {
delete object[key];
return true;
}
object = object[key];
if (!isObject(object)) {
return false;
}
}
}
export function hasProperty(object: Record<string, any> | undefined, path: string) {
if (!isObject(object) || typeof path !== "string") {
return false;
}
const pathArray = getPathSegments(path);
if (pathArray.length === 0) {
return false;
}
for (const key of pathArray) {
if (!isObject(object) || !(key in object) || isStringIndex(object, key)) {
return false;
}
object = object[key];
}
return true;
}
export function escapePath(path: string) {
if (typeof path !== "string") {
throw new TypeError("Expected a string");
}
return path.replace(/[\\.[]/g, "\\$&");
}
// The keys returned by Object.entries() for arrays are strings
function entries(value: unknown) {
if (Array.isArray(value)) {
return value.map((value, index) => [index, value]);
}
return Object.entries(value);
}
function stringifyPath(pathSegments: unknown) {
let result = "";
// eslint-disable-next-line prefer-const
for (let [index, segment] of entries(pathSegments)) {
if (typeof segment === "number") {
result += `[${segment}]`;
} else {
segment = escapePath(segment);
result += index === 0 ? segment : `.${segment}`;
}
}
return result;
}
function* deepKeysIterator(object: unknown, currentPath = []) {
if (!isObject(object)) {
if (currentPath.length > 0) {
yield stringifyPath(currentPath);
}
return;
}
for (const [key, value] of entries(object)) {
yield* deepKeysIterator(value, [...currentPath, key]);
}
}
export function deepKeys(object: unknown) {
return [...deepKeysIterator(object)];
}
| 23.217262 | 119 | 0.569542 | 251 | 13 | 0 | 22 | 21 | 0 | 7 | 4 | 20 | 0 | 9 | 16.230769 | 1,988 | 0.017606 | 0.010563 | 0 | 0 | 0.004527 | 0.071429 | 0.357143 | 0.245297 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
// Ported from https://github.com/sindresorhus/dot-prop
/* Example usages of 'isObject' are shown below:
!isObject(object) || typeof path !== "string";
!isObject(object[key]);
!isObject(object);
!isObject(object) || !(key in object) || isStringIndex(object, key);
*/
const isObject = (value) => {
const type = typeof value;
return value !== null && (type === "object" || type === "function");
};
const disallowedKeys = new Set(["__proto__", "prototype", "constructor"]);
const digits = new Set("0123456789");
/* Example usages of 'getPathSegments' are shown below:
getPathSegments(path);
*/
function getPathSegments(path) {
const parts = [];
let currentSegment = "";
let currentPart = "start";
let isIgnoring = false;
for (const character of path) {
switch (character) {
case "\\": {
if (currentPart === "index") {
throw new Error("Invalid character in an index");
}
if (currentPart === "indexEnd") {
throw new Error("Invalid character after an index");
}
if (isIgnoring) {
currentSegment += character;
}
currentPart = "property";
isIgnoring = !isIgnoring;
break;
}
case ".": {
if (currentPart === "index") {
throw new Error("Invalid character in an index");
}
if (currentPart === "indexEnd") {
currentPart = "property";
break;
}
if (isIgnoring) {
isIgnoring = false;
currentSegment += character;
break;
}
if (disallowedKeys.has(currentSegment)) {
return [];
}
parts.push(currentSegment);
currentSegment = "";
currentPart = "property";
break;
}
case "[": {
if (currentPart === "index") {
throw new Error("Invalid character in an index");
}
if (currentPart === "indexEnd") {
currentPart = "index";
break;
}
if (isIgnoring) {
isIgnoring = false;
currentSegment += character;
break;
}
if (currentPart === "property") {
if (disallowedKeys.has(currentSegment)) {
return [];
}
parts.push(currentSegment);
currentSegment = "";
}
currentPart = "index";
break;
}
case "]": {
if (currentPart === "index") {
parts.push(Number.parseInt(currentSegment, 10));
currentSegment = "";
currentPart = "indexEnd";
break;
}
if (currentPart === "indexEnd") {
throw new Error("Invalid character after an index");
}
// Falls through
}
default: {
if (currentPart === "index" && !digits.has(character)) {
throw new Error("Invalid character in an index");
}
if (currentPart === "indexEnd") {
throw new Error("Invalid character after an index");
}
if (currentPart === "start") {
currentPart = "property";
}
if (isIgnoring) {
isIgnoring = false;
currentSegment += "\\";
}
currentSegment += character;
}
}
}
if (isIgnoring) {
currentSegment += "\\";
}
switch (currentPart) {
case "property": {
if (disallowedKeys.has(currentSegment)) {
return [];
}
parts.push(currentSegment);
break;
}
case "index": {
throw new Error("Index was not closed");
}
case "start": {
parts.push("");
break;
}
// No default
}
return parts;
}
/* Example usages of 'isStringIndex' are shown below:
isStringIndex(object, key);
!isObject(object) || !(key in object) || isStringIndex(object, key);
*/
function isStringIndex(object, key) {
if (typeof key !== "number" && Array.isArray(object)) {
const index = Number.parseInt(key, 10);
return Number.isInteger(index) && object[index] === object[key];
}
return false;
}
/* Example usages of 'assertNotStringIndex' are shown below:
assertNotStringIndex(object, key);
*/
function assertNotStringIndex(object, key) {
if (isStringIndex(object, key)) {
throw new Error("Cannot use string index");
}
}
export function getProperty<ObjectType, PathType extends string, DefaultValue = undefined>(
object,
path,
value?
) {
if (!isObject(object) || typeof path !== "string") {
return value === undefined ? object : value;
}
const pathArray = getPathSegments(path);
if (pathArray.length === 0) {
return value;
}
for (let index = 0; index < pathArray.length; index++) {
const key = pathArray[index];
if (isStringIndex(object, key)) {
object = index === pathArray.length - 1 ? undefined : null;
} else {
object = object[key];
}
if (object === undefined || object === null) {
// `object` is either `undefined` or `null` so we want to stop the loop, and
// if this is not the last bit of the path, and
// if it didn't return `undefined`
// it would return `null` if `object` is `null`
// but we want `get({foo: null}, 'foo.bar')` to equal `undefined`, or the supplied value, not `null`
if (index !== pathArray.length - 1) {
return value;
}
break;
}
}
return object === undefined ? value : object;
}
export function setProperty<ObjectType extends Record<string, any>>(object, path, value) {
if (!isObject(object) || typeof path !== "string") {
return object;
}
const root = object;
const pathArray = getPathSegments(path);
for (let index = 0; index < pathArray.length; index++) {
const key = pathArray[index];
assertNotStringIndex(object, key);
if (index === pathArray.length - 1) {
object[key] = value;
} else if (!isObject(object[key])) {
object[key] = typeof pathArray[index + 1] === "number" ? [] : {};
}
object = object[key];
}
return root;
}
export function deleteProperty(object, path) {
if (!isObject(object) || typeof path !== "string") {
return false;
}
const pathArray = getPathSegments(path);
for (let index = 0; index < pathArray.length; index++) {
const key = pathArray[index];
assertNotStringIndex(object, key);
if (index === pathArray.length - 1) {
delete object[key];
return true;
}
object = object[key];
if (!isObject(object)) {
return false;
}
}
}
export function hasProperty(object, path) {
if (!isObject(object) || typeof path !== "string") {
return false;
}
const pathArray = getPathSegments(path);
if (pathArray.length === 0) {
return false;
}
for (const key of pathArray) {
if (!isObject(object) || !(key in object) || isStringIndex(object, key)) {
return false;
}
object = object[key];
}
return true;
}
export /* Example usages of 'escapePath' are shown below:
segment = escapePath(segment);
*/
function escapePath(path) {
if (typeof path !== "string") {
throw new TypeError("Expected a string");
}
return path.replace(/[\\.[]/g, "\\$&");
}
// The keys returned by Object.entries() for arrays are strings
/* Example usages of 'entries' are shown below:
Object.entries(value);
entries(pathSegments);
entries(object);
*/
function entries(value) {
if (Array.isArray(value)) {
return value.map((value, index) => [index, value]);
}
return Object.entries(value);
}
/* Example usages of 'stringifyPath' are shown below:
stringifyPath(currentPath);
*/
function stringifyPath(pathSegments) {
let result = "";
// eslint-disable-next-line prefer-const
for (let [index, segment] of entries(pathSegments)) {
if (typeof segment === "number") {
result += `[${segment}]`;
} else {
segment = escapePath(segment);
result += index === 0 ? segment : `.${segment}`;
}
}
return result;
}
function* deepKeysIterator(object, currentPath = []) {
if (!isObject(object)) {
if (currentPath.length > 0) {
yield stringifyPath(currentPath);
}
return;
}
for (const [key, value] of entries(object)) {
yield* deepKeysIterator(value, [...currentPath, key]);
}
}
export function deepKeys(object) {
return [...deepKeysIterator(object)];
}
|
702105c77d2a8c53c4914da6ce3e6dc757b34e11 | 1,916 | ts | TypeScript | src/helpers/dateFilter.ts | DarlanAguiar/salessystem | 81a169fdfe85ce8af1bdaea1022b81a11f75f4d5 | [
"MIT"
] | null | null | null | src/helpers/dateFilter.ts | DarlanAguiar/salessystem | 81a169fdfe85ce8af1bdaea1022b81a11f75f4d5 | [
"MIT"
] | 1 | 2022-03-28T18:43:41.000Z | 2022-03-28T18:43:41.000Z | src/helpers/dateFilter.ts | DarlanAguiar/salessystem | 81a169fdfe85ce8af1bdaea1022b81a11f75f4d5 | [
"MIT"
] | null | null | null | export const getCurrentMonth = () => {
const now = new Date();
return `${now.getFullYear()}-${now.getMonth() + 1}`;
};
export const fromatDate = (date: Date): string => {
const newDate = new Date(date);
const year = newDate.getFullYear();
const month = String(newDate.getMonth() + 1).padStart(2, '0');
const day = String(newDate.getDate()).padStart(2, '0');
return `${day}/${month}/${year}`;
};
export const formatCurrentMonth = (currentMonth: string): string => {
const [year, month] = currentMonth.split('-');
const months = [
'Janeiro',
'Fevereiro',
'Março',
'Abril',
'Maio',
'Junho',
'Julho',
'Agosto',
'Setembro',
'Outubro',
'Novembro',
'Dezembro'
];
return `${months[Number(month) - 1]} de ${year}`;
};
export const getDate = () => {
const date = new Date();
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
export const formatDateTimeZone = (date: string) => {
const tempDate = new Date(date);
tempDate.setMinutes(tempDate.getMinutes() + tempDate.getTimezoneOffset());
return tempDate.getTime();
};
export const formatFinalDate = (endDate: string) => {
const date = new Date(endDate);
date.setDate(date.getDate() + 2);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
export const formatInitialMonth = (year: number, month: number) => {
const date = formatDateTimeZone(
`${year}-${String(month).padStart(2, '0')}-01`
);
return date;
};
export const formatFinalMonth = (year: number, month: number) => {
const date = formatDateTimeZone(
`${year}-${String(month + 1).padStart(2, '0')}-01`
);
return date;
};
| 24.253165 | 76 | 0.616388 | 61 | 8 | 0 | 8 | 26 | 0 | 2 | 0 | 9 | 0 | 0 | 5.625 | 587 | 0.027257 | 0.044293 | 0 | 0 | 0 | 0 | 0.214286 | 0.378795 | export const getCurrentMonth = () => {
const now = new Date();
return `${now.getFullYear()}-${now.getMonth() + 1}`;
};
export const fromatDate = (date) => {
const newDate = new Date(date);
const year = newDate.getFullYear();
const month = String(newDate.getMonth() + 1).padStart(2, '0');
const day = String(newDate.getDate()).padStart(2, '0');
return `${day}/${month}/${year}`;
};
export const formatCurrentMonth = (currentMonth) => {
const [year, month] = currentMonth.split('-');
const months = [
'Janeiro',
'Fevereiro',
'Março',
'Abril',
'Maio',
'Junho',
'Julho',
'Agosto',
'Setembro',
'Outubro',
'Novembro',
'Dezembro'
];
return `${months[Number(month) - 1]} de ${year}`;
};
export /* Example usages of 'getDate' are shown below:
String(newDate.getDate()).padStart(2, '0');
String(date.getDate()).padStart(2, '0');
date.setDate(date.getDate() + 2);
*/
const getDate = () => {
const date = new Date();
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
export /* Example usages of 'formatDateTimeZone' are shown below:
formatDateTimeZone(`${year}-${String(month).padStart(2, '0')}-01`);
formatDateTimeZone(`${year}-${String(month + 1).padStart(2, '0')}-01`);
*/
const formatDateTimeZone = (date) => {
const tempDate = new Date(date);
tempDate.setMinutes(tempDate.getMinutes() + tempDate.getTimezoneOffset());
return tempDate.getTime();
};
export const formatFinalDate = (endDate) => {
const date = new Date(endDate);
date.setDate(date.getDate() + 2);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
export const formatInitialMonth = (year, month) => {
const date = formatDateTimeZone(
`${year}-${String(month).padStart(2, '0')}-01`
);
return date;
};
export const formatFinalMonth = (year, month) => {
const date = formatDateTimeZone(
`${year}-${String(month + 1).padStart(2, '0')}-01`
);
return date;
};
|
bbb3c6df82171fa90d0040776b93e6265574820e | 4,557 | ts | TypeScript | src/match.ts | MassScout-Alliance/massscout-extension | c0f42cc2866742a2aeeb32833af6426bb47677a7 | [
"MIT"
] | null | null | null | src/match.ts | MassScout-Alliance/massscout-extension | c0f42cc2866742a2aeeb32833af6426bb47677a7 | [
"MIT"
] | 12 | 2022-01-01T06:39:10.000Z | 2022-03-05T05:34:04.000Z | src/match.ts | MassScout-Alliance/massscout-extension | c0f42cc2866742a2aeeb32833af6426bb47677a7 | [
"MIT"
] | null | null | null | export enum AllianceColor {
BLUE, RED
}
export enum StoneType {
SKYSTONE, STONE
}
export enum ScoringResult {
SCORED, FAILED, DID_NOT_TRY
}
// OK FTC state-of-the-art mobile phone control system
export enum DisconnectStatus {
NO_DISCONNECT, PARTIAL, TOTAL
}
export class MatchEntry {
matchCode: string;
teamNumber: number;
alliance: AllianceColor;
auto: AutonomousPerformance;
teleOp: TeleOpPerformance;
endgame: EndgamePerformance;
disconnect: DisconnectStatus;
remarks?: string;
constructor(matchCode: string, teamNumber: number, alliance: AllianceColor,
auto: AutonomousPerformance, teleOp: TeleOpPerformance, endgame: EndgamePerformance,
disconnect: DisconnectStatus, remarks?: string) {
this.matchCode = matchCode;
this.teamNumber = teamNumber;
this.alliance = alliance;
this.auto = auto;
this.teleOp = teleOp;
this.endgame = endgame;
this.disconnect = disconnect;
this.remarks = remarks;
this.validateAutonomous();
this.validateMetadata();
}
public validateMetadata() {
if (!isValidMatchCode(this.matchCode)) {
throw new Error(`Match code "${this.matchCode}" is invalid`);
}
if (isNaN(this.teamNumber)) {
throw new Error(`Invalid team number`);
}
if (this.teamNumber < 1 || Math.floor(this.teamNumber) !== this.teamNumber) {
throw new Error(`Team number ${this.teamNumber} is invalid`);
}
if (this.disconnect === DisconnectStatus.TOTAL && this.getTotalScore() > 0) {
throw new Error('A totally disconnected team cannot score points');
}
}
public validateAutonomous() {
if (this.auto.cyclesAttempted < this.auto.deliveredStones.length) {
throw new RangeError(`${this.teamNumber} ${this.matchCode}: autonomous cyclesAttempted < num of deliveredStones`);
}
if (this.auto.stonesOnFoundation > this.auto.deliveredStones.length) {
throw new RangeError(`${this.teamNumber} ${this.matchCode}: autonomous stonesOnFoundation > num of deliveredStones`);
}
}
getAutonomousScore(): number {
let score = 0;
// 4.5.2.1
if (this.auto.movedFoundation === ScoringResult.SCORED) {
score += 10;
}
// 4.5.2.2
for (let i = 0; i < this.auto.deliveredStones.length; i++) {
const stone = this.auto.deliveredStones[i];
if (stone === StoneType.SKYSTONE && i < 2) {
score += 10;
} else if (stone != undefined) {
score += 2;
}
}
// 4.5.2.3
if (this.auto.parked === ScoringResult.SCORED) {
score += 5;
}
// 4.5.2.4
score += this.auto.stonesOnFoundation * 4;
return score;
}
getTeleOpScore(): number {
let score = 0;
// 4.5.3.1
score += this.teleOp.allianceStonesDelivered;
// 4.5.3.2
score += this.teleOp.stonesPerLevel.reduce((a, b) => a + b, 0);
// 4.5.3.3
score += this.teleOp.stonesPerLevel.length * 2;
return score;
}
getEndgameScore(): number {
let score = 0;
// 4.5.4.1
if (this.endgame.capstoneLevel !== undefined) {
score += 5 + this.endgame.capstoneLevel;
}
// 4.5.4.2
if (this.endgame.movedFoundation === ScoringResult.SCORED) {
score += 15;
}
// 4.5.4.3
if (this.endgame.parked === ScoringResult.SCORED) {
score += 5;
}
return score;
}
getTotalScore(): number {
return this.getAutonomousScore() + this.getTeleOpScore() + this.getEndgameScore();
}
}
export interface AutonomousPerformance {
deliveredStones: StoneType[];
cyclesAttempted: number;
stonesOnFoundation: number;
parked: ScoringResult;
movedFoundation: ScoringResult;
}
export interface TeleOpPerformance {
allianceStonesDelivered: number;
neutralStonesDelivered: number;
stonesPerLevel: number[];
}
export interface EndgamePerformance {
movedFoundation: ScoringResult;
capstoneLevel?: number;
parked: ScoringResult;
}
export type MatchEntrySet = MatchEntry[];
export function isValidMatchCode(matchCode: string): boolean {
const matchResult = matchCode.match(/^([QF][1-9][0-9]*)|(SF[12]-[1-9][0-9]*)$/);
return matchResult !== null && matchResult[0] === matchCode;
}
| 30.178808 | 129 | 0.60237 | 122 | 9 | 0 | 11 | 6 | 19 | 7 | 0 | 18 | 5 | 0 | 7.222222 | 1,258 | 0.015898 | 0.004769 | 0.015103 | 0.003975 | 0 | 0 | 0.4 | 0.230502 | export enum AllianceColor {
BLUE, RED
}
export enum StoneType {
SKYSTONE, STONE
}
export enum ScoringResult {
SCORED, FAILED, DID_NOT_TRY
}
// OK FTC state-of-the-art mobile phone control system
export enum DisconnectStatus {
NO_DISCONNECT, PARTIAL, TOTAL
}
export class MatchEntry {
matchCode;
teamNumber;
alliance;
auto;
teleOp;
endgame;
disconnect;
remarks?;
constructor(matchCode, teamNumber, alliance,
auto, teleOp, endgame,
disconnect, remarks?) {
this.matchCode = matchCode;
this.teamNumber = teamNumber;
this.alliance = alliance;
this.auto = auto;
this.teleOp = teleOp;
this.endgame = endgame;
this.disconnect = disconnect;
this.remarks = remarks;
this.validateAutonomous();
this.validateMetadata();
}
public validateMetadata() {
if (!isValidMatchCode(this.matchCode)) {
throw new Error(`Match code "${this.matchCode}" is invalid`);
}
if (isNaN(this.teamNumber)) {
throw new Error(`Invalid team number`);
}
if (this.teamNumber < 1 || Math.floor(this.teamNumber) !== this.teamNumber) {
throw new Error(`Team number ${this.teamNumber} is invalid`);
}
if (this.disconnect === DisconnectStatus.TOTAL && this.getTotalScore() > 0) {
throw new Error('A totally disconnected team cannot score points');
}
}
public validateAutonomous() {
if (this.auto.cyclesAttempted < this.auto.deliveredStones.length) {
throw new RangeError(`${this.teamNumber} ${this.matchCode}: autonomous cyclesAttempted < num of deliveredStones`);
}
if (this.auto.stonesOnFoundation > this.auto.deliveredStones.length) {
throw new RangeError(`${this.teamNumber} ${this.matchCode}: autonomous stonesOnFoundation > num of deliveredStones`);
}
}
getAutonomousScore() {
let score = 0;
// 4.5.2.1
if (this.auto.movedFoundation === ScoringResult.SCORED) {
score += 10;
}
// 4.5.2.2
for (let i = 0; i < this.auto.deliveredStones.length; i++) {
const stone = this.auto.deliveredStones[i];
if (stone === StoneType.SKYSTONE && i < 2) {
score += 10;
} else if (stone != undefined) {
score += 2;
}
}
// 4.5.2.3
if (this.auto.parked === ScoringResult.SCORED) {
score += 5;
}
// 4.5.2.4
score += this.auto.stonesOnFoundation * 4;
return score;
}
getTeleOpScore() {
let score = 0;
// 4.5.3.1
score += this.teleOp.allianceStonesDelivered;
// 4.5.3.2
score += this.teleOp.stonesPerLevel.reduce((a, b) => a + b, 0);
// 4.5.3.3
score += this.teleOp.stonesPerLevel.length * 2;
return score;
}
getEndgameScore() {
let score = 0;
// 4.5.4.1
if (this.endgame.capstoneLevel !== undefined) {
score += 5 + this.endgame.capstoneLevel;
}
// 4.5.4.2
if (this.endgame.movedFoundation === ScoringResult.SCORED) {
score += 15;
}
// 4.5.4.3
if (this.endgame.parked === ScoringResult.SCORED) {
score += 5;
}
return score;
}
getTotalScore() {
return this.getAutonomousScore() + this.getTeleOpScore() + this.getEndgameScore();
}
}
export interface AutonomousPerformance {
deliveredStones;
cyclesAttempted;
stonesOnFoundation;
parked;
movedFoundation;
}
export interface TeleOpPerformance {
allianceStonesDelivered;
neutralStonesDelivered;
stonesPerLevel;
}
export interface EndgamePerformance {
movedFoundation;
capstoneLevel?;
parked;
}
export type MatchEntrySet = MatchEntry[];
export /* Example usages of 'isValidMatchCode' are shown below:
!isValidMatchCode(this.matchCode);
*/
function isValidMatchCode(matchCode) {
const matchResult = matchCode.match(/^([QF][1-9][0-9]*)|(SF[12]-[1-9][0-9]*)$/);
return matchResult !== null && matchResult[0] === matchCode;
}
|
6e3e058255cbb3c91ddb6ed39665c74db2430318 | 9,484 | ts | TypeScript | src/editor-module/utils/pcd-util.ts | fastlabel/AutomanTools | bf1fe121298a88443afdb64fc5d3527553dc8da0 | [
"Apache-2.0"
] | 20 | 2022-01-21T07:46:31.000Z | 2022-03-11T09:32:04.000Z | src/editor-module/utils/pcd-util.ts | fastlabel/AutomanTools | bf1fe121298a88443afdb64fc5d3527553dc8da0 | [
"Apache-2.0"
] | null | null | null | src/editor-module/utils/pcd-util.ts | fastlabel/AutomanTools | bf1fe121298a88443afdb64fc5d3527553dc8da0 | [
"Apache-2.0"
] | 2 | 2022-02-07T04:00:54.000Z | 2022-02-07T08:27:25.000Z | // from https://gitlab.com/taketwo/three-pcd-loader/blob/master/decompress-lzf.js
const decompressLZF = (inData: any, outLength: number): Uint8Array => {
const inLength = inData.length;
const outData = new Uint8Array(outLength);
let inPtr = 0;
let outPtr = 0;
let ctrl;
let len;
let ref;
do {
ctrl = inData[inPtr++];
if (ctrl < 1 << 5) {
ctrl++;
if (outPtr + ctrl > outLength)
throw new Error('Output buffer is not large enough');
if (inPtr + ctrl > inLength) throw new Error('Invalid compressed data');
do {
outData[outPtr++] = inData[inPtr++];
} while (--ctrl);
} else {
len = ctrl >> 5;
ref = outPtr - ((ctrl & 0x1f) << 8) - 1;
if (inPtr >= inLength) throw new Error('Invalid compressed data');
if (len === 7) {
len += inData[inPtr++];
if (inPtr >= inLength) throw new Error('Invalid compressed data');
}
ref -= inData[inPtr++];
if (outPtr + len + 2 > outLength)
throw new Error('Output buffer is not large enough');
if (ref < 0) throw new Error('Invalid compressed data');
if (ref >= outPtr) throw new Error('Invalid compressed data');
do {
outData[outPtr++] = outData[ref++];
} while (--len + 2);
}
} while (inPtr < inLength);
return outData;
};
const parseHeader = (data: any) => {
const header: any = {};
const result1 = data.search(/[\r\n]DATA\s(\S*)\s/i);
const result2 = /[\r\n]DATA\s(\S*)\s/i.exec(data.substr(result1 - 1)) || [];
header.data = result2[1];
header.headerLen = result2[0].length + result1;
header.str = data.substr(0, header.headerLen);
// remove comments
header.str = header.str.replace(/#.*/gi, '');
// parse
header.version = /VERSION (.*)/i.exec(header.str);
header.fields = /FIELDS (.*)/i.exec(header.str);
header.size = /SIZE (.*)/i.exec(header.str);
header.type = /TYPE (.*)/i.exec(header.str);
header.count = /COUNT (.*)/i.exec(header.str);
header.width = /WIDTH (.*)/i.exec(header.str);
header.height = /HEIGHT (.*)/i.exec(header.str);
header.viewpoint = /VIEWPOINT (.*)/i.exec(header.str);
header.points = /POINTS (.*)/i.exec(header.str);
// evaluate
if (header.version !== null) {
header.version = parseFloat(header.version[1]);
}
if (header.fields !== null) {
header.fields = header.fields[1].split(' ');
}
if (header.type !== null) {
header.type = header.type[1].split(' ');
}
if (header.width !== null) {
header.width = parseInt(header.width[1]);
}
if (header.height !== null) {
header.height = parseInt(header.height[1]);
}
if (header.viewpoint !== null) {
header.viewpoint = header.viewpoint[1];
}
if (header.points !== null) {
header.points = parseInt(header.points[1], 10);
}
if (header.points === null) {
header.points = header.width * header.height;
}
if (header.size !== null) {
header.size = header.size[1].split(' ').map((x: any) => {
return parseInt(x, 10);
});
}
if (header.count !== null) {
header.count = header.count[1].split(' ').map((x: any) => {
return parseInt(x, 10);
});
} else {
header.count = [];
for (let i = 0, l = header.fields.length; i < l; i++) {
header.count.push(1);
}
}
header.offset = {};
let sizeSum = 0;
for (let i = 0, l = header.fields.length; i < l; i++) {
if (header.data === 'ascii') {
header.offset[header.fields[i]] = i;
} else {
header.offset[header.fields[i]] = sizeSum;
sizeSum += header.size[i] * header.count[i];
}
}
// for binary only
header.rowSize = sizeSum;
return header;
};
const PcdUtil = {
parse(data: any, textData: string, url: string, argLittleEndian?: boolean) {
const littleEndian = argLittleEndian === undefined ? true : argLittleEndian;
// parse header (always ascii format)
const header = parseHeader(textData);
// parse data
const position = [];
const normal = [];
const color = [];
// ascii
if (header.data === 'ascii') {
const offset = header.offset;
const pcdData = textData.substr(header.headerLen);
const lines = pcdData.split('\n');
for (let i = 0, l = lines.length; i < l; i++) {
if (lines[i] === '') continue;
const line = lines[i].split(' ');
if (offset.x !== undefined) {
position.push(parseFloat(line[offset.x]));
position.push(parseFloat(line[offset.y]));
position.push(parseFloat(line[offset.z]));
}
if (offset.rgb !== undefined) {
const rgb = parseFloat(line[offset.rgb]);
const r = (rgb >> 16) & 0x0000ff;
const g = (rgb >> 8) & 0x0000ff;
const b = (rgb >> 0) & 0x0000ff;
color.push(r / 255, g / 255, b / 255);
}
if (offset.normal_x !== undefined) {
normal.push(parseFloat(line[offset.normal_x]));
normal.push(parseFloat(line[offset.normal_y]));
normal.push(parseFloat(line[offset.normal_z]));
}
}
}
// binary-compressed
// normally data in PCD files are organized as array of structures: XYZRGBXYZRGB
// binary compressed PCD files organize their data as structure of arrays: XXYYZZRGBRGB
// that requires a totally different parsing approach compared to non-compressed data
if (header.data === 'binary_compressed') {
const sizes = new Uint32Array(
data.slice(header.headerLen, header.headerLen + 8)
);
const compressedSize = sizes[0];
const decompressedSize = sizes[1];
const decompressed = decompressLZF(
new Uint8Array(data, header.headerLen + 8, compressedSize),
decompressedSize
);
const dataview = new DataView(decompressed.buffer);
const offset = header.offset;
for (let i = 0; i < header.points; i++) {
if (offset.x !== undefined) {
position.push(
dataview.getFloat32(
header.points * offset.x + header.size[0] * i,
littleEndian
)
);
position.push(
dataview.getFloat32(
header.points * offset.y + header.size[1] * i,
littleEndian
)
);
position.push(
dataview.getFloat32(
header.points * offset.z + header.size[2] * i,
littleEndian
)
);
}
if (offset.rgb !== undefined) {
color.push(
dataview.getUint8(
header.points * offset.rgb + header.size[3] * i + 0
) / 255.0
);
color.push(
dataview.getUint8(
header.points * offset.rgb + header.size[3] * i + 1
) / 255.0
);
color.push(
dataview.getUint8(
header.points * offset.rgb + header.size[3] * i + 2
) / 255.0
);
}
if (offset.normal_x !== undefined) {
normal.push(
dataview.getFloat32(
header.points * offset.normal_x + header.size[4] * i,
littleEndian
)
);
normal.push(
dataview.getFloat32(
header.points * offset.normal_y + header.size[5] * i,
littleEndian
)
);
normal.push(
dataview.getFloat32(
header.points * offset.normal_z + header.size[6] * i,
littleEndian
)
);
}
}
}
// binary
if (header.data === 'binary') {
const dataview = new DataView(data, header.headerLen);
const offset = header.offset;
for (let i = 0, row = 0; i < header.points; i++, row += header.rowSize) {
if (offset.x !== undefined) {
position.push(dataview.getFloat32(row + offset.x, littleEndian));
position.push(dataview.getFloat32(row + offset.y, littleEndian));
position.push(dataview.getFloat32(row + offset.z, littleEndian));
}
if (offset.rgb !== undefined) {
color.push(dataview.getUint8(row + offset.rgb + 2) / 255.0);
color.push(dataview.getUint8(row + offset.rgb + 1) / 255.0);
color.push(dataview.getUint8(row + offset.rgb + 0) / 255.0);
}
if (offset.normal_x !== undefined) {
normal.push(dataview.getFloat32(row + offset.normal_x, littleEndian));
normal.push(dataview.getFloat32(row + offset.normal_y, littleEndian));
normal.push(dataview.getFloat32(row + offset.normal_z, littleEndian));
}
}
}
const urlConverted = /([^/]*)/.exec(url.split('').reverse().join('')) || [];
const name = urlConverted[1].split('').reverse().join('');
return { header, position, normal, color, name };
},
getMaxMin(
vertices: number[] | Float32Array,
target: 'x' | 'y' | 'z'
): { max: number; min: number; points: number[] } {
const stride = 3;
let max = Number.NEGATIVE_INFINITY;
let min = Number.POSITIVE_INFINITY;
const points = [];
const offset = target === 'z' ? 2 : target === 'y' ? 1 : 0;
for (let i = 0, l = vertices.length / stride; i < l; i++) {
const vertic = vertices[stride * i + offset];
if (vertic > max) {
max = vertic;
}
if (vertic < min) {
min = vertic;
}
points.push(vertic);
}
return { max, min, points };
},
};
export default PcdUtil;
| 32.591065 | 91 | 0.553564 | 260 | 6 | 0 | 11 | 54 | 0 | 2 | 6 | 8 | 0 | 0 | 41.333333 | 2,759 | 0.006162 | 0.019572 | 0 | 0 | 0 | 0.084507 | 0.112676 | 0.247576 | // from https://gitlab.com/taketwo/three-pcd-loader/blob/master/decompress-lzf.js
/* Example usages of 'decompressLZF' are shown below:
decompressLZF(new Uint8Array(data, header.headerLen + 8, compressedSize), decompressedSize);
*/
const decompressLZF = (inData, outLength) => {
const inLength = inData.length;
const outData = new Uint8Array(outLength);
let inPtr = 0;
let outPtr = 0;
let ctrl;
let len;
let ref;
do {
ctrl = inData[inPtr++];
if (ctrl < 1 << 5) {
ctrl++;
if (outPtr + ctrl > outLength)
throw new Error('Output buffer is not large enough');
if (inPtr + ctrl > inLength) throw new Error('Invalid compressed data');
do {
outData[outPtr++] = inData[inPtr++];
} while (--ctrl);
} else {
len = ctrl >> 5;
ref = outPtr - ((ctrl & 0x1f) << 8) - 1;
if (inPtr >= inLength) throw new Error('Invalid compressed data');
if (len === 7) {
len += inData[inPtr++];
if (inPtr >= inLength) throw new Error('Invalid compressed data');
}
ref -= inData[inPtr++];
if (outPtr + len + 2 > outLength)
throw new Error('Output buffer is not large enough');
if (ref < 0) throw new Error('Invalid compressed data');
if (ref >= outPtr) throw new Error('Invalid compressed data');
do {
outData[outPtr++] = outData[ref++];
} while (--len + 2);
}
} while (inPtr < inLength);
return outData;
};
/* Example usages of 'parseHeader' are shown below:
parseHeader(textData);
*/
const parseHeader = (data) => {
const header = {};
const result1 = data.search(/[\r\n]DATA\s(\S*)\s/i);
const result2 = /[\r\n]DATA\s(\S*)\s/i.exec(data.substr(result1 - 1)) || [];
header.data = result2[1];
header.headerLen = result2[0].length + result1;
header.str = data.substr(0, header.headerLen);
// remove comments
header.str = header.str.replace(/#.*/gi, '');
// parse
header.version = /VERSION (.*)/i.exec(header.str);
header.fields = /FIELDS (.*)/i.exec(header.str);
header.size = /SIZE (.*)/i.exec(header.str);
header.type = /TYPE (.*)/i.exec(header.str);
header.count = /COUNT (.*)/i.exec(header.str);
header.width = /WIDTH (.*)/i.exec(header.str);
header.height = /HEIGHT (.*)/i.exec(header.str);
header.viewpoint = /VIEWPOINT (.*)/i.exec(header.str);
header.points = /POINTS (.*)/i.exec(header.str);
// evaluate
if (header.version !== null) {
header.version = parseFloat(header.version[1]);
}
if (header.fields !== null) {
header.fields = header.fields[1].split(' ');
}
if (header.type !== null) {
header.type = header.type[1].split(' ');
}
if (header.width !== null) {
header.width = parseInt(header.width[1]);
}
if (header.height !== null) {
header.height = parseInt(header.height[1]);
}
if (header.viewpoint !== null) {
header.viewpoint = header.viewpoint[1];
}
if (header.points !== null) {
header.points = parseInt(header.points[1], 10);
}
if (header.points === null) {
header.points = header.width * header.height;
}
if (header.size !== null) {
header.size = header.size[1].split(' ').map((x) => {
return parseInt(x, 10);
});
}
if (header.count !== null) {
header.count = header.count[1].split(' ').map((x) => {
return parseInt(x, 10);
});
} else {
header.count = [];
for (let i = 0, l = header.fields.length; i < l; i++) {
header.count.push(1);
}
}
header.offset = {};
let sizeSum = 0;
for (let i = 0, l = header.fields.length; i < l; i++) {
if (header.data === 'ascii') {
header.offset[header.fields[i]] = i;
} else {
header.offset[header.fields[i]] = sizeSum;
sizeSum += header.size[i] * header.count[i];
}
}
// for binary only
header.rowSize = sizeSum;
return header;
};
const PcdUtil = {
parse(data, textData, url, argLittleEndian?) {
const littleEndian = argLittleEndian === undefined ? true : argLittleEndian;
// parse header (always ascii format)
const header = parseHeader(textData);
// parse data
const position = [];
const normal = [];
const color = [];
// ascii
if (header.data === 'ascii') {
const offset = header.offset;
const pcdData = textData.substr(header.headerLen);
const lines = pcdData.split('\n');
for (let i = 0, l = lines.length; i < l; i++) {
if (lines[i] === '') continue;
const line = lines[i].split(' ');
if (offset.x !== undefined) {
position.push(parseFloat(line[offset.x]));
position.push(parseFloat(line[offset.y]));
position.push(parseFloat(line[offset.z]));
}
if (offset.rgb !== undefined) {
const rgb = parseFloat(line[offset.rgb]);
const r = (rgb >> 16) & 0x0000ff;
const g = (rgb >> 8) & 0x0000ff;
const b = (rgb >> 0) & 0x0000ff;
color.push(r / 255, g / 255, b / 255);
}
if (offset.normal_x !== undefined) {
normal.push(parseFloat(line[offset.normal_x]));
normal.push(parseFloat(line[offset.normal_y]));
normal.push(parseFloat(line[offset.normal_z]));
}
}
}
// binary-compressed
// normally data in PCD files are organized as array of structures: XYZRGBXYZRGB
// binary compressed PCD files organize their data as structure of arrays: XXYYZZRGBRGB
// that requires a totally different parsing approach compared to non-compressed data
if (header.data === 'binary_compressed') {
const sizes = new Uint32Array(
data.slice(header.headerLen, header.headerLen + 8)
);
const compressedSize = sizes[0];
const decompressedSize = sizes[1];
const decompressed = decompressLZF(
new Uint8Array(data, header.headerLen + 8, compressedSize),
decompressedSize
);
const dataview = new DataView(decompressed.buffer);
const offset = header.offset;
for (let i = 0; i < header.points; i++) {
if (offset.x !== undefined) {
position.push(
dataview.getFloat32(
header.points * offset.x + header.size[0] * i,
littleEndian
)
);
position.push(
dataview.getFloat32(
header.points * offset.y + header.size[1] * i,
littleEndian
)
);
position.push(
dataview.getFloat32(
header.points * offset.z + header.size[2] * i,
littleEndian
)
);
}
if (offset.rgb !== undefined) {
color.push(
dataview.getUint8(
header.points * offset.rgb + header.size[3] * i + 0
) / 255.0
);
color.push(
dataview.getUint8(
header.points * offset.rgb + header.size[3] * i + 1
) / 255.0
);
color.push(
dataview.getUint8(
header.points * offset.rgb + header.size[3] * i + 2
) / 255.0
);
}
if (offset.normal_x !== undefined) {
normal.push(
dataview.getFloat32(
header.points * offset.normal_x + header.size[4] * i,
littleEndian
)
);
normal.push(
dataview.getFloat32(
header.points * offset.normal_y + header.size[5] * i,
littleEndian
)
);
normal.push(
dataview.getFloat32(
header.points * offset.normal_z + header.size[6] * i,
littleEndian
)
);
}
}
}
// binary
if (header.data === 'binary') {
const dataview = new DataView(data, header.headerLen);
const offset = header.offset;
for (let i = 0, row = 0; i < header.points; i++, row += header.rowSize) {
if (offset.x !== undefined) {
position.push(dataview.getFloat32(row + offset.x, littleEndian));
position.push(dataview.getFloat32(row + offset.y, littleEndian));
position.push(dataview.getFloat32(row + offset.z, littleEndian));
}
if (offset.rgb !== undefined) {
color.push(dataview.getUint8(row + offset.rgb + 2) / 255.0);
color.push(dataview.getUint8(row + offset.rgb + 1) / 255.0);
color.push(dataview.getUint8(row + offset.rgb + 0) / 255.0);
}
if (offset.normal_x !== undefined) {
normal.push(dataview.getFloat32(row + offset.normal_x, littleEndian));
normal.push(dataview.getFloat32(row + offset.normal_y, littleEndian));
normal.push(dataview.getFloat32(row + offset.normal_z, littleEndian));
}
}
}
const urlConverted = /([^/]*)/.exec(url.split('').reverse().join('')) || [];
const name = urlConverted[1].split('').reverse().join('');
return { header, position, normal, color, name };
},
getMaxMin(
vertices,
target
) {
const stride = 3;
let max = Number.NEGATIVE_INFINITY;
let min = Number.POSITIVE_INFINITY;
const points = [];
const offset = target === 'z' ? 2 : target === 'y' ? 1 : 0;
for (let i = 0, l = vertices.length / stride; i < l; i++) {
const vertic = vertices[stride * i + offset];
if (vertic > max) {
max = vertic;
}
if (vertic < min) {
min = vertic;
}
points.push(vertic);
}
return { max, min, points };
},
};
export default PcdUtil;
|
6ec8fa8d7c3e71053f80ee4c39f92497110c15ae | 7,528 | ts | TypeScript | tool/analytics/report.ts | jinjor/whiteboard | f1f18f389f2b99be491b9f27dab20ba8210f279d | [
"MIT"
] | 9 | 2022-03-18T16:07:25.000Z | 2022-03-27T09:35:40.000Z | tool/analytics/report.ts | jinjor/whiteboard | f1f18f389f2b99be491b9f27dab20ba8210f279d | [
"MIT"
] | 1 | 2022-03-20T11:28:16.000Z | 2022-03-20T11:28:16.000Z | tool/analytics/report.ts | jinjor/whiteboard | f1f18f389f2b99be491b9f27dab20ba8210f279d | [
"MIT"
] | null | null | null | // https://developers.cloudflare.com/workers/platform/pricing
const WORKER_REQ_LIMIT = 1000 * 1000;
const WORKER_DURATION_LIMIT = 400 * 1000;
const DURABLE_OBJECT_REQ_LIMIT = 1000 * 1000;
const DURABLE_OBJECT_DURATION_LIMIT = 400 * 1000;
const DURABLE_STORAGE_READ_LIMIT = 1000 * 1000;
const DURABLE_STORAGE_WRITE_LIMIT = 1000 * 1000;
const DURABLE_STORAGE_DELETE_LIMIT = 1000 * 1000;
const DURABLE_STORAGE_AMOUNT_LIMIT = 1000 * 1000 * 1000;
function sum(array: number[]) {
return array.reduce((a, b) => a + b, 0);
}
const color1 = "#36a";
const color2 = "#a63";
const color3 = "#6a3";
const color4 = "#a36";
export function writeHTMLReport(env: string, data: any): string {
const workerReqsTotal = sum(data.workerReqs);
const workerDurationsTotal = sum(data.workerDurations);
const durableObjectReqsTotal = sum(data.durableObjectReqs);
const durableObjectWallTimes = data.durableObjectWallTimes.map(
(microsecs) => ((microsecs / 1000 / 1000) * 128) / 1000
); // GB*s
const durableObjectCpuTimes = data.durableObjectCpuTimes.map(
(microsecs) => ((microsecs / 1000 / 1000) * 128) / 1000
); // GB*s
const durableObjectDurationTotal = Math.max(
sum(durableObjectWallTimes),
sum(durableObjectCpuTimes)
); // GB*s
const durableObjectReadsTotal = sum(data.durableObjectReads);
const durableObjectWritesTotal = sum(data.durableObjectWrites);
const durableObjectDeletesTotal = sum(data.durableObjectDeletes);
const durableObjectStoredMax = sum(data.durableObjectStored);
const dayLabels = data.days.map((d) =>
d.slice(5).replaceAll("0", "").replace("-", "/")
);
const chart1 = renderLineChart({
id: "worker-reqs",
title: "workers requests",
labels: dayLabels,
datasets: [
{
color: color1,
label: "Requests",
data: data.workerReqs,
},
],
});
const chart2 = renderLineChart({
id: "worker-durations",
title: "workers durations",
labels: dayLabels,
datasets: [
{
color: color1,
label: "Duration (GB * s)",
data: data.workerDurations,
},
],
});
const pichart1 = renderPieChart({
id: "worker-requests-pie",
title: "workers requests",
color: color1,
label: "Requests",
value: workerReqsTotal,
limit: WORKER_REQ_LIMIT,
});
const pichart2 = renderPieChart({
id: "worker-durations-pie",
title: "workers durations",
color: color1,
label: "Duration",
value: workerDurationsTotal,
limit: WORKER_DURATION_LIMIT,
});
const chart3 = renderLineChart({
id: "durable-object-requests",
title: "durable object requests",
labels: dayLabels,
datasets: [
{
color: color1,
label: "Requests",
data: data.durableObjectReqs,
},
],
});
const chart4 = renderLineChart({
id: "durable-object-durations",
title: "durable object durations",
labels: dayLabels,
datasets: [
{
color: color1,
label: "Wall times (GB * s)",
data: durableObjectWallTimes,
},
{
color: color2,
label: "CPU times (GB * s)",
data: durableObjectCpuTimes,
},
],
});
const pichart3 = renderPieChart({
id: "durable-object-requests-pie",
title: "durable object requests",
color: color1,
label: "Requests",
value: durableObjectReqsTotal,
limit: DURABLE_OBJECT_REQ_LIMIT,
});
const pichart4 = renderPieChart({
id: "durable-object-durations-pie",
title: "durable object durations",
color: color1,
label: "Duration",
value: durableObjectDurationTotal,
limit: DURABLE_OBJECT_DURATION_LIMIT,
});
const chart5 = renderLineChart({
id: "durable-storage-requests",
title: "durable storage requests",
labels: dayLabels,
datasets: [
{
color: color1,
label: "Reads (unit)",
data: data.durableObjectReads,
},
{
color: color3,
label: "Writes (unit)",
data: data.durableObjectWrites,
},
{
color: color4,
label: "Deletes (unit)",
data: data.durableObjectDeletes,
},
],
});
const pichart5a = renderPieChart({
id: "durable-storage-reads-pie",
title: "durable storage reads",
color: color1,
label: "Reads",
value: durableObjectReadsTotal,
limit: DURABLE_STORAGE_READ_LIMIT,
});
const pichart5b = renderPieChart({
id: "durable-storage-writes-pie",
title: "durable storage writes",
color: color3,
label: "Writes",
value: durableObjectWritesTotal,
limit: DURABLE_STORAGE_WRITE_LIMIT,
});
const pichart5c = renderPieChart({
id: "durable-storage-deletes-pie",
title: "durable storage deletes",
color: color4,
label: "Deletes",
value: durableObjectDeletesTotal,
limit: DURABLE_STORAGE_DELETE_LIMIT,
});
const chart6 = renderLineChart({
id: "durable-storage-amount",
title: "durable storage amount",
labels: dayLabels,
datasets: [
{
color: color1,
label: "Amount (byte)",
data: data.durableObjectStored,
},
],
});
const pichart6 = renderPieChart({
id: "durable-storage-amount-pie",
title: "durable storage amount",
color: color1,
label: "Amount",
value: durableObjectStoredMax,
limit: DURABLE_STORAGE_AMOUNT_LIMIT,
});
return `
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script>
<style>
h2 { font-size: 20px; }
.raw { margin-bottom: 40px; display: flex; gap: 20px; }
</style>
</head>
<body>
<h2>Worker (env: ${env})</h2>
<div class="raw">${chart1}${chart2}</div>
<div class="raw">${pichart1}${pichart2}</div>
<h2>Durable Object (env: ${env})</h2>
<div class="raw">${chart3}${chart4}</div>
<div class="raw">${pichart3}${pichart4}</div>
<h2>Durable Storage (all environments)</h2>
<div class="raw">${chart5}${chart6}</div>
<div class="raw">${pichart5a}${pichart5b}${pichart5c}${pichart6}</div>
</body>
</html>
`;
}
function renderLineChart(o: {
id: string;
title: string;
labels: string[];
datasets: {
color: string;
label: string;
data: number[];
}[];
}) {
return renderOneChart(o.id, o.title, {
type: "line",
data: {
labels: o.labels,
datasets: o.datasets.map((ds) => {
return {
borderColor: ds.color,
backgroundColor: ds.color,
label: ds.label,
data: ds.data,
};
}),
},
options: {
maintainAspectRatio: false,
},
});
}
function renderPieChart(o: {
id: string;
title: string;
color: string;
label: string;
value: number;
limit: number;
}) {
return renderOneChart(
o.id,
o.title,
{
type: "pie",
data: {
labels: [o.label],
datasets: [
{
borderColor: [o.color, "#eee"],
backgroundColor: [o.color, "#eee"],
data: [o.value, o.limit - o.value],
},
],
},
options: {
maintainAspectRatio: false,
},
},
true
);
}
function renderOneChart(
id: string,
title: string,
settings: any,
half = false
) {
return `
<div class="chart-container" style="position: relative; height:200px; width: ${
half ? 200 : 400
}px;">
<canvas id="${id}"></canvas>
</div>
<script>
(() => {
const ctx = document.getElementById('${id}').getContext('2d');
const chart = new Chart(ctx, ${JSON.stringify(settings)});
})();
</script>
`;
}
| 25.605442 | 87 | 0.61517 | 288 | 10 | 0 | 15 | 37 | 0 | 4 | 2 | 17 | 0 | 0 | 25.5 | 2,342 | 0.010675 | 0.015798 | 0 | 0 | 0 | 0.032258 | 0.274194 | 0.246869 | // https://developers.cloudflare.com/workers/platform/pricing
const WORKER_REQ_LIMIT = 1000 * 1000;
const WORKER_DURATION_LIMIT = 400 * 1000;
const DURABLE_OBJECT_REQ_LIMIT = 1000 * 1000;
const DURABLE_OBJECT_DURATION_LIMIT = 400 * 1000;
const DURABLE_STORAGE_READ_LIMIT = 1000 * 1000;
const DURABLE_STORAGE_WRITE_LIMIT = 1000 * 1000;
const DURABLE_STORAGE_DELETE_LIMIT = 1000 * 1000;
const DURABLE_STORAGE_AMOUNT_LIMIT = 1000 * 1000 * 1000;
/* Example usages of 'sum' are shown below:
sum(data.workerReqs);
sum(data.workerDurations);
sum(data.durableObjectReqs);
Math.max(sum(durableObjectWallTimes), sum(durableObjectCpuTimes));
sum(data.durableObjectReads);
sum(data.durableObjectWrites);
sum(data.durableObjectDeletes);
sum(data.durableObjectStored);
*/
function sum(array) {
return array.reduce((a, b) => a + b, 0);
}
const color1 = "#36a";
const color2 = "#a63";
const color3 = "#6a3";
const color4 = "#a36";
export function writeHTMLReport(env, data) {
const workerReqsTotal = sum(data.workerReqs);
const workerDurationsTotal = sum(data.workerDurations);
const durableObjectReqsTotal = sum(data.durableObjectReqs);
const durableObjectWallTimes = data.durableObjectWallTimes.map(
(microsecs) => ((microsecs / 1000 / 1000) * 128) / 1000
); // GB*s
const durableObjectCpuTimes = data.durableObjectCpuTimes.map(
(microsecs) => ((microsecs / 1000 / 1000) * 128) / 1000
); // GB*s
const durableObjectDurationTotal = Math.max(
sum(durableObjectWallTimes),
sum(durableObjectCpuTimes)
); // GB*s
const durableObjectReadsTotal = sum(data.durableObjectReads);
const durableObjectWritesTotal = sum(data.durableObjectWrites);
const durableObjectDeletesTotal = sum(data.durableObjectDeletes);
const durableObjectStoredMax = sum(data.durableObjectStored);
const dayLabels = data.days.map((d) =>
d.slice(5).replaceAll("0", "").replace("-", "/")
);
const chart1 = renderLineChart({
id: "worker-reqs",
title: "workers requests",
labels: dayLabels,
datasets: [
{
color: color1,
label: "Requests",
data: data.workerReqs,
},
],
});
const chart2 = renderLineChart({
id: "worker-durations",
title: "workers durations",
labels: dayLabels,
datasets: [
{
color: color1,
label: "Duration (GB * s)",
data: data.workerDurations,
},
],
});
const pichart1 = renderPieChart({
id: "worker-requests-pie",
title: "workers requests",
color: color1,
label: "Requests",
value: workerReqsTotal,
limit: WORKER_REQ_LIMIT,
});
const pichart2 = renderPieChart({
id: "worker-durations-pie",
title: "workers durations",
color: color1,
label: "Duration",
value: workerDurationsTotal,
limit: WORKER_DURATION_LIMIT,
});
const chart3 = renderLineChart({
id: "durable-object-requests",
title: "durable object requests",
labels: dayLabels,
datasets: [
{
color: color1,
label: "Requests",
data: data.durableObjectReqs,
},
],
});
const chart4 = renderLineChart({
id: "durable-object-durations",
title: "durable object durations",
labels: dayLabels,
datasets: [
{
color: color1,
label: "Wall times (GB * s)",
data: durableObjectWallTimes,
},
{
color: color2,
label: "CPU times (GB * s)",
data: durableObjectCpuTimes,
},
],
});
const pichart3 = renderPieChart({
id: "durable-object-requests-pie",
title: "durable object requests",
color: color1,
label: "Requests",
value: durableObjectReqsTotal,
limit: DURABLE_OBJECT_REQ_LIMIT,
});
const pichart4 = renderPieChart({
id: "durable-object-durations-pie",
title: "durable object durations",
color: color1,
label: "Duration",
value: durableObjectDurationTotal,
limit: DURABLE_OBJECT_DURATION_LIMIT,
});
const chart5 = renderLineChart({
id: "durable-storage-requests",
title: "durable storage requests",
labels: dayLabels,
datasets: [
{
color: color1,
label: "Reads (unit)",
data: data.durableObjectReads,
},
{
color: color3,
label: "Writes (unit)",
data: data.durableObjectWrites,
},
{
color: color4,
label: "Deletes (unit)",
data: data.durableObjectDeletes,
},
],
});
const pichart5a = renderPieChart({
id: "durable-storage-reads-pie",
title: "durable storage reads",
color: color1,
label: "Reads",
value: durableObjectReadsTotal,
limit: DURABLE_STORAGE_READ_LIMIT,
});
const pichart5b = renderPieChart({
id: "durable-storage-writes-pie",
title: "durable storage writes",
color: color3,
label: "Writes",
value: durableObjectWritesTotal,
limit: DURABLE_STORAGE_WRITE_LIMIT,
});
const pichart5c = renderPieChart({
id: "durable-storage-deletes-pie",
title: "durable storage deletes",
color: color4,
label: "Deletes",
value: durableObjectDeletesTotal,
limit: DURABLE_STORAGE_DELETE_LIMIT,
});
const chart6 = renderLineChart({
id: "durable-storage-amount",
title: "durable storage amount",
labels: dayLabels,
datasets: [
{
color: color1,
label: "Amount (byte)",
data: data.durableObjectStored,
},
],
});
const pichart6 = renderPieChart({
id: "durable-storage-amount-pie",
title: "durable storage amount",
color: color1,
label: "Amount",
value: durableObjectStoredMax,
limit: DURABLE_STORAGE_AMOUNT_LIMIT,
});
return `
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script>
<style>
h2 { font-size: 20px; }
.raw { margin-bottom: 40px; display: flex; gap: 20px; }
</style>
</head>
<body>
<h2>Worker (env: ${env})</h2>
<div class="raw">${chart1}${chart2}</div>
<div class="raw">${pichart1}${pichart2}</div>
<h2>Durable Object (env: ${env})</h2>
<div class="raw">${chart3}${chart4}</div>
<div class="raw">${pichart3}${pichart4}</div>
<h2>Durable Storage (all environments)</h2>
<div class="raw">${chart5}${chart6}</div>
<div class="raw">${pichart5a}${pichart5b}${pichart5c}${pichart6}</div>
</body>
</html>
`;
}
/* Example usages of 'renderLineChart' are shown below:
renderLineChart({
id: "worker-reqs",
title: "workers requests",
labels: dayLabels,
datasets: [
{
color: color1,
label: "Requests",
data: data.workerReqs,
},
],
});
renderLineChart({
id: "worker-durations",
title: "workers durations",
labels: dayLabels,
datasets: [
{
color: color1,
label: "Duration (GB * s)",
data: data.workerDurations,
},
],
});
renderLineChart({
id: "durable-object-requests",
title: "durable object requests",
labels: dayLabels,
datasets: [
{
color: color1,
label: "Requests",
data: data.durableObjectReqs,
},
],
});
renderLineChart({
id: "durable-object-durations",
title: "durable object durations",
labels: dayLabels,
datasets: [
{
color: color1,
label: "Wall times (GB * s)",
data: durableObjectWallTimes,
},
{
color: color2,
label: "CPU times (GB * s)",
data: durableObjectCpuTimes,
},
],
});
renderLineChart({
id: "durable-storage-requests",
title: "durable storage requests",
labels: dayLabels,
datasets: [
{
color: color1,
label: "Reads (unit)",
data: data.durableObjectReads,
},
{
color: color3,
label: "Writes (unit)",
data: data.durableObjectWrites,
},
{
color: color4,
label: "Deletes (unit)",
data: data.durableObjectDeletes,
},
],
});
renderLineChart({
id: "durable-storage-amount",
title: "durable storage amount",
labels: dayLabels,
datasets: [
{
color: color1,
label: "Amount (byte)",
data: data.durableObjectStored,
},
],
});
*/
function renderLineChart(o) {
return renderOneChart(o.id, o.title, {
type: "line",
data: {
labels: o.labels,
datasets: o.datasets.map((ds) => {
return {
borderColor: ds.color,
backgroundColor: ds.color,
label: ds.label,
data: ds.data,
};
}),
},
options: {
maintainAspectRatio: false,
},
});
}
/* Example usages of 'renderPieChart' are shown below:
renderPieChart({
id: "worker-requests-pie",
title: "workers requests",
color: color1,
label: "Requests",
value: workerReqsTotal,
limit: WORKER_REQ_LIMIT,
});
renderPieChart({
id: "worker-durations-pie",
title: "workers durations",
color: color1,
label: "Duration",
value: workerDurationsTotal,
limit: WORKER_DURATION_LIMIT,
});
renderPieChart({
id: "durable-object-requests-pie",
title: "durable object requests",
color: color1,
label: "Requests",
value: durableObjectReqsTotal,
limit: DURABLE_OBJECT_REQ_LIMIT,
});
renderPieChart({
id: "durable-object-durations-pie",
title: "durable object durations",
color: color1,
label: "Duration",
value: durableObjectDurationTotal,
limit: DURABLE_OBJECT_DURATION_LIMIT,
});
renderPieChart({
id: "durable-storage-reads-pie",
title: "durable storage reads",
color: color1,
label: "Reads",
value: durableObjectReadsTotal,
limit: DURABLE_STORAGE_READ_LIMIT,
});
renderPieChart({
id: "durable-storage-writes-pie",
title: "durable storage writes",
color: color3,
label: "Writes",
value: durableObjectWritesTotal,
limit: DURABLE_STORAGE_WRITE_LIMIT,
});
renderPieChart({
id: "durable-storage-deletes-pie",
title: "durable storage deletes",
color: color4,
label: "Deletes",
value: durableObjectDeletesTotal,
limit: DURABLE_STORAGE_DELETE_LIMIT,
});
renderPieChart({
id: "durable-storage-amount-pie",
title: "durable storage amount",
color: color1,
label: "Amount",
value: durableObjectStoredMax,
limit: DURABLE_STORAGE_AMOUNT_LIMIT,
});
*/
function renderPieChart(o) {
return renderOneChart(
o.id,
o.title,
{
type: "pie",
data: {
labels: [o.label],
datasets: [
{
borderColor: [o.color, "#eee"],
backgroundColor: [o.color, "#eee"],
data: [o.value, o.limit - o.value],
},
],
},
options: {
maintainAspectRatio: false,
},
},
true
);
}
/* Example usages of 'renderOneChart' are shown below:
renderOneChart(o.id, o.title, {
type: "line",
data: {
labels: o.labels,
datasets: o.datasets.map((ds) => {
return {
borderColor: ds.color,
backgroundColor: ds.color,
label: ds.label,
data: ds.data,
};
}),
},
options: {
maintainAspectRatio: false,
},
});
renderOneChart(o.id, o.title, {
type: "pie",
data: {
labels: [o.label],
datasets: [
{
borderColor: [o.color, "#eee"],
backgroundColor: [o.color, "#eee"],
data: [o.value, o.limit - o.value],
},
],
},
options: {
maintainAspectRatio: false,
},
}, true);
*/
function renderOneChart(
id,
title,
settings,
half = false
) {
return `
<div class="chart-container" style="position: relative; height:200px; width: ${
half ? 200 : 400
}px;">
<canvas id="${id}"></canvas>
</div>
<script>
(() => {
const ctx = document.getElementById('${id}').getContext('2d');
const chart = new Chart(ctx, ${JSON.stringify(settings)});
})();
</script>
`;
}
|
6edaf3d52b218cab800016af422eeb8cc16d7357 | 3,966 | ts | TypeScript | src/components/Timeline/Views/Wave/Utils.ts | WhiteWolf21/kotwel-frontend | a13203dd7b08075d5c4e42436a1925c5e0b01619 | [
"Apache-2.0"
] | null | null | null | src/components/Timeline/Views/Wave/Utils.ts | WhiteWolf21/kotwel-frontend | a13203dd7b08075d5c4e42436a1925c5e0b01619 | [
"Apache-2.0"
] | 1 | 2022-03-31T11:29:01.000Z | 2022-03-31T11:29:01.000Z | src/components/Timeline/Views/Wave/Utils.ts | WhiteWolf21/kotwel-frontend | a13203dd7b08075d5c4e42436a1925c5e0b01619 | [
"Apache-2.0"
] | 1 | 2022-03-06T09:21:58.000Z | 2022-03-06T09:21:58.000Z | /**
* Use formatTimeCallback to style the notch labels as you wish, such
* as with more detail as the number of pixels per second increases.
*
* Here we format as M:SS.frac, with M suppressed for times < 1 minute,
* and frac having 0, 1, or 2 digits as the zoom increases.
*
* Note that if you override the default function, you'll almost
* certainly want to override timeInterval, primaryLabelInterval and/or
* secondaryLabelInterval so they all work together.
*
* @param: seconds
* @param: pxPerSec
*/
export const formatTimeCallback = (seconds: number, pxPerSec: number) => {
const timeDate = new Date(seconds * 1000).toISOString();
const startIndex = (pxPerSec >= 25 * 10) ? 14 : (seconds >= 3600 ? 11 : 14);
const endIndex = (pxPerSec >= 25 * 10) ? 23 : 19;
const formatted = timeDate.substring(startIndex, endIndex);
return formatted;
// seconds = Number(seconds);
// const minutes = Math.floor(seconds / 60);
// seconds = seconds % 60;
// // fill up seconds with zeroes
// let secondsStr = Math.round(seconds).toString();
// if (pxPerSec >= 25 * 10) {
// secondsStr = seconds.toFixed(2);
// } else if (pxPerSec >= 25 * 1) {
// secondsStr = seconds.toFixed(1);
// }
// if (minutes > 0) {
// if (seconds < 10) {
// secondsStr = "0" + secondsStr;
// }
// return `${minutes}:${secondsStr}`;
// }
// return secondsStr;
};
/**
* Use timeInterval to set the period between notches, in seconds,
* adding notches as the number of pixels per second increases.
*
* Note that if you override the default function, you'll almost
* certainly want to override formatTimeCallback, primaryLabelInterval
* and/or secondaryLabelInterval so they all work together.
*
* @param: pxPerSec
*/
export const timeInterval = (pxPerSec: number) => {
let retval = 1;
if (pxPerSec >= 25 * 100) {
retval = 0.01;
} else if (pxPerSec >= 25 * 40) {
retval = 0.025;
} else if (pxPerSec >= 25 * 10) {
retval = 0.1;
} else if (pxPerSec >= 25 * 4) {
retval = 0.25;
} else if (pxPerSec >= 25) {
retval = 1;
} else if (pxPerSec * 5 >= 25) {
retval = 5;
} else if (pxPerSec * 15 >= 25) {
retval = 15;
} else {
retval = Math.ceil(0.5 / pxPerSec) * 60;
}
return retval;
};
/**
* Return the cadence of notches that get labels in the primary color.
* EG, return 2 if every 2nd notch should be labeled,
* return 10 if every 10th notch should be labeled, etc.
*
* Note that if you override the default function, you'll almost
* certainly want to override formatTimeCallback, primaryLabelInterval
* and/or secondaryLabelInterval so they all work together.
*
* @param pxPerSec
*/
export const primaryLabelInterval = (pxPerSec: number) => {
let retval = 1;
if (pxPerSec >= 25 * 100) {
retval = 10;
} else if (pxPerSec >= 25 * 40) {
retval = 4;
} else if (pxPerSec >= 25 * 10) {
retval = 10;
} else if (pxPerSec >= 25 * 4) {
retval = 4;
} else if (pxPerSec >= 25) {
retval = 1;
} else if (pxPerSec * 5 >= 25) {
retval = 5;
} else if (pxPerSec * 15 >= 25) {
retval = 15;
} else {
retval = Math.ceil(0.5 / pxPerSec) * 60;
}
return retval;
};
/**
* Return the cadence of notches to get labels in the secondary color.
* EG, return 2 if every 2nd notch should be labeled,
* return 10 if every 10th notch should be labeled, etc.
*
* Secondary labels are drawn after primary labels, so if
* you want to have labels every 10 seconds and another color labels
* every 60 seconds, the 60 second labels should be the secondaries.
*
* Note that if you override the default function, you'll almost
* certainly want to override formatTimeCallback, primaryLabelInterval
* and/or secondaryLabelInterval so they all work together.
*
* @param pxPerSec
*/
export const secondaryLabelInterval = (pxPerSec: number) => {
// draw one every 10s as an example
return Math.floor(10 / timeInterval(pxPerSec));
};
| 30.274809 | 78 | 0.652547 | 52 | 4 | 0 | 5 | 10 | 0 | 1 | 0 | 5 | 0 | 0 | 11 | 1,298 | 0.006934 | 0.007704 | 0 | 0 | 0 | 0 | 0.263158 | 0.21135 | /**
* Use formatTimeCallback to style the notch labels as you wish, such
* as with more detail as the number of pixels per second increases.
*
* Here we format as M:SS.frac, with M suppressed for times < 1 minute,
* and frac having 0, 1, or 2 digits as the zoom increases.
*
* Note that if you override the default function, you'll almost
* certainly want to override timeInterval, primaryLabelInterval and/or
* secondaryLabelInterval so they all work together.
*
* @param: seconds
* @param: pxPerSec
*/
export const formatTimeCallback = (seconds, pxPerSec) => {
const timeDate = new Date(seconds * 1000).toISOString();
const startIndex = (pxPerSec >= 25 * 10) ? 14 : (seconds >= 3600 ? 11 : 14);
const endIndex = (pxPerSec >= 25 * 10) ? 23 : 19;
const formatted = timeDate.substring(startIndex, endIndex);
return formatted;
// seconds = Number(seconds);
// const minutes = Math.floor(seconds / 60);
// seconds = seconds % 60;
// // fill up seconds with zeroes
// let secondsStr = Math.round(seconds).toString();
// if (pxPerSec >= 25 * 10) {
// secondsStr = seconds.toFixed(2);
// } else if (pxPerSec >= 25 * 1) {
// secondsStr = seconds.toFixed(1);
// }
// if (minutes > 0) {
// if (seconds < 10) {
// secondsStr = "0" + secondsStr;
// }
// return `${minutes}:${secondsStr}`;
// }
// return secondsStr;
};
/**
* Use timeInterval to set the period between notches, in seconds,
* adding notches as the number of pixels per second increases.
*
* Note that if you override the default function, you'll almost
* certainly want to override formatTimeCallback, primaryLabelInterval
* and/or secondaryLabelInterval so they all work together.
*
* @param: pxPerSec
*/
export /* Example usages of 'timeInterval' are shown below:
Math.floor(10 / timeInterval(pxPerSec));
*/
const timeInterval = (pxPerSec) => {
let retval = 1;
if (pxPerSec >= 25 * 100) {
retval = 0.01;
} else if (pxPerSec >= 25 * 40) {
retval = 0.025;
} else if (pxPerSec >= 25 * 10) {
retval = 0.1;
} else if (pxPerSec >= 25 * 4) {
retval = 0.25;
} else if (pxPerSec >= 25) {
retval = 1;
} else if (pxPerSec * 5 >= 25) {
retval = 5;
} else if (pxPerSec * 15 >= 25) {
retval = 15;
} else {
retval = Math.ceil(0.5 / pxPerSec) * 60;
}
return retval;
};
/**
* Return the cadence of notches that get labels in the primary color.
* EG, return 2 if every 2nd notch should be labeled,
* return 10 if every 10th notch should be labeled, etc.
*
* Note that if you override the default function, you'll almost
* certainly want to override formatTimeCallback, primaryLabelInterval
* and/or secondaryLabelInterval so they all work together.
*
* @param pxPerSec
*/
export const primaryLabelInterval = (pxPerSec) => {
let retval = 1;
if (pxPerSec >= 25 * 100) {
retval = 10;
} else if (pxPerSec >= 25 * 40) {
retval = 4;
} else if (pxPerSec >= 25 * 10) {
retval = 10;
} else if (pxPerSec >= 25 * 4) {
retval = 4;
} else if (pxPerSec >= 25) {
retval = 1;
} else if (pxPerSec * 5 >= 25) {
retval = 5;
} else if (pxPerSec * 15 >= 25) {
retval = 15;
} else {
retval = Math.ceil(0.5 / pxPerSec) * 60;
}
return retval;
};
/**
* Return the cadence of notches to get labels in the secondary color.
* EG, return 2 if every 2nd notch should be labeled,
* return 10 if every 10th notch should be labeled, etc.
*
* Secondary labels are drawn after primary labels, so if
* you want to have labels every 10 seconds and another color labels
* every 60 seconds, the 60 second labels should be the secondaries.
*
* Note that if you override the default function, you'll almost
* certainly want to override formatTimeCallback, primaryLabelInterval
* and/or secondaryLabelInterval so they all work together.
*
* @param pxPerSec
*/
export const secondaryLabelInterval = (pxPerSec) => {
// draw one every 10s as an example
return Math.floor(10 / timeInterval(pxPerSec));
};
|
4b6809336367809d6e2619e3f2bb0a688aa1ad4e | 2,731 | ts | TypeScript | src/pull-request-comment.ts | john-waitforit/action-eslint-leaderboard | cdd57d7ae06ab32b0463768242fc70bdbad1f9c9 | [
"MIT"
] | 1 | 2022-02-19T17:26:35.000Z | 2022-02-19T17:26:35.000Z | src/pull-request-comment.ts | john-waitforit/action-eslint-leaderboard | cdd57d7ae06ab32b0463768242fc70bdbad1f9c9 | [
"MIT"
] | 6 | 2022-02-21T10:57:30.000Z | 2022-03-28T14:25:08.000Z | src/pull-request-comment.ts | john-waitforit/action-eslint-leaderboard | cdd57d7ae06ab32b0463768242fc70bdbad1f9c9 | [
"MIT"
] | null | null | null | const TITLE = `## :shield: Eslint heroes`
const YOUR_SCORE = `### Your score[^1]:`
const PODIUM = `### Podium[^2]:`
const LEADERBOARD = `<summary> :bar_chart: Full leaderboard</summary>`
const FOOTNOTE = `[^1]: You earn \`+1\` point for each \`eslint-disable-next-line\` removed and \`+10\` for each \`eslint-disable\` (whole file) removed
[^2]: The leaderboard restarts every Mondays at 00:00`
interface LeaderboardEntry {
author: string
score: number
}
export const generatePrComment = (
allScores: Record<string, number>,
me: string,
pullRequestScore: number
): string => {
const sortedLeaderboardEntries = getSortedLeaderboardEntries(allScores)
return `${TITLE}
${YOUR_SCORE}
${generateYourScore(sortedLeaderboardEntries, me, pullRequestScore)}
${PODIUM}
${generatePodium(sortedLeaderboardEntries)}
---
<details>
${LEADERBOARD}
${generateLeaderboard(sortedLeaderboardEntries)}
</details>
${FOOTNOTE}
`
}
export const generatePodium = (
sortedLeaderboardEntries: LeaderboardEntry[]
): string => {
const first = formatLeaderboardEntry(sortedLeaderboardEntries[0])
const second = formatLeaderboardEntry(sortedLeaderboardEntries[1])
const third = formatLeaderboardEntry(sortedLeaderboardEntries[2])
return (
`:1st_place_medal:|:2nd_place_medal:|:3rd_place_medal:\n` +
`-|-|-\n` +
`${first}|${second}|${third}`
)
}
const formatLeaderboardEntry = (
leaderboardEntry: LeaderboardEntry | undefined
): string =>
leaderboardEntry
? `**${leaderboardEntry.author}** (${leaderboardEntry.score})`
: ``
export const generateYourScore = (
sortedLeaderboardEntries: LeaderboardEntry[],
me: string,
pullRequestScore: number
): string => {
const myLeaderboardIndex = sortedLeaderboardEntries.findIndex(
entry => entry.author === me
)
const weekScore =
myLeaderboardIndex === -1
? '?'
: sortedLeaderboardEntries[myLeaderboardIndex].score
const weekRank = myLeaderboardIndex === -1 ? '?' : myLeaderboardIndex + 1
const PR_SCORE = `- Points earned with this PR:`
const WEEK_SCORE = `- Points earned since the beginning of the week:`
const RANK = `- Rank:`
return `${PR_SCORE} \`${pullRequestScore}\`
${WEEK_SCORE} \`${weekScore}\`
${RANK} \`${weekRank}\``
}
export const generateLeaderboard = (
sortedLeaderboardEntries: LeaderboardEntry[]
): string => {
return sortedLeaderboardEntries
.map((entry, index) => `${index + 1}. ${formatLeaderboardEntry(entry)}`)
.join('\n')
}
export const getSortedLeaderboardEntries = (
allScores: Record<string, number>
): LeaderboardEntry[] =>
Object.entries(allScores)
.map(([author, score]) => ({
author,
score
}))
.sort((a, b) => (a.score > b.score ? -1 : 1))
| 26.514563 | 152 | 0.693519 | 83 | 10 | 0 | 16 | 21 | 2 | 5 | 0 | 15 | 1 | 0 | 5.4 | 762 | 0.034121 | 0.027559 | 0.002625 | 0.001312 | 0 | 0 | 0.306122 | 0.342941 | const TITLE = `## :shield: Eslint heroes`
const YOUR_SCORE = `### Your score[^1]:`
const PODIUM = `### Podium[^2]:`
const LEADERBOARD = `<summary> :bar_chart: Full leaderboard</summary>`
const FOOTNOTE = `[^1]: You earn \`+1\` point for each \`eslint-disable-next-line\` removed and \`+10\` for each \`eslint-disable\` (whole file) removed
[^2]: The leaderboard restarts every Mondays at 00:00`
interface LeaderboardEntry {
author
score
}
export const generatePrComment = (
allScores,
me,
pullRequestScore
) => {
const sortedLeaderboardEntries = getSortedLeaderboardEntries(allScores)
return `${TITLE}
${YOUR_SCORE}
${generateYourScore(sortedLeaderboardEntries, me, pullRequestScore)}
${PODIUM}
${generatePodium(sortedLeaderboardEntries)}
---
<details>
${LEADERBOARD}
${generateLeaderboard(sortedLeaderboardEntries)}
</details>
${FOOTNOTE}
`
}
export /* Example usages of 'generatePodium' are shown below:
generatePodium(sortedLeaderboardEntries);
*/
const generatePodium = (
sortedLeaderboardEntries
) => {
const first = formatLeaderboardEntry(sortedLeaderboardEntries[0])
const second = formatLeaderboardEntry(sortedLeaderboardEntries[1])
const third = formatLeaderboardEntry(sortedLeaderboardEntries[2])
return (
`:1st_place_medal:|:2nd_place_medal:|:3rd_place_medal:\n` +
`-|-|-\n` +
`${first}|${second}|${third}`
)
}
/* Example usages of 'formatLeaderboardEntry' are shown below:
formatLeaderboardEntry(sortedLeaderboardEntries[0]);
formatLeaderboardEntry(sortedLeaderboardEntries[1]);
formatLeaderboardEntry(sortedLeaderboardEntries[2]);
formatLeaderboardEntry(entry);
*/
const formatLeaderboardEntry = (
leaderboardEntry
) =>
leaderboardEntry
? `**${leaderboardEntry.author}** (${leaderboardEntry.score})`
: ``
export /* Example usages of 'generateYourScore' are shown below:
generateYourScore(sortedLeaderboardEntries, me, pullRequestScore);
*/
const generateYourScore = (
sortedLeaderboardEntries,
me,
pullRequestScore
) => {
const myLeaderboardIndex = sortedLeaderboardEntries.findIndex(
entry => entry.author === me
)
const weekScore =
myLeaderboardIndex === -1
? '?'
: sortedLeaderboardEntries[myLeaderboardIndex].score
const weekRank = myLeaderboardIndex === -1 ? '?' : myLeaderboardIndex + 1
const PR_SCORE = `- Points earned with this PR:`
const WEEK_SCORE = `- Points earned since the beginning of the week:`
const RANK = `- Rank:`
return `${PR_SCORE} \`${pullRequestScore}\`
${WEEK_SCORE} \`${weekScore}\`
${RANK} \`${weekRank}\``
}
export /* Example usages of 'generateLeaderboard' are shown below:
generateLeaderboard(sortedLeaderboardEntries);
*/
const generateLeaderboard = (
sortedLeaderboardEntries
) => {
return sortedLeaderboardEntries
.map((entry, index) => `${index + 1}. ${formatLeaderboardEntry(entry)}`)
.join('\n')
}
export /* Example usages of 'getSortedLeaderboardEntries' are shown below:
getSortedLeaderboardEntries(allScores);
*/
const getSortedLeaderboardEntries = (
allScores
) =>
Object.entries(allScores)
.map(([author, score]) => ({
author,
score
}))
.sort((a, b) => (a.score > b.score ? -1 : 1))
|
9232371dfa21a47ce397b18f5fd76f02d4b0d2b1 | 1,703 | ts | TypeScript | src/Iterable.ts | ClintH/ixfx | 71ae665900fdc607cd013e330fde3fb68c4db119 | [
"MIT"
] | 2 | 2022-03-25T13:13:57.000Z | 2022-03-25T13:29:10.000Z | src/Iterable.ts | ClintH/ixfx | 71ae665900fdc607cd013e330fde3fb68c4db119 | [
"MIT"
] | null | null | null | src/Iterable.ts | ClintH/ixfx | 71ae665900fdc607cd013e330fde3fb68c4db119 | [
"MIT"
] | null | null | null | type WithEvents = {
addEventListener(type: string, callbackfn: any): void;
removeEventListener(type: string, callbackfn: any): void;
}
export const isAsyncIterable = (v: any): v is AsyncIterable<any> => Symbol.asyncIterator in Object(v);
export const isIterable = (v: any): v is Iterable<any> => Symbol.iterator in Object(v);
export const eventsToIterable = <V>(eventSource: WithEvents, eventType: string): AsyncIterator<any, any, undefined> => {
const pullQueue: any[] = [];
const pushQueue: any[] = [];
let done = false;
const pushValue = async (args: any) => {
if (pullQueue.length !== 0) {
const resolver = pullQueue.shift();
resolver(...args);
} else {
pushQueue.push(args);
}
};
const pullValue = (): Promise<V> => {
return new Promise<V>((resolve) => {
if (pushQueue.length !== 0) {
const args = pushQueue.shift();
// @ts-ignore
resolve(...args);
} else {
pullQueue.push(resolve);
}
});
};
const handler = (...args: any) => {
pushValue(args);
};
eventSource.addEventListener(eventType, handler);
const r = {
next: async (): Promise<IteratorResult<V>> => {
if (done) return {done: true, value: undefined};
return {
done: false,
value: await pullValue()
};
},
return: async (): Promise<IteratorResult<V>> => {
done = true;
eventSource.removeEventListener(eventType, handler);
return {done: true, value: undefined};
},
throw: async (error: any): Promise<IteratorResult<V>> => {
done = true;
return {
done: true,
value: Promise.reject(error)
};
}
};
return r;
}; | 27.467742 | 120 | 0.587786 | 55 | 10 | 2 | 12 | 12 | 0 | 2 | 13 | 5 | 1 | 0 | 8.3 | 455 | 0.048352 | 0.026374 | 0 | 0.002198 | 0 | 0.361111 | 0.138889 | 0.367528 | type WithEvents = {
addEventListener(type, callbackfn);
removeEventListener(type, callbackfn);
}
export const isAsyncIterable = (v): v is AsyncIterable<any> => Symbol.asyncIterator in Object(v);
export const isIterable = (v): v is Iterable<any> => Symbol.iterator in Object(v);
export const eventsToIterable = <V>(eventSource, eventType) => {
const pullQueue = [];
const pushQueue = [];
let done = false;
/* Example usages of 'pushValue' are shown below:
pushValue(args);
*/
const pushValue = async (args) => {
if (pullQueue.length !== 0) {
const resolver = pullQueue.shift();
resolver(...args);
} else {
pushQueue.push(args);
}
};
/* Example usages of 'pullValue' are shown below:
pullValue();
*/
const pullValue = () => {
return new Promise<V>((resolve) => {
if (pushQueue.length !== 0) {
const args = pushQueue.shift();
// @ts-ignore
resolve(...args);
} else {
pullQueue.push(resolve);
}
});
};
/* Example usages of 'handler' are shown below:
eventSource.addEventListener(eventType, handler);
eventSource.removeEventListener(eventType, handler);
*/
const handler = (...args) => {
pushValue(args);
};
eventSource.addEventListener(eventType, handler);
const r = {
next: async () => {
if (done) return {done: true, value: undefined};
return {
done: false,
value: await pullValue()
};
},
return: async () => {
done = true;
eventSource.removeEventListener(eventType, handler);
return {done: true, value: undefined};
},
throw: async (error) => {
done = true;
return {
done: true,
value: Promise.reject(error)
};
}
};
return r;
}; |
926e0fa8004265b0ca1d35a24cc6e7abe374ce51 | 22,518 | ts | TypeScript | src/jsep.ts | threax/htmlrapier | 03db9f5ea71205527d8a3a8e8c2e10103f698b1c | [
"MIT"
] | 1 | 2022-01-19T18:11:24.000Z | 2022-01-19T18:11:24.000Z | src/jsep.ts | threax/htmlrapier | 03db9f5ea71205527d8a3a8e8c2e10103f698b1c | [
"MIT"
] | null | null | null | src/jsep.ts | threax/htmlrapier | 03db9f5ea71205527d8a3a8e8c2e10103f698b1c | [
"MIT"
] | null | null | null | // JavaScript Expression Parser (JSEP) 0.3.4
// JSEP may be freely distributed under the MIT License
// http://jsep.from.so/
'use strict';
// Node Types
// ----------
// This is the full set of types that any JSEP node can be.
// Store them here to save space when minified
const COMPOUND = 'Compound';
const IDENTIFIER = 'Identifier';
const MEMBER_EXP = 'MemberExpression';
const LITERAL = 'Literal';
const THIS_EXP = 'ThisExpression';
const CALL_EXP = 'CallExpression';
const UNARY_EXP = 'UnaryExpression';
const BINARY_EXP = 'BinaryExpression';
const LOGICAL_EXP = 'LogicalExpression';
const CONDITIONAL_EXP = 'ConditionalExpression';
const ARRAY_EXP = 'ArrayExpression';
export type ParsedType =
'Compound' |
'Identifier' |
'MemberExpression' |
'Literal' |
'ThisExpression' |
'CallExpression' |
'UnaryExpression' |
'BinaryExpression' |
'LogicalExpression' |
'ConditionalExpression' |
'ArrayExpression';
const PERIOD_CODE = 46; // '.'
const COMMA_CODE = 44; // ','
const SQUOTE_CODE = 39; // single quote
const DQUOTE_CODE = 34; // double quotes
const OPAREN_CODE = 40; // (
const CPAREN_CODE = 41; // )
const OBRACK_CODE = 91; // [
const CBRACK_CODE = 93; // ]
const QUMARK_CODE = 63; // ?
const SEMCOL_CODE = 59; // ;
const COLON_CODE = 58; // :
function throwError(message, index) {
var error: any = new Error(message + ' at character ' + index);
error.index = index;
error.description = message;
throw error;
};
// Operations
// ----------
var unary_ops = { '-': true, '!': true, '~': true, '+': true };
// Also use a map for the binary operations but set their values to their
// binary precedence for quick reference:
// see [Order of operations](http://en.wikipedia.org/wiki/Order_of_operations#Programming_language)
var binary_ops = {
'||': 1, '&&': 2, '|': 3, '^': 4, '&': 5,
'==': 6, '!=': 6, '===': 6, '!==': 6,
'<': 7, '>': 7, '<=': 7, '>=': 7,
'<<': 8, '>>': 8, '>>>': 8,
'+': 9, '-': 9,
'*': 10, '/': 10, '%': 10
};
export type OpTypes =
'||'
| '&&'
| '|'
| '^'
| '&'
| '=='
| '!='
| '==='
| '!=='
| '<'
| '>'
| '<='
| '>='
| '<<'
| '>>'
| '>>>'
| '+'
| '-'
| '*'
| '/'
| '%'
| '!';
// Get return the longest key length of any object
function getMaxKeyLen(obj) {
var max_len = 0, len;
for (var key in obj) {
if ((len = key.length) > max_len && obj.hasOwnProperty(key)) {
max_len = len;
}
}
return max_len;
};
var max_unop_len = getMaxKeyLen(unary_ops);
var max_binop_len = getMaxKeyLen(binary_ops);
// Literals
// ----------
// Store the values to return for the various literals we may encounter
var literals = {
'true': true,
'false': false,
'null': null
};
// Except for `this`, which is special. This could be changed to something like `'self'` as well
var this_str = 'this';
// Returns the precedence of a binary operator or `0` if it isn't a binary operator
function binaryPrecedence(op_val) {
return binary_ops[op_val] || 0;
};
// Utility function (gets called from multiple places)
// Also note that `a && b` and `a || b` are *logical* expressions, not binary expressions
function createBinaryExpression(operator, left, right) {
var type = (operator === '||' || operator === '&&') ? LOGICAL_EXP : BINARY_EXP;
return {
type: type,
operator: operator,
left: left,
right: right
};
};
// `ch` is a character code in the next three functions
function isDecimalDigit(ch) {
return (ch >= 48 && ch <= 57); // 0...9
};
function isIdentifierStart(ch) {
return (ch === 36) || (ch === 95) || // `$` and `_`
(ch >= 65 && ch <= 90) || // A...Z
(ch >= 97 && ch <= 122) || // a...z
(ch >= 128 && !binary_ops[String.fromCharCode(ch)]); // any non-ASCII that is not an operator
};
function isIdentifierPart(ch) {
return (ch === 36) || (ch === 95) || // `$` and `_`
(ch >= 65 && ch <= 90) || // A...Z
(ch >= 97 && ch <= 122) || // a...z
(ch >= 48 && ch <= 57) || // 0...9
(ch >= 128 && !binary_ops[String.fromCharCode(ch)]); // any non-ASCII that is not an operator
};
export interface JsepNode {
type: ParsedType;
}
export interface MemberExpression extends JsepNode {
computed?: boolean;
object?: Identifier;
property?: Identifier;
}
export interface Identifier extends JsepNode {
name?: string;
}
export interface Literal extends JsepNode {
value?: any;
raw?: string;
}
export interface CallExpression extends JsepNode {
arguments: JsepNode[];
callee: JsepNode;
}
export interface UnaryExpression extends JsepNode {
operator?: OpTypes;
argument?: JsepNode;
}
export interface BinaryExpression extends JsepNode {
operator?: OpTypes;
left?: JsepNode;
right?: JsepNode;
}
export interface LogicalExpression extends JsepNode {
operator?: OpTypes;
left?: JsepNode;
right?: JsepNode;
}
export interface Compound extends JsepNode {
body?: JsepNode[];
}
/**
* Parse
* @param expr a string with the passed in expression
*/
export function parse(expr: string): JsepNode {
// `index` stores the character number we are currently at while `length` is a constant
// All of the gobbles below will modify `index` as we move along
var index = 0,
charAtFunc = expr.charAt,
charCodeAtFunc = expr.charCodeAt,
exprI = function (i) { return charAtFunc.call(expr, i); },
exprICode = function (i) { return charCodeAtFunc.call(expr, i); },
length = expr.length,
// Push `index` up to the next non-space character
gobbleSpaces = function () {
var ch = exprICode(index);
// space or tab
while (ch === 32 || ch === 9 || ch === 10 || ch === 13) {
ch = exprICode(++index);
}
},
// The main parsing function. Much of this code is dedicated to ternary expressions
gobbleExpression = function () {
var test = gobbleBinaryExpression(),
consequent, alternate;
gobbleSpaces();
if (exprICode(index) === QUMARK_CODE) {
// Ternary expression: test ? consequent : alternate
index++;
consequent = gobbleExpression();
if (!consequent) {
throwError('Expected expression', index);
}
gobbleSpaces();
if (exprICode(index) === COLON_CODE) {
index++;
alternate = gobbleExpression();
if (!alternate) {
throwError('Expected expression', index);
}
return {
type: CONDITIONAL_EXP,
test: test,
consequent: consequent,
alternate: alternate
};
} else {
throwError('Expected :', index);
}
} else {
return test;
}
},
// Search for the operation portion of the string (e.g. `+`, `===`)
// Start by taking the longest possible binary operations (3 characters: `===`, `!==`, `>>>`)
// and move down from 3 to 2 to 1 character until a matching binary operation is found
// then, return that binary operation
gobbleBinaryOp = function () {
gobbleSpaces();
var biop, to_check = expr.substr(index, max_binop_len), tc_len = to_check.length;
while (tc_len > 0) {
// Don't accept a binary op when it is an identifier.
// Binary ops that start with a identifier-valid character must be followed
// by a non identifier-part valid character
if (binary_ops.hasOwnProperty(to_check) && (
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)))
)) {
index += tc_len;
return to_check;
}
to_check = to_check.substr(0, --tc_len);
}
return false;
},
// This function is responsible for gobbling an individual expression,
// e.g. `1`, `1+2`, `a+(b*2)-Math.sqrt(2)`
gobbleBinaryExpression = function () {
var ch_i, node, biop, prec, stack, biop_info, left, right, i, cur_biop;
// First, try to get the leftmost thing
// Then, check to see if there's a binary operator operating on that leftmost thing
left = gobbleToken();
biop = gobbleBinaryOp();
// If there wasn't a binary operator, just return the leftmost node
if (!biop) {
return left;
}
// Otherwise, we need to start a stack to properly place the binary operations in their
// precedence structure
biop_info = { value: biop, prec: binaryPrecedence(biop) };
right = gobbleToken();
if (!right) {
throwError("Expected expression after " + biop, index);
}
stack = [left, biop_info, right];
// Properly deal with precedence using [recursive descent](http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm)
while ((biop = gobbleBinaryOp())) {
prec = binaryPrecedence(biop);
if (prec === 0) {
break;
}
biop_info = { value: biop, prec: prec };
cur_biop = biop;
// Reduce: make a binary expression from the three topmost entries.
while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
right = stack.pop();
biop = stack.pop().value;
left = stack.pop();
node = createBinaryExpression(biop, left, right);
stack.push(node);
}
node = gobbleToken();
if (!node) {
throwError("Expected expression after " + cur_biop, index);
}
stack.push(biop_info, node);
}
i = stack.length - 1;
node = stack[i];
while (i > 1) {
node = createBinaryExpression(stack[i - 1].value, stack[i - 2], node);
i -= 2;
}
return node;
},
// An individual part of a binary expression:
// e.g. `foo.bar(baz)`, `1`, `"abc"`, `(a % 2)` (because it's in parenthesis)
gobbleToken = function () {
var ch, to_check, tc_len;
gobbleSpaces();
ch = exprICode(index);
if (isDecimalDigit(ch) || ch === PERIOD_CODE) {
// Char code 46 is a dot `.` which can start off a numeric literal
return gobbleNumericLiteral();
} else if (ch === SQUOTE_CODE || ch === DQUOTE_CODE) {
// Single or double quotes
return gobbleStringLiteral();
} else if (ch === OBRACK_CODE) {
return gobbleArray();
} else {
to_check = expr.substr(index, max_unop_len);
tc_len = to_check.length;
while (tc_len > 0) {
// Don't accept an unary op when it is an identifier.
// Unary ops that start with a identifier-valid character must be followed
// by a non identifier-part valid character
if (unary_ops.hasOwnProperty(to_check) && (
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)))
)) {
index += tc_len;
return {
type: UNARY_EXP,
operator: to_check,
argument: gobbleToken(),
prefix: true
};
}
to_check = to_check.substr(0, --tc_len);
}
if (isIdentifierStart(ch) || ch === OPAREN_CODE) { // open parenthesis
// `foo`, `bar.baz`
return gobbleVariable();
}
}
return false;
},
// Parse simple numeric literals: `12`, `3.4`, `.5`. Do this by using a string to
// keep track of everything in the numeric literal and then calling `parseFloat` on that string
gobbleNumericLiteral = function () {
var number = '', ch, chCode;
while (isDecimalDigit(exprICode(index))) {
number += exprI(index++);
}
if (exprICode(index) === PERIOD_CODE) { // can start with a decimal marker
number += exprI(index++);
while (isDecimalDigit(exprICode(index))) {
number += exprI(index++);
}
}
ch = exprI(index);
if (ch === 'e' || ch === 'E') { // exponent marker
number += exprI(index++);
ch = exprI(index);
if (ch === '+' || ch === '-') { // exponent sign
number += exprI(index++);
}
while (isDecimalDigit(exprICode(index))) { //exponent itself
number += exprI(index++);
}
if (!isDecimalDigit(exprICode(index - 1))) {
throwError('Expected exponent (' + number + exprI(index) + ')', index);
}
}
chCode = exprICode(index);
// Check to make sure this isn't a variable name that start with a number (123abc)
if (isIdentifierStart(chCode)) {
throwError('Variable names cannot start with a number (' +
number + exprI(index) + ')', index);
} else if (chCode === PERIOD_CODE) {
throwError('Unexpected period', index);
}
return {
type: LITERAL,
value: parseFloat(number),
raw: number
};
},
// Parses a string literal, staring with single or double quotes with basic support for escape codes
// e.g. `"hello world"`, `'this is\nJSEP'`
gobbleStringLiteral = function () {
var str = '', quote = exprI(index++), closed = false, ch;
while (index < length) {
ch = exprI(index++);
if (ch === quote) {
closed = true;
break;
} else if (ch === '\\') {
// Check for all of the common escape codes
ch = exprI(index++);
switch (ch) {
case 'n': str += '\n'; break;
case 'r': str += '\r'; break;
case 't': str += '\t'; break;
case 'b': str += '\b'; break;
case 'f': str += '\f'; break;
case 'v': str += '\x0B'; break;
default: str += ch;
}
} else {
str += ch;
}
}
if (!closed) {
throwError('Unclosed quote after "' + str + '"', index);
}
return {
type: LITERAL,
value: str,
raw: quote + str + quote
};
},
// Gobbles only identifiers
// e.g.: `foo`, `_value`, `$x1`
// Also, this function checks if that identifier is a literal:
// (e.g. `true`, `false`, `null`) or `this`
gobbleIdentifier = function () {
var ch = exprICode(index), start = index, identifier;
if (isIdentifierStart(ch)) {
index++;
} else {
throwError('Unexpected ' + exprI(index), index);
}
while (index < length) {
ch = exprICode(index);
if (isIdentifierPart(ch)) {
index++;
} else {
break;
}
}
identifier = expr.slice(start, index);
if (literals.hasOwnProperty(identifier)) {
return {
type: LITERAL,
value: literals[identifier],
raw: identifier
};
} else if (identifier === this_str) {
return { type: THIS_EXP };
} else {
return {
type: IDENTIFIER,
name: identifier
};
}
},
// Gobbles a list of arguments within the context of a function call
// or array literal. This function also assumes that the opening character
// `(` or `[` has already been gobbled, and gobbles expressions and commas
// until the terminator character `)` or `]` is encountered.
// e.g. `foo(bar, baz)`, `my_func()`, or `[bar, baz]`
gobbleArguments = function (termination) {
var ch_i, args = [], node, closed = false;
while (index < length) {
gobbleSpaces();
ch_i = exprICode(index);
if (ch_i === termination) { // done parsing
closed = true;
index++;
break;
} else if (ch_i === COMMA_CODE) { // between expressions
index++;
} else {
node = gobbleExpression();
if (!node || node.type === COMPOUND) {
throwError('Expected comma', index);
}
args.push(node);
}
}
if (!closed) {
throwError('Expected ' + String.fromCharCode(termination), index);
}
return args;
},
// Gobble a non-literal variable name. This variable name may include properties
// e.g. `foo`, `bar.baz`, `foo['bar'].baz`
// It also gobbles function calls:
// e.g. `Math.acos(obj.angle)`
gobbleVariable = function () {
var ch_i, node;
ch_i = exprICode(index);
if (ch_i === OPAREN_CODE) {
node = gobbleGroup();
} else {
node = gobbleIdentifier();
}
gobbleSpaces();
ch_i = exprICode(index);
while (ch_i === PERIOD_CODE || ch_i === OBRACK_CODE || ch_i === OPAREN_CODE) {
index++;
if (ch_i === PERIOD_CODE) {
gobbleSpaces();
node = {
type: MEMBER_EXP,
computed: false,
object: node,
property: gobbleIdentifier()
};
} else if (ch_i === OBRACK_CODE) {
node = {
type: MEMBER_EXP,
computed: true,
object: node,
property: gobbleExpression()
};
gobbleSpaces();
ch_i = exprICode(index);
if (ch_i !== CBRACK_CODE) {
throwError('Unclosed [', index);
}
index++;
} else if (ch_i === OPAREN_CODE) {
// A function call is being made; gobble all the arguments
node = {
type: CALL_EXP,
'arguments': gobbleArguments(CPAREN_CODE),
callee: node
};
}
gobbleSpaces();
ch_i = exprICode(index);
}
return node;
},
// Responsible for parsing a group of things within parentheses `()`
// This function assumes that it needs to gobble the opening parenthesis
// and then tries to gobble everything within that parenthesis, assuming
// that the next thing it should see is the close parenthesis. If not,
// then the expression probably doesn't have a `)`
gobbleGroup = function () {
index++;
var node = gobbleExpression();
gobbleSpaces();
if (exprICode(index) === CPAREN_CODE) {
index++;
return node;
} else {
throwError('Unclosed (', index);
}
},
// Responsible for parsing Array literals `[1, 2, 3]`
// This function assumes that it needs to gobble the opening bracket
// and then tries to gobble the expressions as arguments.
gobbleArray = function () {
index++;
return {
type: ARRAY_EXP,
elements: gobbleArguments(CBRACK_CODE)
};
},
nodes = [], ch_i, node;
while (index < length) {
ch_i = exprICode(index);
// Expressions can be separated by semicolons, commas, or just inferred without any
// separators
if (ch_i === SEMCOL_CODE || ch_i === COMMA_CODE) {
index++; // ignore separators
} else {
// Try to gobble each expression individually
if ((node = gobbleExpression())) {
nodes.push(node);
// If we weren't able to find a binary expression and are out of room, then
// the expression passed in probably has too much
} else if (index < length) {
throwError('Unexpected "' + exprI(index) + '"', index);
}
}
}
// If there's only one expression just try returning the expression
if (nodes.length === 1) {
return nodes[0];
} else {
return <any>{
type: COMPOUND,
body: nodes
};
}
}; | 34.53681 | 121 | 0.48499 | 496 | 22 | 0 | 14 | 90 | 18 | 21 | 3 | 4 | 11 | 0 | 30 | 5,357 | 0.00672 | 0.0168 | 0.00336 | 0.002053 | 0 | 0.020833 | 0.027778 | 0.249068 | // JavaScript Expression Parser (JSEP) 0.3.4
// JSEP may be freely distributed under the MIT License
// http://jsep.from.so/
'use strict';
// Node Types
// ----------
// This is the full set of types that any JSEP node can be.
// Store them here to save space when minified
const COMPOUND = 'Compound';
const IDENTIFIER = 'Identifier';
const MEMBER_EXP = 'MemberExpression';
const LITERAL = 'Literal';
const THIS_EXP = 'ThisExpression';
const CALL_EXP = 'CallExpression';
const UNARY_EXP = 'UnaryExpression';
const BINARY_EXP = 'BinaryExpression';
const LOGICAL_EXP = 'LogicalExpression';
const CONDITIONAL_EXP = 'ConditionalExpression';
const ARRAY_EXP = 'ArrayExpression';
export type ParsedType =
'Compound' |
'Identifier' |
'MemberExpression' |
'Literal' |
'ThisExpression' |
'CallExpression' |
'UnaryExpression' |
'BinaryExpression' |
'LogicalExpression' |
'ConditionalExpression' |
'ArrayExpression';
const PERIOD_CODE = 46; // '.'
const COMMA_CODE = 44; // ','
const SQUOTE_CODE = 39; // single quote
const DQUOTE_CODE = 34; // double quotes
const OPAREN_CODE = 40; // (
const CPAREN_CODE = 41; // )
const OBRACK_CODE = 91; // [
const CBRACK_CODE = 93; // ]
const QUMARK_CODE = 63; // ?
const SEMCOL_CODE = 59; // ;
const COLON_CODE = 58; // :
/* Example usages of 'throwError' are shown below:
throwError('Expected expression', index);
throwError('Expected :', index);
throwError("Expected expression after " + biop, index);
throwError("Expected expression after " + cur_biop, index);
throwError('Expected exponent (' + number + exprI(index) + ')', index);
throwError('Variable names cannot start with a number (' +
number + exprI(index) + ')', index);
throwError('Unexpected period', index);
throwError('Unclosed quote after "' + str + '"', index);
throwError('Unexpected ' + exprI(index), index);
throwError('Expected comma', index);
throwError('Expected ' + String.fromCharCode(termination), index);
throwError('Unclosed [', index);
throwError('Unclosed (', index);
throwError('Unexpected "' + exprI(index) + '"', index);
*/
function throwError(message, index) {
var error = new Error(message + ' at character ' + index);
error.index = index;
error.description = message;
throw error;
};
// Operations
// ----------
var unary_ops = { '-': true, '!': true, '~': true, '+': true };
// Also use a map for the binary operations but set their values to their
// binary precedence for quick reference:
// see [Order of operations](http://en.wikipedia.org/wiki/Order_of_operations#Programming_language)
var binary_ops = {
'||': 1, '&&': 2, '|': 3, '^': 4, '&': 5,
'==': 6, '!=': 6, '===': 6, '!==': 6,
'<': 7, '>': 7, '<=': 7, '>=': 7,
'<<': 8, '>>': 8, '>>>': 8,
'+': 9, '-': 9,
'*': 10, '/': 10, '%': 10
};
export type OpTypes =
'||'
| '&&'
| '|'
| '^'
| '&'
| '=='
| '!='
| '==='
| '!=='
| '<'
| '>'
| '<='
| '>='
| '<<'
| '>>'
| '>>>'
| '+'
| '-'
| '*'
| '/'
| '%'
| '!';
// Get return the longest key length of any object
/* Example usages of 'getMaxKeyLen' are shown below:
getMaxKeyLen(unary_ops);
getMaxKeyLen(binary_ops);
*/
function getMaxKeyLen(obj) {
var max_len = 0, len;
for (var key in obj) {
if ((len = key.length) > max_len && obj.hasOwnProperty(key)) {
max_len = len;
}
}
return max_len;
};
var max_unop_len = getMaxKeyLen(unary_ops);
var max_binop_len = getMaxKeyLen(binary_ops);
// Literals
// ----------
// Store the values to return for the various literals we may encounter
var literals = {
'true': true,
'false': false,
'null': null
};
// Except for `this`, which is special. This could be changed to something like `'self'` as well
var this_str = 'this';
// Returns the precedence of a binary operator or `0` if it isn't a binary operator
/* Example usages of 'binaryPrecedence' are shown below:
binaryPrecedence(biop);
prec = binaryPrecedence(biop);
*/
function binaryPrecedence(op_val) {
return binary_ops[op_val] || 0;
};
// Utility function (gets called from multiple places)
// Also note that `a && b` and `a || b` are *logical* expressions, not binary expressions
/* Example usages of 'createBinaryExpression' are shown below:
node = createBinaryExpression(biop, left, right);
node = createBinaryExpression(stack[i - 1].value, stack[i - 2], node);
*/
function createBinaryExpression(operator, left, right) {
var type = (operator === '||' || operator === '&&') ? LOGICAL_EXP : BINARY_EXP;
return {
type: type,
operator: operator,
left: left,
right: right
};
};
// `ch` is a character code in the next three functions
/* Example usages of 'isDecimalDigit' are shown below:
isDecimalDigit(ch) || ch === PERIOD_CODE;
isDecimalDigit(exprICode(index));
!isDecimalDigit(exprICode(index - 1));
*/
function isDecimalDigit(ch) {
return (ch >= 48 && ch <= 57); // 0...9
};
/* Example usages of 'isIdentifierStart' are shown below:
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)));
isIdentifierStart(ch) || ch === OPAREN_CODE;
isIdentifierStart(chCode);
isIdentifierStart(ch);
*/
function isIdentifierStart(ch) {
return (ch === 36) || (ch === 95) || // `$` and `_`
(ch >= 65 && ch <= 90) || // A...Z
(ch >= 97 && ch <= 122) || // a...z
(ch >= 128 && !binary_ops[String.fromCharCode(ch)]); // any non-ASCII that is not an operator
};
/* Example usages of 'isIdentifierPart' are shown below:
index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length));
isIdentifierPart(ch);
*/
function isIdentifierPart(ch) {
return (ch === 36) || (ch === 95) || // `$` and `_`
(ch >= 65 && ch <= 90) || // A...Z
(ch >= 97 && ch <= 122) || // a...z
(ch >= 48 && ch <= 57) || // 0...9
(ch >= 128 && !binary_ops[String.fromCharCode(ch)]); // any non-ASCII that is not an operator
};
export interface JsepNode {
type;
}
export interface MemberExpression extends JsepNode {
computed?;
object?;
property?;
}
export interface Identifier extends JsepNode {
name?;
}
export interface Literal extends JsepNode {
value?;
raw?;
}
export interface CallExpression extends JsepNode {
arguments;
callee;
}
export interface UnaryExpression extends JsepNode {
operator?;
argument?;
}
export interface BinaryExpression extends JsepNode {
operator?;
left?;
right?;
}
export interface LogicalExpression extends JsepNode {
operator?;
left?;
right?;
}
export interface Compound extends JsepNode {
body?;
}
/**
* Parse
* @param expr a string with the passed in expression
*/
export function parse(expr) {
// `index` stores the character number we are currently at while `length` is a constant
// All of the gobbles below will modify `index` as we move along
/* Example usages of 'index' are shown below:
;
new Error(message + ' at character ' + index);
error.index = index;
var index = 0;
exprICode(index);
ch = exprICode(++index);
exprICode(index) === QUMARK_CODE;
// Ternary expression: test ? consequent : alternate
index++;
throwError('Expected expression', index);
exprICode(index) === COLON_CODE;
index++;
throwError('Expected :', index);
expr.substr(index, max_binop_len);
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)));
index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length));
index += tc_len;
throwError("Expected expression after " + biop, index);
throwError("Expected expression after " + cur_biop, index);
ch = exprICode(index);
to_check = expr.substr(index, max_unop_len);
isDecimalDigit(exprICode(index));
number += exprI(index++);
exprICode(index) === PERIOD_CODE;
ch = exprI(index);
!isDecimalDigit(exprICode(index - 1));
throwError('Expected exponent (' + number + exprI(index) + ')', index);
chCode = exprICode(index);
throwError('Variable names cannot start with a number (' +
number + exprI(index) + ')', index);
throwError('Unexpected period', index);
exprI(index++);
index < length;
ch = exprI(index++);
// Check for all of the common escape codes
ch = exprI(index++);
throwError('Unclosed quote after "' + str + '"', index);
var start = index;
throwError('Unexpected ' + exprI(index), index);
identifier = expr.slice(start, index);
ch_i = exprICode(index);
throwError('Expected comma', index);
throwError('Expected ' + String.fromCharCode(termination), index);
throwError('Unclosed [', index);
exprICode(index) === CPAREN_CODE;
throwError('Unclosed (', index);
throwError('Unexpected "' + exprI(index) + '"', index);
*/
/* Example usages of 'index' are shown below:
;
new Error(message + ' at character ' + index);
error.index = index;
var index = 0;
exprICode(index);
ch = exprICode(++index);
exprICode(index) === QUMARK_CODE;
// Ternary expression: test ? consequent : alternate
index++;
throwError('Expected expression', index);
exprICode(index) === COLON_CODE;
index++;
throwError('Expected :', index);
expr.substr(index, max_binop_len);
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)));
index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length));
index += tc_len;
throwError("Expected expression after " + biop, index);
throwError("Expected expression after " + cur_biop, index);
ch = exprICode(index);
to_check = expr.substr(index, max_unop_len);
isDecimalDigit(exprICode(index));
number += exprI(index++);
exprICode(index) === PERIOD_CODE;
ch = exprI(index);
!isDecimalDigit(exprICode(index - 1));
throwError('Expected exponent (' + number + exprI(index) + ')', index);
chCode = exprICode(index);
throwError('Variable names cannot start with a number (' +
number + exprI(index) + ')', index);
throwError('Unexpected period', index);
exprI(index++);
index < length;
ch = exprI(index++);
// Check for all of the common escape codes
ch = exprI(index++);
throwError('Unclosed quote after "' + str + '"', index);
var start = index;
throwError('Unexpected ' + exprI(index), index);
identifier = expr.slice(start, index);
ch_i = exprICode(index);
throwError('Expected comma', index);
throwError('Expected ' + String.fromCharCode(termination), index);
throwError('Unclosed [', index);
exprICode(index) === CPAREN_CODE;
throwError('Unclosed (', index);
throwError('Unexpected "' + exprI(index) + '"', index);
*/
/* Example usages of 'index' are shown below:
;
new Error(message + ' at character ' + index);
error.index = index;
var index = 0;
exprICode(index);
ch = exprICode(++index);
exprICode(index) === QUMARK_CODE;
// Ternary expression: test ? consequent : alternate
index++;
throwError('Expected expression', index);
exprICode(index) === COLON_CODE;
index++;
throwError('Expected :', index);
expr.substr(index, max_binop_len);
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)));
index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length));
index += tc_len;
throwError("Expected expression after " + biop, index);
throwError("Expected expression after " + cur_biop, index);
ch = exprICode(index);
to_check = expr.substr(index, max_unop_len);
isDecimalDigit(exprICode(index));
number += exprI(index++);
exprICode(index) === PERIOD_CODE;
ch = exprI(index);
!isDecimalDigit(exprICode(index - 1));
throwError('Expected exponent (' + number + exprI(index) + ')', index);
chCode = exprICode(index);
throwError('Variable names cannot start with a number (' +
number + exprI(index) + ')', index);
throwError('Unexpected period', index);
exprI(index++);
index < length;
ch = exprI(index++);
// Check for all of the common escape codes
ch = exprI(index++);
throwError('Unclosed quote after "' + str + '"', index);
var start = index;
throwError('Unexpected ' + exprI(index), index);
identifier = expr.slice(start, index);
ch_i = exprICode(index);
throwError('Expected comma', index);
throwError('Expected ' + String.fromCharCode(termination), index);
throwError('Unclosed [', index);
exprICode(index) === CPAREN_CODE;
throwError('Unclosed (', index);
throwError('Unexpected "' + exprI(index) + '"', index);
*/
/* Example usages of 'index' are shown below:
;
new Error(message + ' at character ' + index);
error.index = index;
var index = 0;
exprICode(index);
ch = exprICode(++index);
exprICode(index) === QUMARK_CODE;
// Ternary expression: test ? consequent : alternate
index++;
throwError('Expected expression', index);
exprICode(index) === COLON_CODE;
index++;
throwError('Expected :', index);
expr.substr(index, max_binop_len);
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)));
index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length));
index += tc_len;
throwError("Expected expression after " + biop, index);
throwError("Expected expression after " + cur_biop, index);
ch = exprICode(index);
to_check = expr.substr(index, max_unop_len);
isDecimalDigit(exprICode(index));
number += exprI(index++);
exprICode(index) === PERIOD_CODE;
ch = exprI(index);
!isDecimalDigit(exprICode(index - 1));
throwError('Expected exponent (' + number + exprI(index) + ')', index);
chCode = exprICode(index);
throwError('Variable names cannot start with a number (' +
number + exprI(index) + ')', index);
throwError('Unexpected period', index);
exprI(index++);
index < length;
ch = exprI(index++);
// Check for all of the common escape codes
ch = exprI(index++);
throwError('Unclosed quote after "' + str + '"', index);
var start = index;
throwError('Unexpected ' + exprI(index), index);
identifier = expr.slice(start, index);
ch_i = exprICode(index);
throwError('Expected comma', index);
throwError('Expected ' + String.fromCharCode(termination), index);
throwError('Unclosed [', index);
exprICode(index) === CPAREN_CODE;
throwError('Unclosed (', index);
throwError('Unexpected "' + exprI(index) + '"', index);
*/
/* Example usages of 'index' are shown below:
;
new Error(message + ' at character ' + index);
error.index = index;
var index = 0;
exprICode(index);
ch = exprICode(++index);
exprICode(index) === QUMARK_CODE;
// Ternary expression: test ? consequent : alternate
index++;
throwError('Expected expression', index);
exprICode(index) === COLON_CODE;
index++;
throwError('Expected :', index);
expr.substr(index, max_binop_len);
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)));
index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length));
index += tc_len;
throwError("Expected expression after " + biop, index);
throwError("Expected expression after " + cur_biop, index);
ch = exprICode(index);
to_check = expr.substr(index, max_unop_len);
isDecimalDigit(exprICode(index));
number += exprI(index++);
exprICode(index) === PERIOD_CODE;
ch = exprI(index);
!isDecimalDigit(exprICode(index - 1));
throwError('Expected exponent (' + number + exprI(index) + ')', index);
chCode = exprICode(index);
throwError('Variable names cannot start with a number (' +
number + exprI(index) + ')', index);
throwError('Unexpected period', index);
exprI(index++);
index < length;
ch = exprI(index++);
// Check for all of the common escape codes
ch = exprI(index++);
throwError('Unclosed quote after "' + str + '"', index);
var start = index;
throwError('Unexpected ' + exprI(index), index);
identifier = expr.slice(start, index);
ch_i = exprICode(index);
throwError('Expected comma', index);
throwError('Expected ' + String.fromCharCode(termination), index);
throwError('Unclosed [', index);
exprICode(index) === CPAREN_CODE;
throwError('Unclosed (', index);
throwError('Unexpected "' + exprI(index) + '"', index);
*/
/* Example usages of 'index' are shown below:
;
new Error(message + ' at character ' + index);
error.index = index;
var index = 0;
exprICode(index);
ch = exprICode(++index);
exprICode(index) === QUMARK_CODE;
// Ternary expression: test ? consequent : alternate
index++;
throwError('Expected expression', index);
exprICode(index) === COLON_CODE;
index++;
throwError('Expected :', index);
expr.substr(index, max_binop_len);
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)));
index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length));
index += tc_len;
throwError("Expected expression after " + biop, index);
throwError("Expected expression after " + cur_biop, index);
ch = exprICode(index);
to_check = expr.substr(index, max_unop_len);
isDecimalDigit(exprICode(index));
number += exprI(index++);
exprICode(index) === PERIOD_CODE;
ch = exprI(index);
!isDecimalDigit(exprICode(index - 1));
throwError('Expected exponent (' + number + exprI(index) + ')', index);
chCode = exprICode(index);
throwError('Variable names cannot start with a number (' +
number + exprI(index) + ')', index);
throwError('Unexpected period', index);
exprI(index++);
index < length;
ch = exprI(index++);
// Check for all of the common escape codes
ch = exprI(index++);
throwError('Unclosed quote after "' + str + '"', index);
var start = index;
throwError('Unexpected ' + exprI(index), index);
identifier = expr.slice(start, index);
ch_i = exprICode(index);
throwError('Expected comma', index);
throwError('Expected ' + String.fromCharCode(termination), index);
throwError('Unclosed [', index);
exprICode(index) === CPAREN_CODE;
throwError('Unclosed (', index);
throwError('Unexpected "' + exprI(index) + '"', index);
*/
/* Example usages of 'index' are shown below:
;
new Error(message + ' at character ' + index);
error.index = index;
var index = 0;
exprICode(index);
ch = exprICode(++index);
exprICode(index) === QUMARK_CODE;
// Ternary expression: test ? consequent : alternate
index++;
throwError('Expected expression', index);
exprICode(index) === COLON_CODE;
index++;
throwError('Expected :', index);
expr.substr(index, max_binop_len);
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)));
index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length));
index += tc_len;
throwError("Expected expression after " + biop, index);
throwError("Expected expression after " + cur_biop, index);
ch = exprICode(index);
to_check = expr.substr(index, max_unop_len);
isDecimalDigit(exprICode(index));
number += exprI(index++);
exprICode(index) === PERIOD_CODE;
ch = exprI(index);
!isDecimalDigit(exprICode(index - 1));
throwError('Expected exponent (' + number + exprI(index) + ')', index);
chCode = exprICode(index);
throwError('Variable names cannot start with a number (' +
number + exprI(index) + ')', index);
throwError('Unexpected period', index);
exprI(index++);
index < length;
ch = exprI(index++);
// Check for all of the common escape codes
ch = exprI(index++);
throwError('Unclosed quote after "' + str + '"', index);
var start = index;
throwError('Unexpected ' + exprI(index), index);
identifier = expr.slice(start, index);
ch_i = exprICode(index);
throwError('Expected comma', index);
throwError('Expected ' + String.fromCharCode(termination), index);
throwError('Unclosed [', index);
exprICode(index) === CPAREN_CODE;
throwError('Unclosed (', index);
throwError('Unexpected "' + exprI(index) + '"', index);
*/
/* Example usages of 'index' are shown below:
;
new Error(message + ' at character ' + index);
error.index = index;
var index = 0;
exprICode(index);
ch = exprICode(++index);
exprICode(index) === QUMARK_CODE;
// Ternary expression: test ? consequent : alternate
index++;
throwError('Expected expression', index);
exprICode(index) === COLON_CODE;
index++;
throwError('Expected :', index);
expr.substr(index, max_binop_len);
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)));
index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length));
index += tc_len;
throwError("Expected expression after " + biop, index);
throwError("Expected expression after " + cur_biop, index);
ch = exprICode(index);
to_check = expr.substr(index, max_unop_len);
isDecimalDigit(exprICode(index));
number += exprI(index++);
exprICode(index) === PERIOD_CODE;
ch = exprI(index);
!isDecimalDigit(exprICode(index - 1));
throwError('Expected exponent (' + number + exprI(index) + ')', index);
chCode = exprICode(index);
throwError('Variable names cannot start with a number (' +
number + exprI(index) + ')', index);
throwError('Unexpected period', index);
exprI(index++);
index < length;
ch = exprI(index++);
// Check for all of the common escape codes
ch = exprI(index++);
throwError('Unclosed quote after "' + str + '"', index);
var start = index;
throwError('Unexpected ' + exprI(index), index);
identifier = expr.slice(start, index);
ch_i = exprICode(index);
throwError('Expected comma', index);
throwError('Expected ' + String.fromCharCode(termination), index);
throwError('Unclosed [', index);
exprICode(index) === CPAREN_CODE;
throwError('Unclosed (', index);
throwError('Unexpected "' + exprI(index) + '"', index);
*/
/* Example usages of 'index' are shown below:
;
new Error(message + ' at character ' + index);
error.index = index;
var index = 0;
exprICode(index);
ch = exprICode(++index);
exprICode(index) === QUMARK_CODE;
// Ternary expression: test ? consequent : alternate
index++;
throwError('Expected expression', index);
exprICode(index) === COLON_CODE;
index++;
throwError('Expected :', index);
expr.substr(index, max_binop_len);
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)));
index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length));
index += tc_len;
throwError("Expected expression after " + biop, index);
throwError("Expected expression after " + cur_biop, index);
ch = exprICode(index);
to_check = expr.substr(index, max_unop_len);
isDecimalDigit(exprICode(index));
number += exprI(index++);
exprICode(index) === PERIOD_CODE;
ch = exprI(index);
!isDecimalDigit(exprICode(index - 1));
throwError('Expected exponent (' + number + exprI(index) + ')', index);
chCode = exprICode(index);
throwError('Variable names cannot start with a number (' +
number + exprI(index) + ')', index);
throwError('Unexpected period', index);
exprI(index++);
index < length;
ch = exprI(index++);
// Check for all of the common escape codes
ch = exprI(index++);
throwError('Unclosed quote after "' + str + '"', index);
var start = index;
throwError('Unexpected ' + exprI(index), index);
identifier = expr.slice(start, index);
ch_i = exprICode(index);
throwError('Expected comma', index);
throwError('Expected ' + String.fromCharCode(termination), index);
throwError('Unclosed [', index);
exprICode(index) === CPAREN_CODE;
throwError('Unclosed (', index);
throwError('Unexpected "' + exprI(index) + '"', index);
*/
/* Example usages of 'index' are shown below:
;
new Error(message + ' at character ' + index);
error.index = index;
var index = 0;
exprICode(index);
ch = exprICode(++index);
exprICode(index) === QUMARK_CODE;
// Ternary expression: test ? consequent : alternate
index++;
throwError('Expected expression', index);
exprICode(index) === COLON_CODE;
index++;
throwError('Expected :', index);
expr.substr(index, max_binop_len);
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)));
index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length));
index += tc_len;
throwError("Expected expression after " + biop, index);
throwError("Expected expression after " + cur_biop, index);
ch = exprICode(index);
to_check = expr.substr(index, max_unop_len);
isDecimalDigit(exprICode(index));
number += exprI(index++);
exprICode(index) === PERIOD_CODE;
ch = exprI(index);
!isDecimalDigit(exprICode(index - 1));
throwError('Expected exponent (' + number + exprI(index) + ')', index);
chCode = exprICode(index);
throwError('Variable names cannot start with a number (' +
number + exprI(index) + ')', index);
throwError('Unexpected period', index);
exprI(index++);
index < length;
ch = exprI(index++);
// Check for all of the common escape codes
ch = exprI(index++);
throwError('Unclosed quote after "' + str + '"', index);
var start = index;
throwError('Unexpected ' + exprI(index), index);
identifier = expr.slice(start, index);
ch_i = exprICode(index);
throwError('Expected comma', index);
throwError('Expected ' + String.fromCharCode(termination), index);
throwError('Unclosed [', index);
exprICode(index) === CPAREN_CODE;
throwError('Unclosed (', index);
throwError('Unexpected "' + exprI(index) + '"', index);
*/
/* Example usages of 'index' are shown below:
;
new Error(message + ' at character ' + index);
error.index = index;
var index = 0;
exprICode(index);
ch = exprICode(++index);
exprICode(index) === QUMARK_CODE;
// Ternary expression: test ? consequent : alternate
index++;
throwError('Expected expression', index);
exprICode(index) === COLON_CODE;
index++;
throwError('Expected :', index);
expr.substr(index, max_binop_len);
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)));
index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length));
index += tc_len;
throwError("Expected expression after " + biop, index);
throwError("Expected expression after " + cur_biop, index);
ch = exprICode(index);
to_check = expr.substr(index, max_unop_len);
isDecimalDigit(exprICode(index));
number += exprI(index++);
exprICode(index) === PERIOD_CODE;
ch = exprI(index);
!isDecimalDigit(exprICode(index - 1));
throwError('Expected exponent (' + number + exprI(index) + ')', index);
chCode = exprICode(index);
throwError('Variable names cannot start with a number (' +
number + exprI(index) + ')', index);
throwError('Unexpected period', index);
exprI(index++);
index < length;
ch = exprI(index++);
// Check for all of the common escape codes
ch = exprI(index++);
throwError('Unclosed quote after "' + str + '"', index);
var start = index;
throwError('Unexpected ' + exprI(index), index);
identifier = expr.slice(start, index);
ch_i = exprICode(index);
throwError('Expected comma', index);
throwError('Expected ' + String.fromCharCode(termination), index);
throwError('Unclosed [', index);
exprICode(index) === CPAREN_CODE;
throwError('Unclosed (', index);
throwError('Unexpected "' + exprI(index) + '"', index);
*/
/* Example usages of 'index' are shown below:
;
new Error(message + ' at character ' + index);
error.index = index;
var index = 0;
exprICode(index);
ch = exprICode(++index);
exprICode(index) === QUMARK_CODE;
// Ternary expression: test ? consequent : alternate
index++;
throwError('Expected expression', index);
exprICode(index) === COLON_CODE;
index++;
throwError('Expected :', index);
expr.substr(index, max_binop_len);
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)));
index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length));
index += tc_len;
throwError("Expected expression after " + biop, index);
throwError("Expected expression after " + cur_biop, index);
ch = exprICode(index);
to_check = expr.substr(index, max_unop_len);
isDecimalDigit(exprICode(index));
number += exprI(index++);
exprICode(index) === PERIOD_CODE;
ch = exprI(index);
!isDecimalDigit(exprICode(index - 1));
throwError('Expected exponent (' + number + exprI(index) + ')', index);
chCode = exprICode(index);
throwError('Variable names cannot start with a number (' +
number + exprI(index) + ')', index);
throwError('Unexpected period', index);
exprI(index++);
index < length;
ch = exprI(index++);
// Check for all of the common escape codes
ch = exprI(index++);
throwError('Unclosed quote after "' + str + '"', index);
var start = index;
throwError('Unexpected ' + exprI(index), index);
identifier = expr.slice(start, index);
ch_i = exprICode(index);
throwError('Expected comma', index);
throwError('Expected ' + String.fromCharCode(termination), index);
throwError('Unclosed [', index);
exprICode(index) === CPAREN_CODE;
throwError('Unclosed (', index);
throwError('Unexpected "' + exprI(index) + '"', index);
*/
/* Example usages of 'index' are shown below:
;
new Error(message + ' at character ' + index);
error.index = index;
var index = 0;
exprICode(index);
ch = exprICode(++index);
exprICode(index) === QUMARK_CODE;
// Ternary expression: test ? consequent : alternate
index++;
throwError('Expected expression', index);
exprICode(index) === COLON_CODE;
index++;
throwError('Expected :', index);
expr.substr(index, max_binop_len);
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)));
index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length));
index += tc_len;
throwError("Expected expression after " + biop, index);
throwError("Expected expression after " + cur_biop, index);
ch = exprICode(index);
to_check = expr.substr(index, max_unop_len);
isDecimalDigit(exprICode(index));
number += exprI(index++);
exprICode(index) === PERIOD_CODE;
ch = exprI(index);
!isDecimalDigit(exprICode(index - 1));
throwError('Expected exponent (' + number + exprI(index) + ')', index);
chCode = exprICode(index);
throwError('Variable names cannot start with a number (' +
number + exprI(index) + ')', index);
throwError('Unexpected period', index);
exprI(index++);
index < length;
ch = exprI(index++);
// Check for all of the common escape codes
ch = exprI(index++);
throwError('Unclosed quote after "' + str + '"', index);
var start = index;
throwError('Unexpected ' + exprI(index), index);
identifier = expr.slice(start, index);
ch_i = exprICode(index);
throwError('Expected comma', index);
throwError('Expected ' + String.fromCharCode(termination), index);
throwError('Unclosed [', index);
exprICode(index) === CPAREN_CODE;
throwError('Unclosed (', index);
throwError('Unexpected "' + exprI(index) + '"', index);
*/
/* Example usages of 'index' are shown below:
;
new Error(message + ' at character ' + index);
error.index = index;
var index = 0;
exprICode(index);
ch = exprICode(++index);
exprICode(index) === QUMARK_CODE;
// Ternary expression: test ? consequent : alternate
index++;
throwError('Expected expression', index);
exprICode(index) === COLON_CODE;
index++;
throwError('Expected :', index);
expr.substr(index, max_binop_len);
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)));
index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length));
index += tc_len;
throwError("Expected expression after " + biop, index);
throwError("Expected expression after " + cur_biop, index);
ch = exprICode(index);
to_check = expr.substr(index, max_unop_len);
isDecimalDigit(exprICode(index));
number += exprI(index++);
exprICode(index) === PERIOD_CODE;
ch = exprI(index);
!isDecimalDigit(exprICode(index - 1));
throwError('Expected exponent (' + number + exprI(index) + ')', index);
chCode = exprICode(index);
throwError('Variable names cannot start with a number (' +
number + exprI(index) + ')', index);
throwError('Unexpected period', index);
exprI(index++);
index < length;
ch = exprI(index++);
// Check for all of the common escape codes
ch = exprI(index++);
throwError('Unclosed quote after "' + str + '"', index);
var start = index;
throwError('Unexpected ' + exprI(index), index);
identifier = expr.slice(start, index);
ch_i = exprICode(index);
throwError('Expected comma', index);
throwError('Expected ' + String.fromCharCode(termination), index);
throwError('Unclosed [', index);
exprICode(index) === CPAREN_CODE;
throwError('Unclosed (', index);
throwError('Unexpected "' + exprI(index) + '"', index);
*/
var index = 0,
charAtFunc = expr.charAt,
charCodeAtFunc = expr.charCodeAt,
exprI = function (i) { return charAtFunc.call(expr, i); },
exprICode = function (i) { return charCodeAtFunc.call(expr, i); },
length = expr.length,
// Push `index` up to the next non-space character
gobbleSpaces = function () {
var ch = exprICode(index);
// space or tab
while (ch === 32 || ch === 9 || ch === 10 || ch === 13) {
ch = exprICode(++index);
}
},
// The main parsing function. Much of this code is dedicated to ternary expressions
gobbleExpression = function () {
var test = gobbleBinaryExpression(),
consequent, alternate;
gobbleSpaces();
if (exprICode(index) === QUMARK_CODE) {
// Ternary expression: test ? consequent : alternate
index++;
consequent = gobbleExpression();
if (!consequent) {
throwError('Expected expression', index);
}
gobbleSpaces();
if (exprICode(index) === COLON_CODE) {
index++;
alternate = gobbleExpression();
if (!alternate) {
throwError('Expected expression', index);
}
return {
type: CONDITIONAL_EXP,
test: test,
consequent: consequent,
alternate: alternate
};
} else {
throwError('Expected :', index);
}
} else {
return test;
}
},
// Search for the operation portion of the string (e.g. `+`, `===`)
// Start by taking the longest possible binary operations (3 characters: `===`, `!==`, `>>>`)
// and move down from 3 to 2 to 1 character until a matching binary operation is found
// then, return that binary operation
gobbleBinaryOp = function () {
gobbleSpaces();
var biop, to_check = expr.substr(index, max_binop_len), tc_len = to_check.length;
while (tc_len > 0) {
// Don't accept a binary op when it is an identifier.
// Binary ops that start with a identifier-valid character must be followed
// by a non identifier-part valid character
if (binary_ops.hasOwnProperty(to_check) && (
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)))
)) {
index += tc_len;
return to_check;
}
to_check = to_check.substr(0, --tc_len);
}
return false;
},
// This function is responsible for gobbling an individual expression,
// e.g. `1`, `1+2`, `a+(b*2)-Math.sqrt(2)`
gobbleBinaryExpression = function () {
var ch_i, node, biop, prec, stack, biop_info, left, right, i, cur_biop;
// First, try to get the leftmost thing
// Then, check to see if there's a binary operator operating on that leftmost thing
left = gobbleToken();
biop = gobbleBinaryOp();
// If there wasn't a binary operator, just return the leftmost node
if (!biop) {
return left;
}
// Otherwise, we need to start a stack to properly place the binary operations in their
// precedence structure
biop_info = { value: biop, prec: binaryPrecedence(biop) };
right = gobbleToken();
if (!right) {
throwError("Expected expression after " + biop, index);
}
stack = [left, biop_info, right];
// Properly deal with precedence using [recursive descent](http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm)
while ((biop = gobbleBinaryOp())) {
prec = binaryPrecedence(biop);
if (prec === 0) {
break;
}
biop_info = { value: biop, prec: prec };
cur_biop = biop;
// Reduce: make a binary expression from the three topmost entries.
while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) {
right = stack.pop();
biop = stack.pop().value;
left = stack.pop();
node = createBinaryExpression(biop, left, right);
stack.push(node);
}
node = gobbleToken();
if (!node) {
throwError("Expected expression after " + cur_biop, index);
}
stack.push(biop_info, node);
}
i = stack.length - 1;
node = stack[i];
while (i > 1) {
node = createBinaryExpression(stack[i - 1].value, stack[i - 2], node);
i -= 2;
}
return node;
},
// An individual part of a binary expression:
// e.g. `foo.bar(baz)`, `1`, `"abc"`, `(a % 2)` (because it's in parenthesis)
gobbleToken = function () {
var ch, to_check, tc_len;
gobbleSpaces();
ch = exprICode(index);
if (isDecimalDigit(ch) || ch === PERIOD_CODE) {
// Char code 46 is a dot `.` which can start off a numeric literal
return gobbleNumericLiteral();
} else if (ch === SQUOTE_CODE || ch === DQUOTE_CODE) {
// Single or double quotes
return gobbleStringLiteral();
} else if (ch === OBRACK_CODE) {
return gobbleArray();
} else {
to_check = expr.substr(index, max_unop_len);
tc_len = to_check.length;
while (tc_len > 0) {
// Don't accept an unary op when it is an identifier.
// Unary ops that start with a identifier-valid character must be followed
// by a non identifier-part valid character
if (unary_ops.hasOwnProperty(to_check) && (
!isIdentifierStart(exprICode(index)) ||
(index + to_check.length < expr.length && !isIdentifierPart(exprICode(index + to_check.length)))
)) {
index += tc_len;
return {
type: UNARY_EXP,
operator: to_check,
argument: gobbleToken(),
prefix: true
};
}
to_check = to_check.substr(0, --tc_len);
}
if (isIdentifierStart(ch) || ch === OPAREN_CODE) { // open parenthesis
// `foo`, `bar.baz`
return gobbleVariable();
}
}
return false;
},
// Parse simple numeric literals: `12`, `3.4`, `.5`. Do this by using a string to
// keep track of everything in the numeric literal and then calling `parseFloat` on that string
gobbleNumericLiteral = function () {
var number = '', ch, chCode;
while (isDecimalDigit(exprICode(index))) {
number += exprI(index++);
}
if (exprICode(index) === PERIOD_CODE) { // can start with a decimal marker
number += exprI(index++);
while (isDecimalDigit(exprICode(index))) {
number += exprI(index++);
}
}
ch = exprI(index);
if (ch === 'e' || ch === 'E') { // exponent marker
number += exprI(index++);
ch = exprI(index);
if (ch === '+' || ch === '-') { // exponent sign
number += exprI(index++);
}
while (isDecimalDigit(exprICode(index))) { //exponent itself
number += exprI(index++);
}
if (!isDecimalDigit(exprICode(index - 1))) {
throwError('Expected exponent (' + number + exprI(index) + ')', index);
}
}
chCode = exprICode(index);
// Check to make sure this isn't a variable name that start with a number (123abc)
if (isIdentifierStart(chCode)) {
throwError('Variable names cannot start with a number (' +
number + exprI(index) + ')', index);
} else if (chCode === PERIOD_CODE) {
throwError('Unexpected period', index);
}
return {
type: LITERAL,
value: parseFloat(number),
raw: number
};
},
// Parses a string literal, staring with single or double quotes with basic support for escape codes
// e.g. `"hello world"`, `'this is\nJSEP'`
gobbleStringLiteral = function () {
var str = '', quote = exprI(index++), closed = false, ch;
while (index < length) {
ch = exprI(index++);
if (ch === quote) {
closed = true;
break;
} else if (ch === '\\') {
// Check for all of the common escape codes
ch = exprI(index++);
switch (ch) {
case 'n': str += '\n'; break;
case 'r': str += '\r'; break;
case 't': str += '\t'; break;
case 'b': str += '\b'; break;
case 'f': str += '\f'; break;
case 'v': str += '\x0B'; break;
default: str += ch;
}
} else {
str += ch;
}
}
if (!closed) {
throwError('Unclosed quote after "' + str + '"', index);
}
return {
type: LITERAL,
value: str,
raw: quote + str + quote
};
},
// Gobbles only identifiers
// e.g.: `foo`, `_value`, `$x1`
// Also, this function checks if that identifier is a literal:
// (e.g. `true`, `false`, `null`) or `this`
gobbleIdentifier = function () {
var ch = exprICode(index), start = index, identifier;
if (isIdentifierStart(ch)) {
index++;
} else {
throwError('Unexpected ' + exprI(index), index);
}
while (index < length) {
ch = exprICode(index);
if (isIdentifierPart(ch)) {
index++;
} else {
break;
}
}
identifier = expr.slice(start, index);
if (literals.hasOwnProperty(identifier)) {
return {
type: LITERAL,
value: literals[identifier],
raw: identifier
};
} else if (identifier === this_str) {
return { type: THIS_EXP };
} else {
return {
type: IDENTIFIER,
name: identifier
};
}
},
// Gobbles a list of arguments within the context of a function call
// or array literal. This function also assumes that the opening character
// `(` or `[` has already been gobbled, and gobbles expressions and commas
// until the terminator character `)` or `]` is encountered.
// e.g. `foo(bar, baz)`, `my_func()`, or `[bar, baz]`
gobbleArguments = function (termination) {
var ch_i, args = [], node, closed = false;
while (index < length) {
gobbleSpaces();
ch_i = exprICode(index);
if (ch_i === termination) { // done parsing
closed = true;
index++;
break;
} else if (ch_i === COMMA_CODE) { // between expressions
index++;
} else {
node = gobbleExpression();
if (!node || node.type === COMPOUND) {
throwError('Expected comma', index);
}
args.push(node);
}
}
if (!closed) {
throwError('Expected ' + String.fromCharCode(termination), index);
}
return args;
},
// Gobble a non-literal variable name. This variable name may include properties
// e.g. `foo`, `bar.baz`, `foo['bar'].baz`
// It also gobbles function calls:
// e.g. `Math.acos(obj.angle)`
gobbleVariable = function () {
var ch_i, node;
ch_i = exprICode(index);
if (ch_i === OPAREN_CODE) {
node = gobbleGroup();
} else {
node = gobbleIdentifier();
}
gobbleSpaces();
ch_i = exprICode(index);
while (ch_i === PERIOD_CODE || ch_i === OBRACK_CODE || ch_i === OPAREN_CODE) {
index++;
if (ch_i === PERIOD_CODE) {
gobbleSpaces();
node = {
type: MEMBER_EXP,
computed: false,
object: node,
property: gobbleIdentifier()
};
} else if (ch_i === OBRACK_CODE) {
node = {
type: MEMBER_EXP,
computed: true,
object: node,
property: gobbleExpression()
};
gobbleSpaces();
ch_i = exprICode(index);
if (ch_i !== CBRACK_CODE) {
throwError('Unclosed [', index);
}
index++;
} else if (ch_i === OPAREN_CODE) {
// A function call is being made; gobble all the arguments
node = {
type: CALL_EXP,
'arguments': gobbleArguments(CPAREN_CODE),
callee: node
};
}
gobbleSpaces();
ch_i = exprICode(index);
}
return node;
},
// Responsible for parsing a group of things within parentheses `()`
// This function assumes that it needs to gobble the opening parenthesis
// and then tries to gobble everything within that parenthesis, assuming
// that the next thing it should see is the close parenthesis. If not,
// then the expression probably doesn't have a `)`
gobbleGroup = function () {
index++;
var node = gobbleExpression();
gobbleSpaces();
if (exprICode(index) === CPAREN_CODE) {
index++;
return node;
} else {
throwError('Unclosed (', index);
}
},
// Responsible for parsing Array literals `[1, 2, 3]`
// This function assumes that it needs to gobble the opening bracket
// and then tries to gobble the expressions as arguments.
gobbleArray = function () {
index++;
return {
type: ARRAY_EXP,
elements: gobbleArguments(CBRACK_CODE)
};
},
nodes = [], ch_i, node;
while (index < length) {
ch_i = exprICode(index);
// Expressions can be separated by semicolons, commas, or just inferred without any
// separators
if (ch_i === SEMCOL_CODE || ch_i === COMMA_CODE) {
index++; // ignore separators
} else {
// Try to gobble each expression individually
if ((node = gobbleExpression())) {
nodes.push(node);
// If we weren't able to find a binary expression and are out of room, then
// the expression passed in probably has too much
} else if (index < length) {
throwError('Unexpected "' + exprI(index) + '"', index);
}
}
}
// If there's only one expression just try returning the expression
if (nodes.length === 1) {
return nodes[0];
} else {
return <any>{
type: COMPOUND,
body: nodes
};
}
}; |
927f5f7912eb36edfb23ff815b5635350b4d27b6 | 2,450 | ts | TypeScript | src/audio/Resampler.ts | FloflisPull/jsGBC-core | 0d2c721bb2ce2aaef8720c07f8a859707d1445d1 | [
"MIT"
] | null | null | null | src/audio/Resampler.ts | FloflisPull/jsGBC-core | 0d2c721bb2ce2aaef8720c07f8a859707d1445d1 | [
"MIT"
] | 4 | 2022-03-26T17:24:41.000Z | 2022-03-26T17:58:20.000Z | src/audio/Resampler.ts | FloflisPull/jsGBC-core | 0d2c721bb2ce2aaef8720c07f8a859707d1445d1 | [
"MIT"
] | null | null | null | export default class Resampler {
ratioWeight: number;
lastWeight: number;
tailExists: boolean;
outputBuffer: Float32Array;
lastOutput: Float32Array;
constructor(
private fromSampleRate: number,
private toSampleRate: number,
private channels: number,
private outputBufferSize: number
) {
if (
this.fromSampleRate <= 0 ||
this.toSampleRate <= 0 ||
this.channels <= 0
) throw new Error("Invalid settings specified for the resampler.");
this.ratioWeight = this.fromSampleRate / this.toSampleRate;
if (this.fromSampleRate < this.toSampleRate) {
this.lastWeight = 1;
}
this.outputBuffer = new Float32Array(this.outputBufferSize);
this.lastOutput = new Float32Array(this.channels);
}
resample(buffer: Float32Array) {
let bufferLength = buffer.length;
if ((bufferLength % this.channels) !== 0) throw new Error("Buffer was of incorrect sample length.");
if (bufferLength === 0) return;
let weight = this.lastWeight;
let firstWeight = 0;
let secondWeight = 0;
let sourceOffset = 0;
let outputOffset = 0;
for (; weight < 1; weight += this.ratioWeight) {
secondWeight = weight % 1;
firstWeight = 1 - secondWeight;
for (let channel = 0; channel < this.channels; channel++) {
this.outputBuffer[outputOffset++] = (
(
this.lastOutput[channel] *
firstWeight
) +
(
buffer[channel] *
secondWeight
)
);
}
}
weight -= 1;
for (
bufferLength -= this.channels, sourceOffset = Math.floor(weight) * this.channels;
outputOffset < this.outputBufferSize && sourceOffset < bufferLength;
) {
secondWeight = weight % 1;
firstWeight = 1 - secondWeight;
for (let channel = 0; channel < this.channels; channel++) {
this.outputBuffer[outputOffset++] = (
(
buffer[sourceOffset + channel] *
firstWeight
) +
(
buffer[sourceOffset + this.channels + channel] *
secondWeight
)
);
}
weight += this.ratioWeight;
sourceOffset = Math.floor(weight) * this.channels;
}
for (let channel = 0; channel < this.channels; ++channel) {
this.lastOutput[channel] = buffer[sourceOffset++];
}
this.lastWeight = weight % 1;
return outputOffset;
}
}
| 26.06383 | 104 | 0.597959 | 78 | 2 | 0 | 5 | 9 | 5 | 0 | 0 | 7 | 1 | 0 | 31 | 616 | 0.011364 | 0.01461 | 0.008117 | 0.001623 | 0 | 0 | 0.333333 | 0.246659 | export default class Resampler {
ratioWeight;
lastWeight;
tailExists;
outputBuffer;
lastOutput;
constructor(
private fromSampleRate,
private toSampleRate,
private channels,
private outputBufferSize
) {
if (
this.fromSampleRate <= 0 ||
this.toSampleRate <= 0 ||
this.channels <= 0
) throw new Error("Invalid settings specified for the resampler.");
this.ratioWeight = this.fromSampleRate / this.toSampleRate;
if (this.fromSampleRate < this.toSampleRate) {
this.lastWeight = 1;
}
this.outputBuffer = new Float32Array(this.outputBufferSize);
this.lastOutput = new Float32Array(this.channels);
}
resample(buffer) {
let bufferLength = buffer.length;
if ((bufferLength % this.channels) !== 0) throw new Error("Buffer was of incorrect sample length.");
if (bufferLength === 0) return;
let weight = this.lastWeight;
let firstWeight = 0;
let secondWeight = 0;
let sourceOffset = 0;
let outputOffset = 0;
for (; weight < 1; weight += this.ratioWeight) {
secondWeight = weight % 1;
firstWeight = 1 - secondWeight;
for (let channel = 0; channel < this.channels; channel++) {
this.outputBuffer[outputOffset++] = (
(
this.lastOutput[channel] *
firstWeight
) +
(
buffer[channel] *
secondWeight
)
);
}
}
weight -= 1;
for (
bufferLength -= this.channels, sourceOffset = Math.floor(weight) * this.channels;
outputOffset < this.outputBufferSize && sourceOffset < bufferLength;
) {
secondWeight = weight % 1;
firstWeight = 1 - secondWeight;
for (let channel = 0; channel < this.channels; channel++) {
this.outputBuffer[outputOffset++] = (
(
buffer[sourceOffset + channel] *
firstWeight
) +
(
buffer[sourceOffset + this.channels + channel] *
secondWeight
)
);
}
weight += this.ratioWeight;
sourceOffset = Math.floor(weight) * this.channels;
}
for (let channel = 0; channel < this.channels; ++channel) {
this.lastOutput[channel] = buffer[sourceOffset++];
}
this.lastWeight = weight % 1;
return outputOffset;
}
}
|
1c3a1964e67b7238573f2c5259366523f35f2d10 | 4,348 | ts | TypeScript | src/tfidf.ts | liammagee/obsidian-topic-linking | f3206c4ab800e6aab371790a8d1937f4828dd344 | [
"MIT"
] | 16 | 2022-01-11T00:13:35.000Z | 2022-03-29T23:27:19.000Z | src/tfidf.ts | liammagee/obsidian-topic-linking | f3206c4ab800e6aab371790a8d1937f4828dd344 | [
"MIT"
] | 3 | 2022-02-08T14:55:52.000Z | 2022-03-19T04:12:04.000Z | src/tfidf.ts | liammagee/obsidian-topic-linking | f3206c4ab800e6aab371790a8d1937f4828dd344 | [
"MIT"
] | 2 | 2022-03-05T18:20:52.000Z | 2022-03-27T14:11:10.000Z | export class TfIdf {
documents: string[][] = [];
documentLengths: number[] = [];
averageDocumentLength : number = 0;
constructor() {
this.documents = [];
}
addDocument(doc: string, tokenise:boolean = false) {
if (tokenise) {
doc = doc.toLowerCase().replace(/[^A-Za-z\ ]+/g, '').replace(/\s+/g, ' ');
}
let tokens = doc.split(' ');
this.documents.push(tokens);
this.documentLengths.push(doc.length);
}
private tfs() {
let tfs : Record<string, number>[] = [];
for (let tokens of this.documents) {
let tf : Record<string, number> = {};
for (let token of tokens) {
if (tf[token] == null) {
tf[token] = 1
} else {
tf[token] += 1
}
}
tfs.push(tf)
}
return tfs;
}
private dfs() {
let dfs : Record<string, number> = {};
let n : number = this.documents.length;
for (let i = 0; i < n; i++) {
let doc = this.documents[i];
let tokensUnique = doc.filter((value, index, arr) => arr.indexOf(value) === index);
for (let token of tokensUnique) {
if (dfs[token] != undefined)
dfs[token] += 1;
else
dfs[token] = 1;
}
}
return dfs;
}
private sorted(results: any[][], sortKey : string = 'bm25') {
if (results.length == 0 || results[0].length == 0 || results[0][0] == null || results[0][0][sortKey] == null)
throw new Error("Empty results or invalid sort key");
let sortedResults : any[][] = [];
for (let resultsDoc of results) {
let sortedResultsDoc : any[] = [];
sortedResultsDoc = resultsDoc.sort((a, b) => b[sortKey] - a[sortKey]);
sortedResults.push(sortedResultsDoc);
}
return sortedResults;
}
private top(results: any[][], topN:number) {
let sortedResults : any[][] = [];
for (let resultsDoc of results) {
let resultsTopN : any[] = resultsDoc.slice(0, topN);
sortedResults.push(resultsTopN);
}
return sortedResults;
}
private idfs(mix:number) {
let dfs : Record<string, number> = this.dfs();
let n = this.documents.length;
let idfs : Record<string, number> = {};
Object.keys(dfs).forEach((token) => {
let df : number = dfs[token];
// Non-BM25 version
// idfs[token] = 1 + Math.log((n) / (df + mix));
// If 'mix' == 1, amounts to the same
idfs[token] = 1 + Math.log(mix + ( n - df + 0.5) / (df + 0.5));
});
return idfs;
}
tfidfs(k: number = 1.0, b: number = 0.75, mix: number = 0.0, sortKey: string = 'bm25', topN: number = 10) {
let tfs = this.tfs();
let idfs = this.idfs(mix);
let tfidfs : Record<string, number>[] = [];
let results : any[] = [];
// Get average document length
let adl = this.documentLengths.reduce((a, b) => a + b, 0) / this.documentLengths.length;
for (let i in tfs) {
let tfDoc = tfs[i];
let tfidfRec : Record<string, number> = {};
let dl : number = this.documentLengths[i];
let kb : number = k * (1 - b + b * (dl / adl));
let resultsDoc : any[] = [];
for (let term in tfDoc) {
let tf : number = tfDoc[term];
let tfkb : number = tf / (tf + kb);
let idf = idfs[term];
let tfidf : number = tf * idf;
let bm25 : number = tfkb * idf;
let resultTerm : any = {
term: term,
tf: tf,
idf: idf,
tfidf: tfidf,
bm25: bm25
}
resultsDoc.push(resultTerm);
}
results.push(resultsDoc);
tfidfs.push(tfidfRec);
}
if (sortKey != null)
results = this.sorted(results, sortKey);
if (topN != null && topN > 0)
results = this.top(results, topN);
return results;
}
}
| 33.446154 | 117 | 0.463661 | 111 | 12 | 0 | 20 | 32 | 3 | 5 | 9 | 35 | 1 | 0 | 7.916667 | 1,150 | 0.027826 | 0.027826 | 0.002609 | 0.00087 | 0 | 0.134328 | 0.522388 | 0.325962 | export class TfIdf {
documents = [];
documentLengths = [];
averageDocumentLength = 0;
constructor() {
this.documents = [];
}
addDocument(doc, tokenise = false) {
if (tokenise) {
doc = doc.toLowerCase().replace(/[^A-Za-z\ ]+/g, '').replace(/\s+/g, ' ');
}
let tokens = doc.split(' ');
this.documents.push(tokens);
this.documentLengths.push(doc.length);
}
private tfs() {
let tfs = [];
for (let tokens of this.documents) {
let tf = {};
for (let token of tokens) {
if (tf[token] == null) {
tf[token] = 1
} else {
tf[token] += 1
}
}
tfs.push(tf)
}
return tfs;
}
private dfs() {
let dfs = {};
let n = this.documents.length;
for (let i = 0; i < n; i++) {
let doc = this.documents[i];
let tokensUnique = doc.filter((value, index, arr) => arr.indexOf(value) === index);
for (let token of tokensUnique) {
if (dfs[token] != undefined)
dfs[token] += 1;
else
dfs[token] = 1;
}
}
return dfs;
}
private sorted(results, sortKey = 'bm25') {
if (results.length == 0 || results[0].length == 0 || results[0][0] == null || results[0][0][sortKey] == null)
throw new Error("Empty results or invalid sort key");
let sortedResults = [];
for (let resultsDoc of results) {
let sortedResultsDoc = [];
sortedResultsDoc = resultsDoc.sort((a, b) => b[sortKey] - a[sortKey]);
sortedResults.push(sortedResultsDoc);
}
return sortedResults;
}
private top(results, topN) {
let sortedResults = [];
for (let resultsDoc of results) {
let resultsTopN = resultsDoc.slice(0, topN);
sortedResults.push(resultsTopN);
}
return sortedResults;
}
private idfs(mix) {
let dfs = this.dfs();
let n = this.documents.length;
let idfs = {};
Object.keys(dfs).forEach((token) => {
let df = dfs[token];
// Non-BM25 version
// idfs[token] = 1 + Math.log((n) / (df + mix));
// If 'mix' == 1, amounts to the same
idfs[token] = 1 + Math.log(mix + ( n - df + 0.5) / (df + 0.5));
});
return idfs;
}
tfidfs(k = 1.0, b = 0.75, mix = 0.0, sortKey = 'bm25', topN = 10) {
let tfs = this.tfs();
let idfs = this.idfs(mix);
let tfidfs = [];
let results = [];
// Get average document length
let adl = this.documentLengths.reduce((a, b) => a + b, 0) / this.documentLengths.length;
for (let i in tfs) {
let tfDoc = tfs[i];
let tfidfRec = {};
let dl = this.documentLengths[i];
let kb = k * (1 - b + b * (dl / adl));
let resultsDoc = [];
for (let term in tfDoc) {
let tf = tfDoc[term];
let tfkb = tf / (tf + kb);
let idf = idfs[term];
let tfidf = tf * idf;
let bm25 = tfkb * idf;
let resultTerm = {
term: term,
tf: tf,
idf: idf,
tfidf: tfidf,
bm25: bm25
}
resultsDoc.push(resultTerm);
}
results.push(resultsDoc);
tfidfs.push(tfidfRec);
}
if (sortKey != null)
results = this.sorted(results, sortKey);
if (topN != null && topN > 0)
results = this.top(results, topN);
return results;
}
}
|
1cb25c3d385a287f4227b776402fb108e7a5b784 | 1,670 | ts | TypeScript | app/src/ts/def.ts | begyyal/cmdbbt | 94377cce969e2e9ec22db7f447994623b4ea8111 | [
"MIT"
] | 1 | 2022-02-11T12:07:49.000Z | 2022-02-11T12:07:49.000Z | app/src/ts/def.ts | begyyal/cmdbbt | 94377cce969e2e9ec22db7f447994623b4ea8111 | [
"MIT"
] | null | null | null | app/src/ts/def.ts | begyyal/cmdbbt | 94377cce969e2e9ec22db7f447994623b4ea8111 | [
"MIT"
] | null | null | null | export interface BbtDef {
need: string[];
resource: string;
operations: CmdDef[];
option: number;
}
export function isBbtDef(def: any): def is BbtDef {
let ok = def.need !== undefined &&
def.resource !== undefined &&
def.operations !== undefined;
if (ok) {
let ope = def.operations;
if (Array.isArray(ope))
ok = ok && ope.every(isCmdDef);
else
createRequiredNonNullErr("operations");
}
return ok;
}
export interface CmdDef {
name: string;
command: string;
exitCode: number;
expected: Check[];
}
export function isCmdDef(def: any): def is CmdDef {
let ok = def.name !== undefined
&& def.command !== undefined
&& def.exitCode !== undefined
&& def.expected !== undefined;
if (ok) {
let exp = def.expected;
if (!def.name)
createRequiredNonNullErr("name");
else if (!def.command)
createRequiredNonNullErr("command");
else if (Array.isArray(exp))
ok = ok && exp.every(isCheck);
else
createRequiredNonNullErr("expected");
}
return ok;
}
export interface Check {
act: string;
value: string;
}
export function isCheck(def: any): def is Check {
const ok = def.act !== undefined
&& def.value !== undefined;
if (ok)
if (!def.act)
createRequiredNonNullErr("act");
else if (!def.value)
createRequiredNonNullErr("value");
return ok;
}
function createRequiredNonNullErr(fieldName: string): Error {
return new Error("The [" + fieldName + "] field must be non null.");
} | 25.30303 | 72 | 0.576048 | 60 | 4 | 0 | 4 | 5 | 10 | 1 | 3 | 9 | 3 | 0 | 9 | 415 | 0.019277 | 0.012048 | 0.024096 | 0.007229 | 0 | 0.130435 | 0.391304 | 0.263862 | export interface BbtDef {
need;
resource;
operations;
option;
}
export function isBbtDef(def): def is BbtDef {
let ok = def.need !== undefined &&
def.resource !== undefined &&
def.operations !== undefined;
if (ok) {
let ope = def.operations;
if (Array.isArray(ope))
ok = ok && ope.every(isCmdDef);
else
createRequiredNonNullErr("operations");
}
return ok;
}
export interface CmdDef {
name;
command;
exitCode;
expected;
}
export /* Example usages of 'isCmdDef' are shown below:
ok = ok && ope.every(isCmdDef);
*/
function isCmdDef(def): def is CmdDef {
let ok = def.name !== undefined
&& def.command !== undefined
&& def.exitCode !== undefined
&& def.expected !== undefined;
if (ok) {
let exp = def.expected;
if (!def.name)
createRequiredNonNullErr("name");
else if (!def.command)
createRequiredNonNullErr("command");
else if (Array.isArray(exp))
ok = ok && exp.every(isCheck);
else
createRequiredNonNullErr("expected");
}
return ok;
}
export interface Check {
act;
value;
}
export /* Example usages of 'isCheck' are shown below:
ok = ok && exp.every(isCheck);
*/
function isCheck(def): def is Check {
const ok = def.act !== undefined
&& def.value !== undefined;
if (ok)
if (!def.act)
createRequiredNonNullErr("act");
else if (!def.value)
createRequiredNonNullErr("value");
return ok;
}
/* Example usages of 'createRequiredNonNullErr' are shown below:
createRequiredNonNullErr("operations");
createRequiredNonNullErr("name");
createRequiredNonNullErr("command");
createRequiredNonNullErr("expected");
createRequiredNonNullErr("act");
createRequiredNonNullErr("value");
*/
function createRequiredNonNullErr(fieldName) {
return new Error("The [" + fieldName + "] field must be non null.");
} |
1cff957f4d2e357142c20a3575489611cf52b52e | 1,989 | ts | TypeScript | src/helpers/Validators.ts | theticketfairy/tf-checkout-react-native | 727aea8be812a03a96cae2d7a3d5dffe6480cfe6 | [
"MIT"
] | 5 | 2022-03-14T11:36:43.000Z | 2022-03-22T19:09:02.000Z | src/helpers/Validators.ts | theticketfairy/tf-checkout-react-native | 727aea8be812a03a96cae2d7a3d5dffe6480cfe6 | [
"MIT"
] | null | null | null | src/helpers/Validators.ts | theticketfairy/tf-checkout-react-native | 727aea8be812a03a96cae2d7a3d5dffe6480cfe6 | [
"MIT"
] | null | null | null | export const emailRegex =
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
//https://www.twilio.com/docs/glossary/what-e164
const phoneRegex = /^\+[1-9]\d{1,14}$/
export const validateEmpty = (
value?: string | number,
message?: string
): string => {
let errorMessage = ''
if (!value) {
errorMessage = message || 'Required'
}
return errorMessage
}
export const validateMinLength = (
value: string,
minLength: number,
fieldName: string = 'Field'
) =>
value.length < minLength
? `${fieldName} requires at least ${minLength} characters`
: ''
export const validateEmail = (email: string, equalTo?: string) => {
let validation = ''
if (equalTo) {
validation = email === equalTo ? '' : 'Emails must match'
}
if (validation) {
return validation
}
return !emailRegex.test(email) ? 'Please enter a valid email address' : ''
}
export const validatePasswords = (password: string, equalTo: string) => {
let validation = ''
if (equalTo) {
validation = password === equalTo ? '' : 'Passwords must match'
}
if (validation) {
return validation
}
validation = validateEmpty(password)
if (validation) {
return validation
}
return validateMinLength(password, 6, 'Password')
}
export const validateAge = (
dateOfBirth: Date,
minimumAge: number = 18
): string => {
const today = new Date()
const age = today.getFullYear() - dateOfBirth.getFullYear()
return age < minimumAge ? `You must be at least ${minimumAge} years old` : ''
}
interface IValidatePhoneNumber {
phoneNumber?: string
customError?: string
}
export const validatePhoneNumber = ({
phoneNumber,
customError,
}: IValidatePhoneNumber) => {
if (!phoneNumber) {
return customError || 'Please enter a phone number'
}
return !phoneRegex.test(`${phoneNumber}`)
? customError || 'Please enter a valid phone number'
: ''
}
| 25.177215 | 154 | 0.624937 | 68 | 6 | 0 | 12 | 13 | 2 | 2 | 0 | 15 | 1 | 0 | 6.166667 | 578 | 0.031142 | 0.022491 | 0.00346 | 0.00173 | 0 | 0 | 0.454545 | 0.319126 | export const emailRegex =
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
//https://www.twilio.com/docs/glossary/what-e164
const phoneRegex = /^\+[1-9]\d{1,14}$/
export /* Example usages of 'validateEmpty' are shown below:
validation = validateEmpty(password);
*/
const validateEmpty = (
value?,
message?
) => {
let errorMessage = ''
if (!value) {
errorMessage = message || 'Required'
}
return errorMessage
}
export /* Example usages of 'validateMinLength' are shown below:
validateMinLength(password, 6, 'Password');
*/
const validateMinLength = (
value,
minLength,
fieldName = 'Field'
) =>
value.length < minLength
? `${fieldName} requires at least ${minLength} characters`
: ''
export const validateEmail = (email, equalTo?) => {
let validation = ''
if (equalTo) {
validation = email === equalTo ? '' : 'Emails must match'
}
if (validation) {
return validation
}
return !emailRegex.test(email) ? 'Please enter a valid email address' : ''
}
export const validatePasswords = (password, equalTo) => {
let validation = ''
if (equalTo) {
validation = password === equalTo ? '' : 'Passwords must match'
}
if (validation) {
return validation
}
validation = validateEmpty(password)
if (validation) {
return validation
}
return validateMinLength(password, 6, 'Password')
}
export const validateAge = (
dateOfBirth,
minimumAge = 18
) => {
const today = new Date()
const age = today.getFullYear() - dateOfBirth.getFullYear()
return age < minimumAge ? `You must be at least ${minimumAge} years old` : ''
}
interface IValidatePhoneNumber {
phoneNumber?
customError?
}
export const validatePhoneNumber = ({
phoneNumber,
customError,
}) => {
if (!phoneNumber) {
return customError || 'Please enter a phone number'
}
return !phoneRegex.test(`${phoneNumber}`)
? customError || 'Please enter a valid phone number'
: ''
}
|
2d1db28e173e4c59bc3bde54764d68d63757e431 | 3,121 | ts | TypeScript | packages/backend/src/utils/filters.ts | silash35/makilab | 96ef0e9eb7fab2fe09a165a095f48b10161c378f | [
"Unlicense"
] | null | null | null | packages/backend/src/utils/filters.ts | silash35/makilab | 96ef0e9eb7fab2fe09a165a095f48b10161c378f | [
"Unlicense"
] | 1 | 2022-02-19T23:44:17.000Z | 2022-02-19T23:44:17.000Z | packages/backend/src/utils/filters.ts | silash35/makilab | 96ef0e9eb7fab2fe09a165a095f48b10161c378f | [
"Unlicense"
] | null | null | null | const isString = (variable: unknown): variable is string => {
return typeof variable === "string" && variable.length > 0;
};
export const filterBoolean = (variable: unknown) => {
return (
variable === "on" ||
variable === "true" ||
variable === true ||
variable === 1 ||
variable === "1"
);
};
export const filterMoney = (variable: unknown) => {
const number = filterNumber(variable);
if (number === null) {
return null;
}
if ((variable as string).match(/-/g)?.length === 1) {
return -number;
} else {
return number;
}
};
export const filterNumber = (variable: unknown) => {
if (variable !== undefined && variable !== null && variable !== "") {
const string = String(variable).replace(/\D/g, "");
if (!(string.length > 0)) {
return null;
}
const number = Number(string);
return isNaN(number) ? null : number;
} else {
return null;
}
};
export const filterString = (variable: unknown) => {
return isString(variable) ? variable : null;
};
export const filterDate = (variable: unknown, fail = false) => {
if (variable === null || variable === undefined || variable === "") {
return null;
}
// Check if the date is valid
if (!isNaN(Date.parse(variable as string))) {
return new Date(variable as string);
} else {
if (fail) {
throw new Error("Invalid data: Date");
}
return null;
}
};
export const filterCpfOrCnpj = (variable: unknown) => {
let string = filterString(variable);
if (string === null) {
return null;
}
// Remove all non-numeric characters
string = string.replace(/\D/g, "");
if (string.length === 11) {
string = string.replace(/^(\d{3})(\d{3})(\d{3})(\d{2}).*/, "$1.$2.$3-$4");
} else if (string.length === 14) {
string = string.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2}).*/, "$1.$2.$3/$4-$5");
}
return string;
};
export const filterPhoneNumber = (variable: unknown) => {
let string = filterString(variable);
if (string === null) {
return null;
}
// Remove all non-numeric characters
string = string.replace(/\D/g, "");
if (string.length === 8) {
string = string.replace(/^(\d{4})(\d{4}).*/, "+55 71 $1-$2");
} else if (string.length === 9) {
string = string.replace(/^(\d{5})(\d{4}).*/, "+55 71 $1-$2");
} else if (string.length === 10) {
string = string.replace(/^(\d{2})(\d{4})(\d{4}).*/, "+55 $1 $2-$3");
} else if (string.length === 11) {
string = string.replace(/^(\d{2})(\d{5})(\d{4}).*/, "+55 $1 $2-$3");
} else if (string.length === 12) {
string = string.replace(/^(\d{2})(\d{2})(\d{4})(\d{4}).*/, "+$1 $2 $3-$4");
} else if (string.length === 13) {
string = string.replace(/^(\d{2})(\d{2})(\d{5})(\d{4}).*/, "+$1 $2 $3-$4");
}
return string;
};
export const filterZip = (variable: unknown) => {
let string = filterString(variable);
if (string === null) {
return null;
}
// Remove all non-numeric characters
string = string.replace(/\D/g, "");
if (string.length === 8) {
string = string.replace(/^(\d{5})(\d{3}).*/, "$1-$2");
}
return string;
};
| 26.008333 | 88 | 0.551105 | 96 | 9 | 0 | 10 | 15 | 0 | 3 | 0 | 13 | 0 | 4 | 8.666667 | 1,005 | 0.018905 | 0.014925 | 0 | 0 | 0.00398 | 0 | 0.382353 | 0.262723 | /* Example usages of 'isString' are shown below:
isString(variable) ? variable : null;
*/
const isString = (variable): variable is string => {
return typeof variable === "string" && variable.length > 0;
};
export const filterBoolean = (variable) => {
return (
variable === "on" ||
variable === "true" ||
variable === true ||
variable === 1 ||
variable === "1"
);
};
export const filterMoney = (variable) => {
const number = filterNumber(variable);
if (number === null) {
return null;
}
if ((variable as string).match(/-/g)?.length === 1) {
return -number;
} else {
return number;
}
};
export /* Example usages of 'filterNumber' are shown below:
filterNumber(variable);
*/
const filterNumber = (variable) => {
if (variable !== undefined && variable !== null && variable !== "") {
const string = String(variable).replace(/\D/g, "");
if (!(string.length > 0)) {
return null;
}
const number = Number(string);
return isNaN(number) ? null : number;
} else {
return null;
}
};
export /* Example usages of 'filterString' are shown below:
filterString(variable);
*/
const filterString = (variable) => {
return isString(variable) ? variable : null;
};
export const filterDate = (variable, fail = false) => {
if (variable === null || variable === undefined || variable === "") {
return null;
}
// Check if the date is valid
if (!isNaN(Date.parse(variable as string))) {
return new Date(variable as string);
} else {
if (fail) {
throw new Error("Invalid data: Date");
}
return null;
}
};
export const filterCpfOrCnpj = (variable) => {
let string = filterString(variable);
if (string === null) {
return null;
}
// Remove all non-numeric characters
string = string.replace(/\D/g, "");
if (string.length === 11) {
string = string.replace(/^(\d{3})(\d{3})(\d{3})(\d{2}).*/, "$1.$2.$3-$4");
} else if (string.length === 14) {
string = string.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2}).*/, "$1.$2.$3/$4-$5");
}
return string;
};
export const filterPhoneNumber = (variable) => {
let string = filterString(variable);
if (string === null) {
return null;
}
// Remove all non-numeric characters
string = string.replace(/\D/g, "");
if (string.length === 8) {
string = string.replace(/^(\d{4})(\d{4}).*/, "+55 71 $1-$2");
} else if (string.length === 9) {
string = string.replace(/^(\d{5})(\d{4}).*/, "+55 71 $1-$2");
} else if (string.length === 10) {
string = string.replace(/^(\d{2})(\d{4})(\d{4}).*/, "+55 $1 $2-$3");
} else if (string.length === 11) {
string = string.replace(/^(\d{2})(\d{5})(\d{4}).*/, "+55 $1 $2-$3");
} else if (string.length === 12) {
string = string.replace(/^(\d{2})(\d{2})(\d{4})(\d{4}).*/, "+$1 $2 $3-$4");
} else if (string.length === 13) {
string = string.replace(/^(\d{2})(\d{2})(\d{5})(\d{4}).*/, "+$1 $2 $3-$4");
}
return string;
};
export const filterZip = (variable) => {
let string = filterString(variable);
if (string === null) {
return null;
}
// Remove all non-numeric characters
string = string.replace(/\D/g, "");
if (string.length === 8) {
string = string.replace(/^(\d{5})(\d{3}).*/, "$1-$2");
}
return string;
};
|
2d56fbfab4e337b097b6ea3531864d3185d36222 | 988 | ts | TypeScript | src/editor/components/columns/properties-view/utils/parsePaddingValue.ts | antinspace/hve | db02d33b9a83731204c7ee2deb9d9ad6c3a300a1 | [
"MIT"
] | 1 | 2022-03-19T11:26:19.000Z | 2022-03-19T11:26:19.000Z | src/editor/components/columns/properties-view/utils/parsePaddingValue.ts | antinspace/hve | db02d33b9a83731204c7ee2deb9d9ad6c3a300a1 | [
"MIT"
] | null | null | null | src/editor/components/columns/properties-view/utils/parsePaddingValue.ts | antinspace/hve | db02d33b9a83731204c7ee2deb9d9ad6c3a300a1 | [
"MIT"
] | 1 | 2022-03-20T15:07:13.000Z | 2022-03-20T15:07:13.000Z |
export type PaddingValue = {
top: string;
right: string;
bottom: string;
left: string;
};
export const parsePaddingValue = (val: string): PaddingValue => {
if (!val) {
return {
top: "0px",
right: "0px",
bottom: "0px",
left: "0px"
};
}
const splatted = val.trim().split(/\s+/g).slice(0, 4);
switch (splatted.length) {
case 1: {
return {
top: splatted[0],
right: splatted[0],
bottom: splatted[0],
left: splatted[0]
};
}
case 2: {
return {
top: splatted[0],
right: splatted[1],
bottom: splatted[0],
left: splatted[1]
};
}
case 3: {
return {
top: splatted[0],
right: splatted[1],
bottom: splatted[2],
left: splatted[1]
};
}
case 4: {
return {
top: splatted[0],
right: splatted[1],
bottom: splatted[2],
left: splatted[3]
};
}
}
}; | 17.642857 | 65 | 0.473684 | 51 | 1 | 0 | 1 | 2 | 4 | 0 | 0 | 5 | 1 | 0 | 43 | 321 | 0.006231 | 0.006231 | 0.012461 | 0.003115 | 0 | 0 | 0.625 | 0.209347 |
export type PaddingValue = {
top;
right;
bottom;
left;
};
export const parsePaddingValue = (val) => {
if (!val) {
return {
top: "0px",
right: "0px",
bottom: "0px",
left: "0px"
};
}
const splatted = val.trim().split(/\s+/g).slice(0, 4);
switch (splatted.length) {
case 1: {
return {
top: splatted[0],
right: splatted[0],
bottom: splatted[0],
left: splatted[0]
};
}
case 2: {
return {
top: splatted[0],
right: splatted[1],
bottom: splatted[0],
left: splatted[1]
};
}
case 3: {
return {
top: splatted[0],
right: splatted[1],
bottom: splatted[2],
left: splatted[1]
};
}
case 4: {
return {
top: splatted[0],
right: splatted[1],
bottom: splatted[2],
left: splatted[3]
};
}
}
}; |
2d7090fa39e4a121bd86a59fbe8e23cef3d6c4d4 | 2,707 | ts | TypeScript | src/convert.ts | imagine10255/jsutils | efb7434ccd17d907a8a0ea6e49999019101448a5 | [
"MIT"
] | 4 | 2022-02-06T09:48:53.000Z | 2022-02-17T14:40:17.000Z | src/convert.ts | imagine10255/jsutils | efb7434ccd17d907a8a0ea6e49999019101448a5 | [
"MIT"
] | null | null | null | src/convert.ts | imagine10255/jsutils | efb7434ccd17d907a8a0ea6e49999019101448a5 | [
"MIT"
] | null | null | null | /**
* RGB轉HEX(16進位)色碼
* ex: rbg(0,0,0) -> #000000
*
* @param rgbStr RGB字串
*/
export function rgbToHex(rgbStr: string): string|undefined {
const hexDigits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
const hex = function (x: any) {
return Number.isNaN(x) ? '00' : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
};
const tmp = rgbStr.toLowerCase().match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
if(tmp!== null && tmp.length > 3){
return ['#', hex(tmp[1]) + hex(tmp[2]) + hex(tmp[3])].join('');
}
return undefined;
}
/**
* HEX(16進位)色碼轉轉RGB
* ex: #000000 -> rgb(0,0,0)
* @param hexStr HEX字串
* @param opacity 透明度 (提供透明度參數的話, 會轉回 RGBA)
*/
export function hexToRGB(hexStr: string, opacity = 1): string|undefined {
let newHexStr = hexStr.replace('#', '');
const defaultReturn = undefined;
let regMatch: RegExpMatchArray|null;
if (/^[0-9A-F]{3}$|^[0-9A-F]{6}$/.test(newHexStr.toUpperCase())) {
if (newHexStr.length === 3) {
regMatch = newHexStr.match(/[0-9A-F]/g);
if(!regMatch){
return defaultReturn;
}
newHexStr = regMatch[0] + regMatch[0] + regMatch[1] + regMatch[1] + regMatch[2] + regMatch[2];
}
const r = parseInt(newHexStr.substr(0, 2), 16);
const g = parseInt(newHexStr.substr(2, 2), 16);
const b = parseInt(newHexStr.substr(4, 2), 16);
if(opacity < 1){
const opacityStr = opacity.toString().replace('0.','.');
return `rgba(${[r, g, b, opacityStr].join()})`;
}
return `rgb(${[r, g, b].join()})`;
}
return defaultReturn;
}
/**
* 過濾只剩下數字
* ex: asd1234 -> 1234
*
* @param value
* @param defaultValue
*/
export function filterNumber(value: any, defaultValue = 0): number {
const reg = new RegExp(/^\d+$/);
if(reg.test(value)){
return Number(value);
}
return defaultValue;
}
/**
* 轉數字
* ex: 1234 -> 1234
*
* @param value
* @param defaultValue
*/
export function anyToNumber(value: any, defaultValue = 0): number {
const numberValue = Number(value);
if(!isNaN(numberValue)){
return numberValue;
}
return defaultValue;
}
/**
* 轉布林
* ex: 'true' => true
*
* @param value
* @param isNotBooleanToUndefined
*/
export function anyToBoolean(value: any, isNotBooleanToUndefined = true): boolean|undefined {
if(value === 'true' || value === true || value === 1) {
return true;
}else if(value === 'false' || value === 0 || value === false){
return false;
}else if(isNotBooleanToUndefined){
return undefined;
}
return false;
}
| 23.955752 | 106 | 0.550425 | 58 | 6 | 0 | 10 | 12 | 0 | 1 | 4 | 7 | 0 | 0 | 8.166667 | 952 | 0.016807 | 0.012605 | 0 | 0 | 0 | 0.142857 | 0.25 | 0.24821 | /**
* RGB轉HEX(16進位)色碼
* ex: rbg(0,0,0) -> #000000
*
* @param rgbStr RGB字串
*/
export function rgbToHex(rgbStr) {
const hexDigits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
/* Example usages of 'hex' are shown below:
hex(tmp[1]) + hex(tmp[2]) + hex(tmp[3]);
*/
const hex = function (x) {
return Number.isNaN(x) ? '00' : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
};
const tmp = rgbStr.toLowerCase().match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
if(tmp!== null && tmp.length > 3){
return ['#', hex(tmp[1]) + hex(tmp[2]) + hex(tmp[3])].join('');
}
return undefined;
}
/**
* HEX(16進位)色碼轉轉RGB
* ex: #000000 -> rgb(0,0,0)
* @param hexStr HEX字串
* @param opacity 透明度 (提供透明度參數的話, 會轉回 RGBA)
*/
export function hexToRGB(hexStr, opacity = 1) {
let newHexStr = hexStr.replace('#', '');
const defaultReturn = undefined;
let regMatch;
if (/^[0-9A-F]{3}$|^[0-9A-F]{6}$/.test(newHexStr.toUpperCase())) {
if (newHexStr.length === 3) {
regMatch = newHexStr.match(/[0-9A-F]/g);
if(!regMatch){
return defaultReturn;
}
newHexStr = regMatch[0] + regMatch[0] + regMatch[1] + regMatch[1] + regMatch[2] + regMatch[2];
}
const r = parseInt(newHexStr.substr(0, 2), 16);
const g = parseInt(newHexStr.substr(2, 2), 16);
const b = parseInt(newHexStr.substr(4, 2), 16);
if(opacity < 1){
const opacityStr = opacity.toString().replace('0.','.');
return `rgba(${[r, g, b, opacityStr].join()})`;
}
return `rgb(${[r, g, b].join()})`;
}
return defaultReturn;
}
/**
* 過濾只剩下數字
* ex: asd1234 -> 1234
*
* @param value
* @param defaultValue
*/
export function filterNumber(value, defaultValue = 0) {
const reg = new RegExp(/^\d+$/);
if(reg.test(value)){
return Number(value);
}
return defaultValue;
}
/**
* 轉數字
* ex: 1234 -> 1234
*
* @param value
* @param defaultValue
*/
export function anyToNumber(value, defaultValue = 0) {
const numberValue = Number(value);
if(!isNaN(numberValue)){
return numberValue;
}
return defaultValue;
}
/**
* 轉布林
* ex: 'true' => true
*
* @param value
* @param isNotBooleanToUndefined
*/
export function anyToBoolean(value, isNotBooleanToUndefined = true) {
if(value === 'true' || value === true || value === 1) {
return true;
}else if(value === 'false' || value === 0 || value === false){
return false;
}else if(isNotBooleanToUndefined){
return undefined;
}
return false;
}
|
53173684348d5e070d23374b9d5995b44b7efee5 | 7,885 | ts | TypeScript | src/utilities/codeGenerator.ts | thomasfum/Lemmings.ts | be6c6a959703160807d2bf179ecd75439c45e842 | [
"MIT"
] | 1 | 2022-01-29T13:54:44.000Z | 2022-01-29T13:54:44.000Z | src/utilities/codeGenerator.ts | thomasfum/Lemmings.ts | be6c6a959703160807d2bf179ecd75439c45e842 | [
"MIT"
] | null | null | null | src/utilities/codeGenerator.ts | thomasfum/Lemmings.ts | be6c6a959703160807d2bf179ecd75439c45e842 | [
"MIT"
] | null | null | null | /// This file is part of "Lemmings.js" project, which is made available under the terms of the MIT License (MIT). Note the file "LICENSE" for license and warranty information.
///
/// The CodeGenerator Class is used to parse and generate Lemmings-Level-Codes like "JLDLCINECR"
/// use:
/// reverseCode(STRING LemmingsCodeStr);
/// createCode(INT levelIndex, INT percent, GAME.VERSION gameVersion)
module Lemmings {
/*
interface codeInfo {
levelIndex: number ;//=0
percent: number;// = 100;
lemmingsVersion: string;// = null;
failCount: number;// = 0;
suprise: number;// = 0;
}
*/
export class CodeGenerator {
//private codeBase:Array<string>;
//---
// nibble 0 | nibble 1 | nibble 2 | nibble 3 | nibble 4 | nibble 5 | nibble 6
// -----------|-----------|-----------|-----------|-----------|-----------|----------
// 3 2 1 0| 3 2 1 0| 3 2 1 0| 3 2 1 0| 3 2 1 0| 3 2 1 0| 3 2 1 0
// 8 4 2 1| 8 4 2 1| 8 4 2 1| 8 4 2 1| 8 4 2 1| 8 4 2 1| 8 4 2 1
// | | | | | |
// 3 2 1 0| 7 6 5 4|11 10 9 8|15 14 13 12|19 18 17 16|23 22 21 20|27 26 25 24
// | | | | | |
// L0 P0 F0 S0|S1 L1 0 P1|S2 L2 P2 F1|S4 S3 P3 L3|P4 S5 L4 F2|S6 P5 F3 L5|L7 L6 0 P6
// 0 = fixed bitvalue: must be zero, otherwise the code is not accepted!
// Ln = level bits: L6 is most significant, L0 is least significant
// Pn = previous percentage bits: P6 is most-, P0 is least significant
// Sn = spurious bits: S6 is used here as most, S0 as least significant
// Fn = previous number of times the level was failed Bits
// nibble 7 : least significant bits of level index
// nibble 8 : most significant bits of level index
// nibble 9 : Checksum
/*
this.codeBase = new Array(7);
this.codeBase[gameObject.VERSION.LEMMINGS.value] = "AJHLDHBBCJ";
this.codeBase[gameObject.VERSION.OHNO.value] = "AHPTDHBBAD";
this.codeBase[gameObject.VERSION.HOLIDAY93.value]= "AJHLDHBBAD";
this.codeBase[gameObject.VERSION.HOLIDAY94.value]= "AJPLDHBBCD";
this.codeBase[gameObject.VERSION.XMAS91.value] = this.codeBase[gameObject.VERSION.LEMMINGS.value]; //- they use the same codebase
this.codeBase[gameObject.VERSION.XMAS92.value] = this.codeBase[gameObject.VERSION.LEMMINGS.value];
this.game = gameObject;
var self = this;
*/
/*
//- result structure
function codeInfo()
{
this.levelIndex = 0;
this.percent = 100;
this.lemmingsVersion = null;
this.failCount = 0;
this.suprise = 0;
}
*/
constructor() {
/*
this.codeBase = new Array(7);
this.codeBase["gameObject.VERSION.LEMMINGS.value"] = "AJHLDHBBCJ";
this.codeBase["gameObject.VERSION.OHNO.value"] = "AHPTDHBBAD";
this.codeBase["gameObject.VERSION.HOLIDAY93.value"]= "AJHLDHBBAD";
this.codeBase["gameObject.VERSION.HOLIDAY94.value"]= "AJPLDHBBCD";
this.codeBase["gameObject.VERSION.XMAS91.value"] = this.codeBase["gameObject.VERSION.LEMMINGS.value"]; //- they use the same codebase
this.codeBase["gameObject.VERSION.XMAS92.value"] = this.codeBase["gameObject.VERSION.LEMMINGS.value"];
*/
}
/*
//- return (codeInfo) from Lemmings-Code.
//const bar = { levelValue: 0, persentValue: 0, supriseValue: 0, failValue: 0 ,lemmingsVersion: "" };
public reverseCode(codeString: string, configs: GameConfig[], model: {levelValue: number; persentValue: number; supriseValue: number; failValue: number;gameID: number })
{
for (var i = 0; i < configs.length; i++)
{
var ret = this.reverseCodeSub(codeString, configs[i].accessCodeKey, model);
if(ret==0)
{
model.gameID=configs[i].gameID;
return 0;
}
}
return -1;
//----------------
//- check for all know Lemmings Versions
for (var versionName in gameObject.VERSION)
{
//var version = gameObject.VERSION[versionName];
var ret = this.reverseCodeSub(codeString, codeBase, model);
if(ret==0)
model.gameID=ID;
//if (inf != null) return inf;
}
//----------------
return ret;
}
*/
public reverseCodeSub(codeString:string, codeBase: string, model: {levelValue: number; persentValue: number; supriseValue: number; failValue: number;gameID: number })
{
if (codeString.length != 10) return -1;
//var codeBase = this.codeBase[gameVersion];
//- CodeBase Offsets
var Ofc = new Array(codeBase.length);
for (var i = 0; i < codeBase.length; i++)
{
Ofc[i] = codeBase.charCodeAt(i);
}
//- convert code to int Array
var code = new Array(10);
for (var i = 0; i < 10; i++)
{
code[i] = codeString.charCodeAt(i);
}
//- calculate and check the checksum
var csum = 0;
for (var i = 0; i < 9; i++) csum += code[i];
if ((Ofc[9] + (csum & 0x0F)) != code[9]) return null;
//- get level Index from code
var l1 = (code[7] - Ofc[7]);
var l2 = (code[8] - Ofc[8]);
if ((l1 < 0) || (l2 < 0) || (l1 > 0x0F) || (l2 > 0x0F)) return null;
var levelIndex = l1 | (l2 << 4);
//- unrotate code
var codeVal = new Array(8);
codeVal[7] = 0;
for (var i = 0; i < 7; i++)
{
var j = (i + 8 - (levelIndex % 8)) % 7;
codeVal[i] = code[j] - Ofc[i];
}
//- extract value by bit position
function generateValue(codeValue, bitPosList)
{
var value = 0;
for (var i = 0; i < bitPosList.length; i++)
{
var pos = bitPosList[i];
var nibble = codeValue[Math.floor(pos / 4)];
var bit = (nibble >>> (pos % 4)) & 0x01;
value = value | (bit << i);
}
return value;
}
//- do extract
var nullValue = generateValue(codeVal, [5, 25]);
model.levelValue = generateValue(codeVal, [3, 6, 10, 12, 17, 20, 26, 27]);
model.persentValue = generateValue(codeVal, [2, 4, 9, 13, 19, 22, 24]);
model.supriseValue = generateValue(codeVal, [0, 7, 11, 14, 15, 18, 23]);
model.failValue = generateValue(codeVal, [1, 8, 16, 21]);
if (nullValue != 0) return -1;
if (model.levelValue != levelIndex) return -1;
//var ret = new codeInfo();
//ret.levelIndex = levelValue;
//ret.percent = persentValue;
//model.lemmingsVersion = gameVersion;
//ret.failCount = failValue;
//ret.suprise = supriseValue;
return 0;
}
public createCode (levelIndex:number, percent:number, codeBase:string)
{
//- ToDo: refactor this function using 8 bit for Lbit.
//if (typeof gameVersion === "undefined") gameVersion = self.game.VERSION.LEMMINGS;
if (typeof percent === "undefined") percent = 100;
var result = new Array(9);
var Lbit = [3, 2, 2, 0, 1, 0, 2]; //- where to place the Level bits in result
var Pbit = [2, 0, 1, 1, 3, 2, 0]; //- where to place the Percentage bits in result
//- CodeBase Offsets
//var codeBase = this.codeBase[gameVersion];
var Ofc = new Array(codeBase.length);
for (var i = 0; i < codeBase.length; i++)
{
Ofc[i] = codeBase.charCodeAt(i);
}
//- bit selector
var bitmask = 1;
for (var j = 0; j < 7; j++)
{
//- add level bit
var nibble = (levelIndex & bitmask) << Lbit[j];
//- add percent bit
nibble = nibble + ((percent & bitmask) << Pbit[j]);
//- rotate the order
var i = (j + 8 - (levelIndex % 8)) % 7;
//- assemble the rotated character
result[i] = Ofc[j] + (nibble >>> j);
// next bit
bitmask = bitmask << 1;
}
//- add level characters
result[7] = Ofc[7] + ((levelIndex & 0x0F));
result[8] = Ofc[8] + ((levelIndex & 0xF0) >>> 4);
//- calculating the checksum
var csum = 0;
for (var i = 0; i < 9; i++) csum += result[i];
//- add checksum
result[9] = Ofc[9] + (csum & 0x0F);
//- combine all characters to a proper level string
var Levelcode = "";
for (var i = 0; i < 10; i++)
{
Levelcode += String.fromCharCode(result[i]);
}
return Levelcode;
}
}
}
| 31.043307 | 175 | 0.598224 | 86 | 4 | 0 | 8 | 31 | 0 | 1 | 0 | 10 | 1 | 1 | 20.75 | 2,972 | 0.004038 | 0.010431 | 0 | 0.000336 | 0.000336 | 0 | 0.232558 | 0.214058 | /// This file is part of "Lemmings.js" project, which is made available under the terms of the MIT License (MIT). Note the file "LICENSE" for license and warranty information.
///
/// The CodeGenerator Class is used to parse and generate Lemmings-Level-Codes like "JLDLCINECR"
/// use:
/// reverseCode(STRING LemmingsCodeStr);
/// createCode(INT levelIndex, INT percent, GAME.VERSION gameVersion)
module Lemmings {
/*
interface codeInfo {
levelIndex: number ;//=0
percent: number;// = 100;
lemmingsVersion: string;// = null;
failCount: number;// = 0;
suprise: number;// = 0;
}
*/
export class CodeGenerator {
//private codeBase:Array<string>;
//---
// nibble 0 | nibble 1 | nibble 2 | nibble 3 | nibble 4 | nibble 5 | nibble 6
// -----------|-----------|-----------|-----------|-----------|-----------|----------
// 3 2 1 0| 3 2 1 0| 3 2 1 0| 3 2 1 0| 3 2 1 0| 3 2 1 0| 3 2 1 0
// 8 4 2 1| 8 4 2 1| 8 4 2 1| 8 4 2 1| 8 4 2 1| 8 4 2 1| 8 4 2 1
// | | | | | |
// 3 2 1 0| 7 6 5 4|11 10 9 8|15 14 13 12|19 18 17 16|23 22 21 20|27 26 25 24
// | | | | | |
// L0 P0 F0 S0|S1 L1 0 P1|S2 L2 P2 F1|S4 S3 P3 L3|P4 S5 L4 F2|S6 P5 F3 L5|L7 L6 0 P6
// 0 = fixed bitvalue: must be zero, otherwise the code is not accepted!
// Ln = level bits: L6 is most significant, L0 is least significant
// Pn = previous percentage bits: P6 is most-, P0 is least significant
// Sn = spurious bits: S6 is used here as most, S0 as least significant
// Fn = previous number of times the level was failed Bits
// nibble 7 : least significant bits of level index
// nibble 8 : most significant bits of level index
// nibble 9 : Checksum
/*
this.codeBase = new Array(7);
this.codeBase[gameObject.VERSION.LEMMINGS.value] = "AJHLDHBBCJ";
this.codeBase[gameObject.VERSION.OHNO.value] = "AHPTDHBBAD";
this.codeBase[gameObject.VERSION.HOLIDAY93.value]= "AJHLDHBBAD";
this.codeBase[gameObject.VERSION.HOLIDAY94.value]= "AJPLDHBBCD";
this.codeBase[gameObject.VERSION.XMAS91.value] = this.codeBase[gameObject.VERSION.LEMMINGS.value]; //- they use the same codebase
this.codeBase[gameObject.VERSION.XMAS92.value] = this.codeBase[gameObject.VERSION.LEMMINGS.value];
this.game = gameObject;
var self = this;
*/
/*
//- result structure
function codeInfo()
{
this.levelIndex = 0;
this.percent = 100;
this.lemmingsVersion = null;
this.failCount = 0;
this.suprise = 0;
}
*/
constructor() {
/*
this.codeBase = new Array(7);
this.codeBase["gameObject.VERSION.LEMMINGS.value"] = "AJHLDHBBCJ";
this.codeBase["gameObject.VERSION.OHNO.value"] = "AHPTDHBBAD";
this.codeBase["gameObject.VERSION.HOLIDAY93.value"]= "AJHLDHBBAD";
this.codeBase["gameObject.VERSION.HOLIDAY94.value"]= "AJPLDHBBCD";
this.codeBase["gameObject.VERSION.XMAS91.value"] = this.codeBase["gameObject.VERSION.LEMMINGS.value"]; //- they use the same codebase
this.codeBase["gameObject.VERSION.XMAS92.value"] = this.codeBase["gameObject.VERSION.LEMMINGS.value"];
*/
}
/*
//- return (codeInfo) from Lemmings-Code.
//const bar = { levelValue: 0, persentValue: 0, supriseValue: 0, failValue: 0 ,lemmingsVersion: "" };
public reverseCode(codeString: string, configs: GameConfig[], model: {levelValue: number; persentValue: number; supriseValue: number; failValue: number;gameID: number })
{
for (var i = 0; i < configs.length; i++)
{
var ret = this.reverseCodeSub(codeString, configs[i].accessCodeKey, model);
if(ret==0)
{
model.gameID=configs[i].gameID;
return 0;
}
}
return -1;
//----------------
//- check for all know Lemmings Versions
for (var versionName in gameObject.VERSION)
{
//var version = gameObject.VERSION[versionName];
var ret = this.reverseCodeSub(codeString, codeBase, model);
if(ret==0)
model.gameID=ID;
//if (inf != null) return inf;
}
//----------------
return ret;
}
*/
public reverseCodeSub(codeString, codeBase, model)
{
if (codeString.length != 10) return -1;
//var codeBase = this.codeBase[gameVersion];
//- CodeBase Offsets
var Ofc = new Array(codeBase.length);
for (var i = 0; i < codeBase.length; i++)
{
Ofc[i] = codeBase.charCodeAt(i);
}
//- convert code to int Array
var code = new Array(10);
for (var i = 0; i < 10; i++)
{
code[i] = codeString.charCodeAt(i);
}
//- calculate and check the checksum
var csum = 0;
for (var i = 0; i < 9; i++) csum += code[i];
if ((Ofc[9] + (csum & 0x0F)) != code[9]) return null;
//- get level Index from code
var l1 = (code[7] - Ofc[7]);
var l2 = (code[8] - Ofc[8]);
if ((l1 < 0) || (l2 < 0) || (l1 > 0x0F) || (l2 > 0x0F)) return null;
var levelIndex = l1 | (l2 << 4);
//- unrotate code
var codeVal = new Array(8);
codeVal[7] = 0;
for (var i = 0; i < 7; i++)
{
var j = (i + 8 - (levelIndex % 8)) % 7;
codeVal[i] = code[j] - Ofc[i];
}
//- extract value by bit position
/* Example usages of 'generateValue' are shown below:
generateValue(codeVal, [5, 25]);
model.levelValue = generateValue(codeVal, [3, 6, 10, 12, 17, 20, 26, 27]);
model.persentValue = generateValue(codeVal, [2, 4, 9, 13, 19, 22, 24]);
model.supriseValue = generateValue(codeVal, [0, 7, 11, 14, 15, 18, 23]);
model.failValue = generateValue(codeVal, [1, 8, 16, 21]);
*/
function generateValue(codeValue, bitPosList)
{
var value = 0;
for (var i = 0; i < bitPosList.length; i++)
{
var pos = bitPosList[i];
var nibble = codeValue[Math.floor(pos / 4)];
var bit = (nibble >>> (pos % 4)) & 0x01;
value = value | (bit << i);
}
return value;
}
//- do extract
var nullValue = generateValue(codeVal, [5, 25]);
model.levelValue = generateValue(codeVal, [3, 6, 10, 12, 17, 20, 26, 27]);
model.persentValue = generateValue(codeVal, [2, 4, 9, 13, 19, 22, 24]);
model.supriseValue = generateValue(codeVal, [0, 7, 11, 14, 15, 18, 23]);
model.failValue = generateValue(codeVal, [1, 8, 16, 21]);
if (nullValue != 0) return -1;
if (model.levelValue != levelIndex) return -1;
//var ret = new codeInfo();
//ret.levelIndex = levelValue;
//ret.percent = persentValue;
//model.lemmingsVersion = gameVersion;
//ret.failCount = failValue;
//ret.suprise = supriseValue;
return 0;
}
public createCode (levelIndex, percent, codeBase)
{
//- ToDo: refactor this function using 8 bit for Lbit.
//if (typeof gameVersion === "undefined") gameVersion = self.game.VERSION.LEMMINGS;
if (typeof percent === "undefined") percent = 100;
var result = new Array(9);
var Lbit = [3, 2, 2, 0, 1, 0, 2]; //- where to place the Level bits in result
var Pbit = [2, 0, 1, 1, 3, 2, 0]; //- where to place the Percentage bits in result
//- CodeBase Offsets
//var codeBase = this.codeBase[gameVersion];
var Ofc = new Array(codeBase.length);
for (var i = 0; i < codeBase.length; i++)
{
Ofc[i] = codeBase.charCodeAt(i);
}
//- bit selector
var bitmask = 1;
for (var j = 0; j < 7; j++)
{
//- add level bit
var nibble = (levelIndex & bitmask) << Lbit[j];
//- add percent bit
nibble = nibble + ((percent & bitmask) << Pbit[j]);
//- rotate the order
var i = (j + 8 - (levelIndex % 8)) % 7;
//- assemble the rotated character
result[i] = Ofc[j] + (nibble >>> j);
// next bit
bitmask = bitmask << 1;
}
//- add level characters
result[7] = Ofc[7] + ((levelIndex & 0x0F));
result[8] = Ofc[8] + ((levelIndex & 0xF0) >>> 4);
//- calculating the checksum
var csum = 0;
for (var i = 0; i < 9; i++) csum += result[i];
//- add checksum
result[9] = Ofc[9] + (csum & 0x0F);
//- combine all characters to a proper level string
var Levelcode = "";
for (var i = 0; i < 10; i++)
{
Levelcode += String.fromCharCode(result[i]);
}
return Levelcode;
}
}
}
|
53c8b3641c618b83c79e77ede4eda6e0edc139b8 | 3,190 | ts | TypeScript | kth-largest-element-in-a-stream/PriorityQueue.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | 1 | 2022-03-30T11:10:14.000Z | 2022-03-30T11:10:14.000Z | kth-largest-element-in-a-stream/PriorityQueue.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | null | null | null | kth-largest-element-in-a-stream/PriorityQueue.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | null | null | null | // deno-lint-ignore no-explicit-any
export interface PriorityQueue<T = any> {
clear: () => void;
length: () => number;
comparator: (a: T, b: T) => number;
offer: (value: T) => void;
head: () => T | undefined;
tail: () => T | undefined;
pop: () => T | undefined;
shift: () => T | undefined;
// at: (index: number) => T | undefined;
}
/**
* Your KthLargest object will be instantiated and called as such:
* var obj = new KthLargest(k, nums)
* var param_1 = obj.add(val)
*/
// deno-lint-ignore no-explicit-any
export function PriorityQueue<T = any>(
comparator: (a: T, b: T) => number,
): PriorityQueue<T> {
//默认升序
//comparator Function used to determine the order of the elements. It is expected to return a negative value if the head argument is less than the second argument, zero if they're equal, and a positive value otherwise.
const data: T[] = [];
function length(): number {
return data.length;
}
function swap(i1: number, i2: number) {
[data[i1], data[i2]] = [data[i2], data[i1]];
}
function bubble_head_to_tail() {
if (data.length < 2) {
return;
}
for (let i = 0, j = 1; j < data.length && i < data.length; i++, j++) {
if (comparator(data[i], data[j]) > 0) {
swap(i, j);
} else {
break;
}
}
}
function bubble_tail_to_head() {
if (data.length < 2) {
return;
}
for (
let i = data.length - 2, j = data.length - 1;
j >= 0 && i >= 0;
i--, j--
) {
if (comparator(data[i], data[j]) > 0) {
swap(i, j);
} else {
break;
}
}
}
function offer(value: T) {
const f = head();
if (typeof f === "undefined") {
data.push(value);
return;
}
const l = tail();
if (typeof l === "undefined") {
data.push(value);
return;
}
if (comparator(value, l) > 0) {
data.push(value);
} else if (comparator(value, f) < 0) {
data.unshift(value);
} else {
if (comparator(value, data[Math.floor(data.length / 2)]) > 0) {
data.push(value);
bubble_tail_to_head();
} else {
data.unshift(value);
bubble_head_to_tail();
}
}
}
function head() {
if (!data.length) {
return undefined;
}
return data[0];
}
function tail() {
if (!data.length) {
return undefined;
}
return data[data.length - 1];
}
function pop() {
return data.pop();
}
function shift() {
return data.shift();
}
function clear() {
data.length = 0;
}
//function at(index: number): T | undefined {
// return data.at(index);
// }
return {
clear,
length,
comparator,
offer,
head,
tail,
pop,
shift, /*, at*/
};
}
| 26.147541 | 222 | 0.464577 | 105 | 11 | 0 | 4 | 7 | 8 | 7 | 2 | 8 | 1 | 2 | 13.727273 | 865 | 0.017341 | 0.008092 | 0.009249 | 0.001156 | 0.002312 | 0.066667 | 0.266667 | 0.238983 | // deno-lint-ignore no-explicit-any
export interface PriorityQueue<T = any> {
clear;
length;
comparator;
offer;
head;
tail;
pop;
shift;
// at: (index: number) => T | undefined;
}
/**
* Your KthLargest object will be instantiated and called as such:
* var obj = new KthLargest(k, nums)
* var param_1 = obj.add(val)
*/
// deno-lint-ignore no-explicit-any
export /* Example usages of 'PriorityQueue' are shown below:
// deno-lint-ignore no-explicit-any
;
*/
function PriorityQueue<T = any>(
comparator,
) {
//默认升序
//comparator Function used to determine the order of the elements. It is expected to return a negative value if the head argument is less than the second argument, zero if they're equal, and a positive value otherwise.
const data = [];
/* Example usages of 'length' are shown below:
;
data.length;
data.length < 2;
j < data.length && i < data.length;
data.length - 2;
data.length - 1;
comparator(value, data[Math.floor(data.length / 2)]) > 0;
!data.length;
data[data.length - 1];
data.length = 0;
*/
function length() {
return data.length;
}
/* Example usages of 'swap' are shown below:
swap(i, j);
*/
function swap(i1, i2) {
[data[i1], data[i2]] = [data[i2], data[i1]];
}
/* Example usages of 'bubble_head_to_tail' are shown below:
bubble_head_to_tail();
*/
function bubble_head_to_tail() {
if (data.length < 2) {
return;
}
for (let i = 0, j = 1; j < data.length && i < data.length; i++, j++) {
if (comparator(data[i], data[j]) > 0) {
swap(i, j);
} else {
break;
}
}
}
/* Example usages of 'bubble_tail_to_head' are shown below:
bubble_tail_to_head();
*/
function bubble_tail_to_head() {
if (data.length < 2) {
return;
}
for (
let i = data.length - 2, j = data.length - 1;
j >= 0 && i >= 0;
i--, j--
) {
if (comparator(data[i], data[j]) > 0) {
swap(i, j);
} else {
break;
}
}
}
/* Example usages of 'offer' are shown below:
;
*/
function offer(value) {
const f = head();
if (typeof f === "undefined") {
data.push(value);
return;
}
const l = tail();
if (typeof l === "undefined") {
data.push(value);
return;
}
if (comparator(value, l) > 0) {
data.push(value);
} else if (comparator(value, f) < 0) {
data.unshift(value);
} else {
if (comparator(value, data[Math.floor(data.length / 2)]) > 0) {
data.push(value);
bubble_tail_to_head();
} else {
data.unshift(value);
bubble_head_to_tail();
}
}
}
/* Example usages of 'head' are shown below:
;
head();
*/
function head() {
if (!data.length) {
return undefined;
}
return data[0];
}
/* Example usages of 'tail' are shown below:
;
tail();
*/
function tail() {
if (!data.length) {
return undefined;
}
return data[data.length - 1];
}
/* Example usages of 'pop' are shown below:
;
data.pop();
*/
function pop() {
return data.pop();
}
/* Example usages of 'shift' are shown below:
;
data.shift();
*/
function shift() {
return data.shift();
}
/* Example usages of 'clear' are shown below:
;
*/
function clear() {
data.length = 0;
}
//function at(index: number): T | undefined {
// return data.at(index);
// }
return {
clear,
length,
comparator,
offer,
head,
tail,
pop,
shift, /*, at*/
};
}
|
b62c8bfe1590c97521b9f5bf7d474822cf2a9964 | 2,005 | ts | TypeScript | src/workbench/browser/src/app/utils/index.ts | scarqin/eoapi | 6b78189e389691f1da1c8d8f98fadbbfd05f3e57 | [
"Apache-2.0"
] | 6 | 2022-03-05T15:50:44.000Z | 2022-03-25T14:13:19.000Z | src/workbench/browser/src/app/utils/index.ts | scarqin/eoapi | 6b78189e389691f1da1c8d8f98fadbbfd05f3e57 | [
"Apache-2.0"
] | 8 | 2022-03-14T06:13:41.000Z | 2022-03-25T03:18:23.000Z | src/workbench/browser/src/app/utils/index.ts | scarqin/eoapi | 6b78189e389691f1da1c8d8f98fadbbfd05f3e57 | [
"Apache-2.0"
] | 6 | 2022-02-15T02:50:35.000Z | 2022-03-30T02:34:48.000Z | export const uuid = (): string => Math.random().toString(36).slice(-8);
// const DOMAIN_REGEX =
// '(^((http|wss|ws|ftp|https)://))|(^(((http|wss|ws|ftp|https)://)|)(([\\w\\-_]+([\\w\\-\\.]*)?(\\.(' +
// DOMAIN_CONSTANT.join('|') +
// ')))|((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(localhost))((\\/)|(\\?)|(:)|($)))';
export const whatType = (data: any): string => {
if (data === undefined) {
return 'undefined';
}
if (data === null) {
return 'null';
}
if (data instanceof Array) {
return 'array';
}
if (data instanceof Object) {
return 'object';
}
if (typeof data === 'string') {
return 'string';
}
if (typeof data === 'number') {
return 'number';
}
if (typeof data === 'boolean') {
return 'boolean';
}
return 'unknown';
};
/**
* judge text content type
* @returns textType - xml|json|html|text
*/
export const whatTextType = (tmpText) => {
// TODO it can be better
const tmpCompareText = tmpText.replace(/\s/g, '');
if (/^({|\[)(.*)(}|])$/.test(tmpCompareText) && JSON.parse(tmpCompareText)) {
return 'json';
} else if (/^(<)(.*)(>)$/.test(tmpCompareText)) {
if (/^(<!DOCTYPEhtml>)|(html)/i.test(tmpCompareText)) {
return 'html';
} else {
return 'xml';
}
} else {
return 'text';
}
};
/**
* reverse object key and value
* @param obj
*/
export const reverseObj = (obj) => {
return Object.keys(obj).reduce((acc, key) => {
acc[obj[key]] = key;
return acc;
}, {});
};
/**
* reverse object key and value
* @param obj
*/
export const objectToArray = (obj) => {
return Object.keys(obj).map((val) => ({
key: val,
value: obj[val],
}));
};
export const isEmptyValue = (obj) => {
const list = Object.keys(obj);
const emptyList = list.filter((it) => !obj[it]);
// * If they length are equal, means each value of obj is empty. like { name: '', value: '' }
return emptyList.length === list.length;
};
| 26.038961 | 153 | 0.539152 | 56 | 9 | 0 | 9 | 9 | 0 | 0 | 1 | 2 | 0 | 5 | 5.888889 | 685 | 0.026277 | 0.013139 | 0 | 0 | 0.007299 | 0.037037 | 0.074074 | 0.272666 | export const uuid = () => Math.random().toString(36).slice(-8);
// const DOMAIN_REGEX =
// '(^((http|wss|ws|ftp|https)://))|(^(((http|wss|ws|ftp|https)://)|)(([\\w\\-_]+([\\w\\-\\.]*)?(\\.(' +
// DOMAIN_CONSTANT.join('|') +
// ')))|((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))|(localhost))((\\/)|(\\?)|(:)|($)))';
export const whatType = (data) => {
if (data === undefined) {
return 'undefined';
}
if (data === null) {
return 'null';
}
if (data instanceof Array) {
return 'array';
}
if (data instanceof Object) {
return 'object';
}
if (typeof data === 'string') {
return 'string';
}
if (typeof data === 'number') {
return 'number';
}
if (typeof data === 'boolean') {
return 'boolean';
}
return 'unknown';
};
/**
* judge text content type
* @returns textType - xml|json|html|text
*/
export const whatTextType = (tmpText) => {
// TODO it can be better
const tmpCompareText = tmpText.replace(/\s/g, '');
if (/^({|\[)(.*)(}|])$/.test(tmpCompareText) && JSON.parse(tmpCompareText)) {
return 'json';
} else if (/^(<)(.*)(>)$/.test(tmpCompareText)) {
if (/^(<!DOCTYPEhtml>)|(html)/i.test(tmpCompareText)) {
return 'html';
} else {
return 'xml';
}
} else {
return 'text';
}
};
/**
* reverse object key and value
* @param obj
*/
export const reverseObj = (obj) => {
return Object.keys(obj).reduce((acc, key) => {
acc[obj[key]] = key;
return acc;
}, {});
};
/**
* reverse object key and value
* @param obj
*/
export const objectToArray = (obj) => {
return Object.keys(obj).map((val) => ({
key: val,
value: obj[val],
}));
};
export const isEmptyValue = (obj) => {
const list = Object.keys(obj);
const emptyList = list.filter((it) => !obj[it]);
// * If they length are equal, means each value of obj is empty. like { name: '', value: '' }
return emptyList.length === list.length;
};
|
b67d5a9639860e5f903060e3fd01de168b0c1924 | 2,656 | ts | TypeScript | src/controllers/TicTocController.ts | ali77gh/NodeAndTypeScriptSamples | 293452042e5bd253babae48eb7cb0203a865a058 | [
"MIT"
] | 1 | 2022-03-12T09:13:36.000Z | 2022-03-12T09:13:36.000Z | src/controllers/TicTocController.ts | ali77gh/NodeAndTypeScriptSamples | 293452042e5bd253babae48eb7cb0203a865a058 | [
"MIT"
] | null | null | null | src/controllers/TicTocController.ts | ali77gh/NodeAndTypeScriptSamples | 293452042e5bd253babae48eb7cb0203a865a058 | [
"MIT"
] | null | null | null |
export default class TicTocController {
static prePath = "/tictoc"
static matris = null;
static whoShouldPlay = 'O'
public static init(app) {
this.clearMatrix()
app.post(this.prePath + "/play/:x/:y", (req, res) => {
let player, x, y
[player, x, y] = this.getInputs(req)
let err = this.validation(player, x, y)
if (err != null)
res.status(400).send(err)
else {
let err = this.play(x, y)
if (err)
res.status(400).send(err)
else
res.status(200).send(this.render())
}
})
app.get(this.prePath + "/render", (req, res) => {
res.status(200).send(this.render())
})
app.post(this.prePath + "/reset", (req, res) => {
this.clearMatrix()
res.status(200).send(this.render())
})
}
static play(x: number, y: number): string | null {
if (this.matris[x][y] == '*')
this.matris[x][y] = this.whoShouldPlay
else
return "cell is not empty"
this.switchTurn()
return null
}
static switchTurn() {
if (this.whoShouldPlay == 'O') this.whoShouldPlay = 'X'
else this.whoShouldPlay = 'O'
}
static render(): string {
let result: string = ""
result += JSON.stringify(this.matris[0]) + "\n"
result += JSON.stringify(this.matris[1]) + "\n"
result += JSON.stringify(this.matris[2]) + "\n"
result += "\n" + "turn: " + this.whoShouldPlay
return result
}
public static clearMatrix() {
this.matris =
[
['*', '*', '*'],
['*', '*', '*'],
['*', '*', '*']
]
}
public static getInputs(req): [string, number, number] {
let player: string = req.header('player')
let x: number = parseInt(req.params["x"])
let y: number = parseInt(req.params["y"])
return [player, x, y]
}
private static validation(player: string, x: number, y: number): null | string {
if (player != 'X' && player != 'O') {
return ("player header should be 'O' or 'X' ")
}
if (player != this.whoShouldPlay) {
return ("its not your turn :(")
}
if (isNaN(x) || isNaN(y)) {
return "x and y should be numbers"
}
if (x > 2 || y > 2 || x < 0 || y < 0) {
return ("x and y params should be between 0 and 2")
}
return null
}
} | 24.145455 | 84 | 0.463855 | 78 | 10 | 0 | 13 | 9 | 3 | 6 | 0 | 15 | 1 | 0 | 7.4 | 718 | 0.032033 | 0.012535 | 0.004178 | 0.001393 | 0 | 0 | 0.428571 | 0.289192 |
export default class TicTocController {
static prePath = "/tictoc"
static matris = null;
static whoShouldPlay = 'O'
public static init(app) {
this.clearMatrix()
app.post(this.prePath + "/play/:x/:y", (req, res) => {
let player, x, y
[player, x, y] = this.getInputs(req)
let err = this.validation(player, x, y)
if (err != null)
res.status(400).send(err)
else {
let err = this.play(x, y)
if (err)
res.status(400).send(err)
else
res.status(200).send(this.render())
}
})
app.get(this.prePath + "/render", (req, res) => {
res.status(200).send(this.render())
})
app.post(this.prePath + "/reset", (req, res) => {
this.clearMatrix()
res.status(200).send(this.render())
})
}
static play(x, y) {
if (this.matris[x][y] == '*')
this.matris[x][y] = this.whoShouldPlay
else
return "cell is not empty"
this.switchTurn()
return null
}
static switchTurn() {
if (this.whoShouldPlay == 'O') this.whoShouldPlay = 'X'
else this.whoShouldPlay = 'O'
}
static render() {
let result = ""
result += JSON.stringify(this.matris[0]) + "\n"
result += JSON.stringify(this.matris[1]) + "\n"
result += JSON.stringify(this.matris[2]) + "\n"
result += "\n" + "turn: " + this.whoShouldPlay
return result
}
public static clearMatrix() {
this.matris =
[
['*', '*', '*'],
['*', '*', '*'],
['*', '*', '*']
]
}
public static getInputs(req) {
let player = req.header('player')
let x = parseInt(req.params["x"])
let y = parseInt(req.params["y"])
return [player, x, y]
}
private static validation(player, x, y) {
if (player != 'X' && player != 'O') {
return ("player header should be 'O' or 'X' ")
}
if (player != this.whoShouldPlay) {
return ("its not your turn :(")
}
if (isNaN(x) || isNaN(y)) {
return "x and y should be numbers"
}
if (x > 2 || y > 2 || x < 0 || y < 0) {
return ("x and y params should be between 0 and 2")
}
return null
}
} |
b6b7584e1530cf203e4ea9a0dc9d7d43c8213a65 | 2,255 | tsx | TypeScript | archguard/src/pages/servicesMap/urlMapping.tsx | archguard/archguard-frontend | 0de4d2e521b3db381e0aa1dd077ee6a0c93078e7 | [
"MIT"
] | 2 | 2022-02-22T02:30:20.000Z | 2022-02-24T11:52:46.000Z | archguard/src/pages/servicesMap/urlMapping.tsx | archguard/archguard-frontend | 0de4d2e521b3db381e0aa1dd077ee6a0c93078e7 | [
"MIT"
] | 1 | 2022-02-22T04:34:35.000Z | 2022-02-22T04:34:35.000Z | archguard/src/pages/servicesMap/urlMapping.tsx | archguard/archguard-frontend | 0de4d2e521b3db381e0aa1dd077ee6a0c93078e7 | [
"MIT"
] | 1 | 2022-02-22T02:22:06.000Z | 2022-02-22T02:22:06.000Z | function getPathFromUrl(url: string) {
return url.split("?")[0];
}
function removeUriSuffixAndPrefix(targetUrl: string) {
let url = targetUrl
if (url.startsWith("@uri@/")) {
url = url.slice("@uri@".length)
}
if (url.endsWith("/@uri@")) {
url = url.slice(0, -"/@uri@".length);
}
return url;
}
export function urlMapping(container: any[], unmapping: any[], elements: { nodes: any[], edges: any[] }) {
let linkData = [];
let resourceMap: any = {}
for (let service of container) {
elements.nodes.push({
id: service.name,
language: service.language,
label: service.name,
})
for (let resource of service.resources) {
// @ts-ignore
resourceMap[resource.sourceUrl] = service.name
}
}
let demandMap: any = {}
function setLink(service: any, resourceName: String) {
let linkKey = JSON.stringify({
id: `${service.name}~${resourceName}`,
source: service.name,
target: resourceName,
});
// @ts-ignore
if (!!demandMap[linkKey]) {
demandMap[linkKey] += 1
} else {
demandMap[linkKey] = 1
}
}
for (let service of container) {
for (let demand of service.demands) {
let targetUrl = getPathFromUrl(demand.targetUrl);
let resourceName = resourceMap[targetUrl];
// first match
if (resourceName) {
setLink(service, resourceName);
continue;
}
// remove `/api/resource/@uri@` || `@uri/api/resource/` to as second match
if (targetUrl.endsWith("@uri@") || targetUrl.startsWith("@uri@")) {
let fixedUrl = removeUriSuffixAndPrefix(targetUrl);
let resourceName = resourceMap[fixedUrl];
if (resourceName) {
setLink(service, resourceName);
} else {
unmapping.push({
service: service.name,
originUrl: demand.originUrl,
url: targetUrl
})
}
} else {
unmapping.push({
service: service.name,
originUrl: demand.originUrl,
url: targetUrl
})
}
}
}
for (let key in demandMap) {
let obj = JSON.parse(key);
obj.value = demandMap[key];
linkData.push(obj)
}
elements.edges = linkData
return linkData;
}
| 25.337079 | 106 | 0.583592 | 76 | 4 | 0 | 7 | 10 | 0 | 3 | 7 | 2 | 0 | 0 | 20 | 599 | 0.018364 | 0.016694 | 0 | 0 | 0 | 0.333333 | 0.095238 | 0.262957 | /* Example usages of 'getPathFromUrl' are shown below:
getPathFromUrl(demand.targetUrl);
*/
function getPathFromUrl(url) {
return url.split("?")[0];
}
/* Example usages of 'removeUriSuffixAndPrefix' are shown below:
removeUriSuffixAndPrefix(targetUrl);
*/
function removeUriSuffixAndPrefix(targetUrl) {
let url = targetUrl
if (url.startsWith("@uri@/")) {
url = url.slice("@uri@".length)
}
if (url.endsWith("/@uri@")) {
url = url.slice(0, -"/@uri@".length);
}
return url;
}
export function urlMapping(container, unmapping, elements) {
let linkData = [];
let resourceMap = {}
for (let service of container) {
elements.nodes.push({
id: service.name,
language: service.language,
label: service.name,
})
for (let resource of service.resources) {
// @ts-ignore
resourceMap[resource.sourceUrl] = service.name
}
}
let demandMap = {}
/* Example usages of 'setLink' are shown below:
setLink(service, resourceName);
*/
function setLink(service, resourceName) {
let linkKey = JSON.stringify({
id: `${service.name}~${resourceName}`,
source: service.name,
target: resourceName,
});
// @ts-ignore
if (!!demandMap[linkKey]) {
demandMap[linkKey] += 1
} else {
demandMap[linkKey] = 1
}
}
for (let service of container) {
for (let demand of service.demands) {
let targetUrl = getPathFromUrl(demand.targetUrl);
let resourceName = resourceMap[targetUrl];
// first match
if (resourceName) {
setLink(service, resourceName);
continue;
}
// remove `/api/resource/@uri@` || `@uri/api/resource/` to as second match
if (targetUrl.endsWith("@uri@") || targetUrl.startsWith("@uri@")) {
let fixedUrl = removeUriSuffixAndPrefix(targetUrl);
let resourceName = resourceMap[fixedUrl];
if (resourceName) {
setLink(service, resourceName);
} else {
unmapping.push({
service: service.name,
originUrl: demand.originUrl,
url: targetUrl
})
}
} else {
unmapping.push({
service: service.name,
originUrl: demand.originUrl,
url: targetUrl
})
}
}
}
for (let key in demandMap) {
let obj = JSON.parse(key);
obj.value = demandMap[key];
linkData.push(obj)
}
elements.edges = linkData
return linkData;
}
|
b6bfc45eb561308bc0f3960f3a75e7c4a2d28a90 | 4,501 | ts | TypeScript | src/lib/chan.ts | hankei6km/promise-chan | 601e52f8db0411bc0ceba8387751cebbb7d9a1b7 | [
"MIT"
] | null | null | null | src/lib/chan.ts | hankei6km/promise-chan | 601e52f8db0411bc0ceba8387751cebbb7d9a1b7 | [
"MIT"
] | 1 | 2022-03-25T11:00:43.000Z | 2022-03-25T11:00:43.000Z | src/lib/chan.ts | hankei6km/promise-chan | 601e52f8db0411bc0ceba8387751cebbb7d9a1b7 | [
"MIT"
] | null | null | null | /**
* Options for Chan.
*/
export type ChanOpts = {
/**
* Yield reject to iterator if the value is rejected in receiver(generator).
*/
rejectInReceiver?: boolean
}
/**
* Class reperesenting a channel.
* @template T - Type of the value that will be send via Channel.
*/
export class Chan<T> {
protected opts: ChanOpts = { rejectInReceiver: false }
protected bufSize = 0
protected buf!: T[]
protected sendFunc!: (p: T) => Promise<void>
protected bufPromise!: Promise<void>
protected bufResolve!: (value: void) => void
protected valuePromise!: Promise<void>
protected valueResolve!: (value: void) => void
protected generatorClosed: boolean = false
protected closed: boolean = false
/**
* Make a channel.
* @param bufSize - size of buffer in channel.
* @param opts - options.
*/
constructor(bufSize: number = 0, opts: ChanOpts = {}) {
if (opts.rejectInReceiver !== undefined) {
this.opts.rejectInReceiver = opts.rejectInReceiver
}
this.bufSize = bufSize === 0 ? 1 : bufSize // バッファーサイズ 0 のときも内部的にはバッファーは必要.
this.sendFunc = bufSize === 0 ? this._sendWithoutBuf : this._sendWithBuf
this.buf = []
this.bufReset()
this.valueReset()
}
protected bufReset() {
this.bufPromise = new Promise((resolve) => {
this.bufResolve = resolve
})
}
protected bufRelease() {
this.bufResolve()
}
protected valueReset() {
this.valuePromise = new Promise((resolve, reject) => {
this.valueResolve = resolve
})
}
protected valueRelease() {
this.valueResolve()
}
protected async _sendWithoutBuf(p: T): Promise<void> {
while (!this.generatorClosed) {
if (this.buf.length < this.bufSize) {
this.buf.push(p)
this.bufRelease()
await this.valuePromise
return
}
await this.valuePromise
}
}
protected async _sendWithBuf(p: T): Promise<void> {
while (!this.generatorClosed) {
if (this.buf.length < this.bufSize) {
this.buf.push(p)
this.bufRelease()
return
}
await this.valuePromise
}
}
/**
* Send the value to receiver via channel.
* This method required to call with `await`.
* It will be blocking durring buffer is filled.
* ```
* await ch.send(value)
* ```
* @param value - the value
* @returns
*/
readonly send = async (value: T): Promise<void> => {
if (this.closed) {
throw new Error('panic: send on closed channel')
}
// TOOD: generatorClosed でループを抜けたかのステータスを返すか検討.
// rejectInReceiver が有効だとバッファーに乗っているものでもドロップするので、
// (yeield で reject を for await...of などに渡すと finally が実行されるので)
// ここのステータスだけわかってもあまり意味はないか.
return this.sendFunc(value)
}
private async gate(): Promise<{ done: boolean }> {
// バッファーが埋まっていない場合は、send されるまで待つ.
// close されていれば素通し.
while (this.buf.length === 0 && !this.closed) {
await this.bufPromise
this.bufReset()
}
// バッファーを消費していたら終了.
// 通常は消費しない、close されていれば何度か呼びだされるうちに消費される.
if (this.buf.length > 0) {
return { done: false }
}
return { done: true }
}
/**
* Get async generator to receive the value was sended.
* @returns - Async Generator.
*/
async *receiver(): AsyncGenerator<Awaited<T>, void, void> {
try {
while (true) {
try {
const i = await this.gate()
if (i.done) {
return
}
const v = await this.buf[0]
// バッファーを空ける(yeild の後でやると次回の next() まで実行されないので注意).
this.buf.shift()
// send 側へ空きができたことを通知.
this.valueRelease()
this.valueReset()
yield v
} catch (e) {
// rejct された場合もバッファーを空ける.
this.buf.shift()
// send 側へ空きができたことを通知.
this.valueRelease()
this.valueReset()
if (this.opts.rejectInReceiver) {
// value が Promise だった場合、receiver 側の for await...of などに reject を伝播させる.
yield Promise.reject(e)
}
}
}
} finally {
this.generatorClosed = true
this.clean()
}
}
protected clean() {
this.bufRelease()
this.valueRelease()
}
/**
* Close channel.
*/
close() {
this.closed = true
this.clean()
}
}
/**
* Type of send method Chan class.
*/
export type ChanSend<T> = Chan<T>['send']
/**
* Type of async generator that is returned from receiver method of Chan class.
*/
export type ChanRecv<T> = ReturnType<Chan<T>['receiver']>
| 26.017341 | 82 | 0.602755 | 115 | 14 | 0 | 8 | 2 | 12 | 6 | 0 | 17 | 4 | 0 | 5.428571 | 1,433 | 0.015352 | 0.001396 | 0.008374 | 0.002791 | 0 | 0 | 0.472222 | 0.215931 | /**
* Options for Chan.
*/
export type ChanOpts = {
/**
* Yield reject to iterator if the value is rejected in receiver(generator).
*/
rejectInReceiver?
}
/**
* Class reperesenting a channel.
* @template T - Type of the value that will be send via Channel.
*/
export class Chan<T> {
protected opts = { rejectInReceiver: false }
protected bufSize = 0
protected buf!
protected sendFunc!
protected bufPromise!
protected bufResolve!
protected valuePromise!
protected valueResolve!
protected generatorClosed = false
protected closed = false
/**
* Make a channel.
* @param bufSize - size of buffer in channel.
* @param opts - options.
*/
constructor(bufSize = 0, opts = {}) {
if (opts.rejectInReceiver !== undefined) {
this.opts.rejectInReceiver = opts.rejectInReceiver
}
this.bufSize = bufSize === 0 ? 1 : bufSize // バッファーサイズ 0 のときも内部的にはバッファーは必要.
this.sendFunc = bufSize === 0 ? this._sendWithoutBuf : this._sendWithBuf
this.buf = []
this.bufReset()
this.valueReset()
}
protected bufReset() {
this.bufPromise = new Promise((resolve) => {
this.bufResolve = resolve
})
}
protected bufRelease() {
this.bufResolve()
}
protected valueReset() {
this.valuePromise = new Promise((resolve, reject) => {
this.valueResolve = resolve
})
}
protected valueRelease() {
this.valueResolve()
}
protected async _sendWithoutBuf(p) {
while (!this.generatorClosed) {
if (this.buf.length < this.bufSize) {
this.buf.push(p)
this.bufRelease()
await this.valuePromise
return
}
await this.valuePromise
}
}
protected async _sendWithBuf(p) {
while (!this.generatorClosed) {
if (this.buf.length < this.bufSize) {
this.buf.push(p)
this.bufRelease()
return
}
await this.valuePromise
}
}
/**
* Send the value to receiver via channel.
* This method required to call with `await`.
* It will be blocking durring buffer is filled.
* ```
* await ch.send(value)
* ```
* @param value - the value
* @returns
*/
readonly send = async (value) => {
if (this.closed) {
throw new Error('panic: send on closed channel')
}
// TOOD: generatorClosed でループを抜けたかのステータスを返すか検討.
// rejectInReceiver が有効だとバッファーに乗っているものでもドロップするので、
// (yeield で reject を for await...of などに渡すと finally が実行されるので)
// ここのステータスだけわかってもあまり意味はないか.
return this.sendFunc(value)
}
private async gate() {
// バッファーが埋まっていない場合は、send されるまで待つ.
// close されていれば素通し.
while (this.buf.length === 0 && !this.closed) {
await this.bufPromise
this.bufReset()
}
// バッファーを消費していたら終了.
// 通常は消費しない、close されていれば何度か呼びだされるうちに消費される.
if (this.buf.length > 0) {
return { done: false }
}
return { done: true }
}
/**
* Get async generator to receive the value was sended.
* @returns - Async Generator.
*/
async *receiver() {
try {
while (true) {
try {
const i = await this.gate()
if (i.done) {
return
}
const v = await this.buf[0]
// バッファーを空ける(yeild の後でやると次回の next() まで実行されないので注意).
this.buf.shift()
// send 側へ空きができたことを通知.
this.valueRelease()
this.valueReset()
yield v
} catch (e) {
// rejct された場合もバッファーを空ける.
this.buf.shift()
// send 側へ空きができたことを通知.
this.valueRelease()
this.valueReset()
if (this.opts.rejectInReceiver) {
// value が Promise だった場合、receiver 側の for await...of などに reject を伝播させる.
yield Promise.reject(e)
}
}
}
} finally {
this.generatorClosed = true
this.clean()
}
}
protected clean() {
this.bufRelease()
this.valueRelease()
}
/**
* Close channel.
*/
close() {
this.closed = true
this.clean()
}
}
/**
* Type of send method Chan class.
*/
export type ChanSend<T> = Chan<T>['send']
/**
* Type of async generator that is returned from receiver method of Chan class.
*/
export type ChanRecv<T> = ReturnType<Chan<T>['receiver']>
|
ac2f2620a73cd8792597b3c5d3baa98411d6543c | 5,850 | ts | TypeScript | src/equal/deepCompare.ts | imagine10255/jsutils | efb7434ccd17d907a8a0ea6e49999019101448a5 | [
"MIT"
] | 4 | 2022-02-06T09:48:53.000Z | 2022-02-17T14:40:17.000Z | src/equal/deepCompare.ts | imagine10255/jsutils | efb7434ccd17d907a8a0ea6e49999019101448a5 | [
"MIT"
] | null | null | null | src/equal/deepCompare.ts | imagine10255/jsutils | efb7434ccd17d907a8a0ea6e49999019101448a5 | [
"MIT"
] | null | null | null | function keys(obj: object, hasKey: (obj: object, key: string) => boolean) {
var keys = [];
for (var key in obj) {
if (hasKey(obj, key)) {
keys.push(key);
}
}
return keys.concat(
(Object.getOwnPropertySymbols(obj) as Array<any>).filter(
symbol =>
(Object.getOwnPropertyDescriptor(obj, symbol) as PropertyDescriptor)
.enumerable,
),
);
}
function hasKey(obj: any, key: string) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
function hasDefinedKey(obj: any, key: string) {
return hasKey(obj, key) && obj[key] !== undefined;
}
function isDomNode(obj: any): boolean {
return (
obj !== null &&
typeof obj === 'object' &&
typeof obj.nodeType === 'number' &&
typeof obj.nodeName === 'string' &&
typeof obj.isEqualNode === 'function'
);
}
function isA(typeName: string, value: unknown) {
return Object.prototype.toString.apply(value) === '[object ' + typeName + ']';
}
function isAsymmetric(obj: any) {
return !!obj && isA('Function', obj.asymmetricMatch);
}
function asymmetricMatch(a: any, b: any) {
var asymmetricA = isAsymmetric(a),
asymmetricB = isAsymmetric(b);
if (asymmetricA && asymmetricB) {
return undefined;
}
if (asymmetricA) {
return a.asymmetricMatch(b);
}
if (asymmetricB) {
return b.asymmetricMatch(a);
}
}
type Tester = (a: any, b: any) => boolean | undefined;
/**
* 深比對物件
* @param a
* @param b
* @param aStack
* @param bStack
* @param customTesters
* @param hasKey
*/
const eq = (
a: any,
b: any,
aStack: Array<unknown>,
bStack: Array<unknown>,
customTesters: Array<Tester>,
hasKey: any,
): boolean => {
customTesters = customTesters || [];
var result = true;
var asymmetricResult = asymmetricMatch(a, b);
if (asymmetricResult !== undefined) {
return asymmetricResult;
}
for (var i = 0; i < customTesters.length; i++) {
var customTesterResult = customTesters[i](a, b);
if (customTesterResult !== undefined) {
return customTesterResult;
}
}
if (a instanceof Error && b instanceof Error) {
return a.message == b.message;
}
if (Object.is(a, b)) {
return true;
}
// A strict comparison is necessary because `null == undefined`.
if (a === null || b === null) {
return a === b;
}
var className = Object.prototype.toString.call(a);
if (className != Object.prototype.toString.call(b)) {
return false;
}
switch (className) {
case '[object Boolean]':
case '[object String]':
case '[object Number]':
if (typeof a !== typeof b) {
// One is a primitive, one a `new Primitive()`
return false;
} else if (typeof a !== 'object' && typeof b !== 'object') {
// both are proper primitives
return Object.is(a, b);
} else {
// both are `new Primitive()`s
return Object.is(a.valueOf(), b.valueOf());
}
case '[object Date]':
// Coerce dates to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a == +b;
// RegExps are compared by their source patterns and flags.
case '[object RegExp]':
return a.source === b.source && a.flags === b.flags;
}
if (typeof a !== 'object' || typeof b !== 'object') {
return false;
}
// Use DOM3 method isEqualNode (IE>=9)
if (isDomNode(a) && isDomNode(b)) {
return a.isEqualNode(b);
}
// Used to detect circular references.
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
// circular references at same depth are equal
// circular reference is not equal to non-circular one
if (aStack[length] === a) {
return bStack[length] === b;
} else if (bStack[length] === b) {
return false;
}
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
// Recursively compare objects and arrays.
// Compare array lengths to determine if a deep comparison is necessary.
if (className == '[object Array]' && a.length !== b.length) {
return false;
}
// Deep compare objects.
var aKeys = keys(a, hasKey),
key;
var size = aKeys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
if (keys(b, hasKey).length !== size) {
return false;
}
while (size--) {
key = aKeys[size];
// Deep compare each member
result =
hasKey(b, key) &&
eq(a[key], b[key], aStack, bStack, customTesters, hasKey);
if (!result) {
return false;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return result;
};
/**
* 深度比較 (toStrictEqual)
* @param a
* @param b
* @param isStrictCheck 嚴格(default: false, 開啟則會檢查不可為將物件中的 undefined 視為不同)
* @param options
*/
function deepCompare(
a: unknown,
b: unknown,
isStrictCheck?: boolean,
options?: {
customTesters?: Array<Tester>,
},
): boolean {
const customTesters = options?.customTesters || [];
return eq(a, b, [], [], customTesters, isStrictCheck ? hasKey : hasDefinedKey);
}
export default deepCompare;
| 26.590909 | 101 | 0.568889 | 149 | 10 | 0 | 23 | 14 | 0 | 7 | 12 | 17 | 1 | 14 | 11.7 | 1,535 | 0.021498 | 0.009121 | 0 | 0.000651 | 0.009121 | 0.255319 | 0.361702 | 0.247102 | /* Example usages of 'keys' are shown below:
var keys = [];
keys.push(key);
keys.concat((Object.getOwnPropertySymbols(obj) as Array<any>).filter(symbol => (Object.getOwnPropertyDescriptor(obj, symbol) as PropertyDescriptor)
.enumerable));
keys(a, hasKey);
keys(b, hasKey).length !== size;
*/
function keys(obj, hasKey) {
var keys = [];
for (var key in obj) {
if (hasKey(obj, key)) {
keys.push(key);
}
}
return keys.concat(
(Object.getOwnPropertySymbols(obj) as Array<any>).filter(
symbol =>
(Object.getOwnPropertyDescriptor(obj, symbol) as PropertyDescriptor)
.enumerable,
),
);
}
/* Example usages of 'hasKey' are shown below:
;
hasKey(obj, key);
hasKey(obj, key) && obj[key] !== undefined;
keys(a, hasKey);
keys(b, hasKey).length !== size;
// Deep compare each member
result =
hasKey(b, key) &&
eq(a[key], b[key], aStack, bStack, customTesters, hasKey);
eq(a, b, [], [], customTesters, isStrictCheck ? hasKey : hasDefinedKey);
*/
function hasKey(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
/* Example usages of 'hasDefinedKey' are shown below:
eq(a, b, [], [], customTesters, isStrictCheck ? hasKey : hasDefinedKey);
*/
function hasDefinedKey(obj, key) {
return hasKey(obj, key) && obj[key] !== undefined;
}
/* Example usages of 'isDomNode' are shown below:
isDomNode(a) && isDomNode(b);
*/
function isDomNode(obj) {
return (
obj !== null &&
typeof obj === 'object' &&
typeof obj.nodeType === 'number' &&
typeof obj.nodeName === 'string' &&
typeof obj.isEqualNode === 'function'
);
}
/* Example usages of 'isA' are shown below:
!!obj && isA('Function', obj.asymmetricMatch);
*/
function isA(typeName, value) {
return Object.prototype.toString.apply(value) === '[object ' + typeName + ']';
}
/* Example usages of 'isAsymmetric' are shown below:
isAsymmetric(a);
isAsymmetric(b);
*/
function isAsymmetric(obj) {
return !!obj && isA('Function', obj.asymmetricMatch);
}
/* Example usages of 'asymmetricMatch' are shown below:
!!obj && isA('Function', obj.asymmetricMatch);
a.asymmetricMatch(b);
b.asymmetricMatch(a);
asymmetricMatch(a, b);
*/
function asymmetricMatch(a, b) {
var asymmetricA = isAsymmetric(a),
asymmetricB = isAsymmetric(b);
if (asymmetricA && asymmetricB) {
return undefined;
}
if (asymmetricA) {
return a.asymmetricMatch(b);
}
if (asymmetricB) {
return b.asymmetricMatch(a);
}
}
type Tester = (a, b) => boolean | undefined;
/**
* 深比對物件
* @param a
* @param b
* @param aStack
* @param bStack
* @param customTesters
* @param hasKey
*/
/* Example usages of 'eq' are shown below:
// Deep compare each member
result =
hasKey(b, key) &&
eq(a[key], b[key], aStack, bStack, customTesters, hasKey);
eq(a, b, [], [], customTesters, isStrictCheck ? hasKey : hasDefinedKey);
*/
const eq = (
a,
b,
aStack,
bStack,
customTesters,
hasKey,
) => {
customTesters = customTesters || [];
var result = true;
var asymmetricResult = asymmetricMatch(a, b);
if (asymmetricResult !== undefined) {
return asymmetricResult;
}
for (var i = 0; i < customTesters.length; i++) {
var customTesterResult = customTesters[i](a, b);
if (customTesterResult !== undefined) {
return customTesterResult;
}
}
if (a instanceof Error && b instanceof Error) {
return a.message == b.message;
}
if (Object.is(a, b)) {
return true;
}
// A strict comparison is necessary because `null == undefined`.
if (a === null || b === null) {
return a === b;
}
var className = Object.prototype.toString.call(a);
if (className != Object.prototype.toString.call(b)) {
return false;
}
switch (className) {
case '[object Boolean]':
case '[object String]':
case '[object Number]':
if (typeof a !== typeof b) {
// One is a primitive, one a `new Primitive()`
return false;
} else if (typeof a !== 'object' && typeof b !== 'object') {
// both are proper primitives
return Object.is(a, b);
} else {
// both are `new Primitive()`s
return Object.is(a.valueOf(), b.valueOf());
}
case '[object Date]':
// Coerce dates to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a == +b;
// RegExps are compared by their source patterns and flags.
case '[object RegExp]':
return a.source === b.source && a.flags === b.flags;
}
if (typeof a !== 'object' || typeof b !== 'object') {
return false;
}
// Use DOM3 method isEqualNode (IE>=9)
if (isDomNode(a) && isDomNode(b)) {
return a.isEqualNode(b);
}
// Used to detect circular references.
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
// circular references at same depth are equal
// circular reference is not equal to non-circular one
if (aStack[length] === a) {
return bStack[length] === b;
} else if (bStack[length] === b) {
return false;
}
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
// Recursively compare objects and arrays.
// Compare array lengths to determine if a deep comparison is necessary.
if (className == '[object Array]' && a.length !== b.length) {
return false;
}
// Deep compare objects.
var aKeys = keys(a, hasKey),
key;
var size = aKeys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
if (keys(b, hasKey).length !== size) {
return false;
}
while (size--) {
key = aKeys[size];
// Deep compare each member
result =
hasKey(b, key) &&
eq(a[key], b[key], aStack, bStack, customTesters, hasKey);
if (!result) {
return false;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return result;
};
/**
* 深度比較 (toStrictEqual)
* @param a
* @param b
* @param isStrictCheck 嚴格(default: false, 開啟則會檢查不可為將物件中的 undefined 視為不同)
* @param options
*/
/* Example usages of 'deepCompare' are shown below:
;
*/
function deepCompare(
a,
b,
isStrictCheck?,
options?,
) {
const customTesters = options?.customTesters || [];
return eq(a, b, [], [], customTesters, isStrictCheck ? hasKey : hasDefinedKey);
}
export default deepCompare;
|
ac730fc696dbdeb02598746fef516744d766ee52 | 2,874 | ts | TypeScript | lib/scale.ts | BlockhostOfficial/Blocktrack | 6e5558e7a9b20df78b9470848ce5ddc2ede772cd | [
"MIT"
] | null | null | null | lib/scale.ts | BlockhostOfficial/Blocktrack | 6e5558e7a9b20df78b9470848ce5ddc2ede772cd | [
"MIT"
] | 1 | 2022-03-12T08:52:43.000Z | 2022-03-12T08:52:43.000Z | lib/scale.ts | BlockhostOfficial/Blocktrack | 6e5558e7a9b20df78b9470848ce5ddc2ede772cd | [
"MIT"
] | null | null | null | interface MinMax {
min: number
max: number
}
export class RelativeScale {
static scale (data: any[], tickCount: number, maxFactor: number | undefined) {
const {
min,
max
}: MinMax = RelativeScale.calculateBounds(data)
let factor = 1
while (true) {
const scale = Math.pow(10, factor)
const scaledMin = min - (min % scale)
let scaledMax = max + (max % scale === 0 ? 0 : scale - (max % scale))
// Prevent min/max from being equal (and generating 0 ticks)
// This happens when all data points are products of scale value
if (scaledMin === scaledMax) {
scaledMax += scale
}
const ticks = (scaledMax - scaledMin) / scale
if (ticks <= tickCount || (typeof maxFactor === 'number' && factor === maxFactor)) {
return {
scaledMin,
scaledMax,
scale
}
} else {
// Too many steps between min/max, increase factor and try again
factor++
}
}
}
static scaleMatrix (data: any[], tickCount: number, maxFactor: number | undefined) {
const nonNullData = data.flat().filter((val) => val !== null)
// when used with the spread operator large nonNullData/data arrays can reach the max call stack size
// use reduce calls to safely determine min/max values for any size of array
// https://stackoverflow.com/questions/63705432/maximum-call-stack-size-exceeded-when-using-the-dots-operator/63706516#63706516
const max = nonNullData.reduce((a, b) => {
return Math.max(a, b)
}, Number.NEGATIVE_INFINITY)
return RelativeScale.scale(
[0, RelativeScale.isFiniteOrZero(max)],
tickCount,
maxFactor
)
}
static generateTicks (min: number, max: number, step: number) {
const ticks = []
for (let i = min; i <= max; i += step) {
ticks.push(i)
}
return ticks
}
static calculateBounds (data: any[]): MinMax {
if (data.length === 0) {
return {
min: 0,
max: 0
}
} else {
const nonNullData = data.filter((val) => val !== null)
// when used with the spread operator large nonNullData/data arrays can reach the max call stack size
// use reduce calls to safely determine min/max values for any size of array
// https://stackoverflow.com/questions/63705432/maximum-call-stack-size-exceeded-when-using-the-dots-operator/63706516#63706516
const min = nonNullData.reduce((a, b) => {
return Math.min(a, b)
}, Number.POSITIVE_INFINITY)
const max = nonNullData.reduce((a, b) => {
return Math.max(a, b)
}, Number.NEGATIVE_INFINITY)
return {
min: RelativeScale.isFiniteOrZero(min),
max: RelativeScale.isFiniteOrZero(max)
}
}
}
static isFiniteOrZero (val: number) {
return Number.isFinite(val) ? val : 0
}
}
| 29.628866 | 133 | 0.61517 | 72 | 10 | 0 | 19 | 13 | 2 | 3 | 3 | 10 | 2 | 1 | 6.1 | 792 | 0.036616 | 0.016414 | 0.002525 | 0.002525 | 0.001263 | 0.068182 | 0.227273 | 0.312636 | interface MinMax {
min
max
}
export class RelativeScale {
static scale (data, tickCount, maxFactor) {
const {
min,
max
} = RelativeScale.calculateBounds(data)
let factor = 1
while (true) {
const scale = Math.pow(10, factor)
const scaledMin = min - (min % scale)
let scaledMax = max + (max % scale === 0 ? 0 : scale - (max % scale))
// Prevent min/max from being equal (and generating 0 ticks)
// This happens when all data points are products of scale value
if (scaledMin === scaledMax) {
scaledMax += scale
}
const ticks = (scaledMax - scaledMin) / scale
if (ticks <= tickCount || (typeof maxFactor === 'number' && factor === maxFactor)) {
return {
scaledMin,
scaledMax,
scale
}
} else {
// Too many steps between min/max, increase factor and try again
factor++
}
}
}
static scaleMatrix (data, tickCount, maxFactor) {
const nonNullData = data.flat().filter((val) => val !== null)
// when used with the spread operator large nonNullData/data arrays can reach the max call stack size
// use reduce calls to safely determine min/max values for any size of array
// https://stackoverflow.com/questions/63705432/maximum-call-stack-size-exceeded-when-using-the-dots-operator/63706516#63706516
const max = nonNullData.reduce((a, b) => {
return Math.max(a, b)
}, Number.NEGATIVE_INFINITY)
return RelativeScale.scale(
[0, RelativeScale.isFiniteOrZero(max)],
tickCount,
maxFactor
)
}
static generateTicks (min, max, step) {
const ticks = []
for (let i = min; i <= max; i += step) {
ticks.push(i)
}
return ticks
}
static calculateBounds (data) {
if (data.length === 0) {
return {
min: 0,
max: 0
}
} else {
const nonNullData = data.filter((val) => val !== null)
// when used with the spread operator large nonNullData/data arrays can reach the max call stack size
// use reduce calls to safely determine min/max values for any size of array
// https://stackoverflow.com/questions/63705432/maximum-call-stack-size-exceeded-when-using-the-dots-operator/63706516#63706516
const min = nonNullData.reduce((a, b) => {
return Math.min(a, b)
}, Number.POSITIVE_INFINITY)
const max = nonNullData.reduce((a, b) => {
return Math.max(a, b)
}, Number.NEGATIVE_INFINITY)
return {
min: RelativeScale.isFiniteOrZero(min),
max: RelativeScale.isFiniteOrZero(max)
}
}
}
static isFiniteOrZero (val) {
return Number.isFinite(val) ? val : 0
}
}
|
2a968018b71746a75b3e52c18dc31914f2533cfa | 12,410 | ts | TypeScript | src/bright-code/code/javascript.ts | Tyh2001/bright-code | d17443a5ada2d3a825f7529cbb54a8d396783364 | [
"MIT"
] | 1 | 2022-03-27T14:36:32.000Z | 2022-03-27T14:36:32.000Z | src/bright-code/code/javascript.ts | Tyh2001/bright-code | d17443a5ada2d3a825f7529cbb54a8d396783364 | [
"MIT"
] | null | null | null | src/bright-code/code/javascript.ts | Tyh2001/bright-code | d17443a5ada2d3a825f7529cbb54a8d396783364 | [
"MIT"
] | null | null | null | const IDENT_RE = '[A-Za-z$_][0-9A-Za-z$_]*'
const KEYWORDS = [
'as',
'in',
'of',
'if',
'for',
'while',
'finally',
'var',
'new',
'function',
'do',
'return',
'void',
'else',
'break',
'catch',
'instanceof',
'with',
'throw',
'case',
'default',
'try',
'switch',
'continue',
'typeof',
'delete',
'let',
'yield',
'const',
'class',
'debugger',
'async',
'await',
'static',
'import',
'from',
'export',
'extends'
] as const
const LITERALS = ['true', 'false', 'null', 'undefined', 'NaN', 'Infinity'] as const
const TYPES = [
'Object',
'Function',
'Boolean',
'Symbol',
'Math',
'Date',
'Number',
'BigInt',
'String',
'RegExp',
'Array',
'Float32Array',
'Float64Array',
'Int8Array',
'Uint8Array',
'Uint8ClampedArray',
'Int16Array',
'Int32Array',
'Uint16Array',
'Uint32Array',
'BigInt64Array',
'BigUint64Array',
'Set',
'Map',
'WeakSet',
'WeakMap',
'ArrayBuffer',
'SharedArrayBuffer',
'Atomics',
'DataView',
'JSON',
'Promise',
'Generator',
'GeneratorFunction',
'AsyncFunction',
'Reflect',
'Proxy',
'Intl',
'WebAssembly'
] as const
const ERROR_TYPES = [
'Error',
'EvalError',
'InternalError',
'RangeError',
'ReferenceError',
'SyntaxError',
'TypeError',
'URIError'
] as const
const BUILT_IN_GLOBALS = [
'setInterval',
'setTimeout',
'clearInterval',
'clearTimeout',
'require',
'exports',
'eval',
'isFinite',
'isNaN',
'parseFloat',
'parseInt',
'decodeURI',
'decodeURIComponent',
'encodeURI',
'encodeURIComponent',
'escape',
'unescape'
] as const
const BUILT_IN_VARIABLES = [
'arguments',
'this',
'super',
'console',
'window',
'document',
'localStorage',
'module',
'global'
] as const
const BUILT_INS = [].concat(BUILT_IN_GLOBALS, TYPES, ERROR_TYPES)
export const javascript = hljs => {
const regex = hljs.regex
const hasClosingTag = (match, { after }) => {
const tag = '</' + match[0].slice(1)
const pos = match.input.indexOf(tag, after)
return pos !== -1
}
const IDENT_RE$1 = IDENT_RE
const FRAGMENT = {
begin: '<>',
end: '</>'
}
const XML_SELF_CLOSING: RegExp = /<[A-Za-z0-9\\._:-]+\s*\/>/
const XML_TAG = {
begin: /<[A-Za-z0-9\\._:-]+/,
end: /\/[A-Za-z0-9\\._:-]+>|\/>/,
isTrulyOpeningTag: (match, response) => {
const afterMatchIndex = match[0].length + match.index
const nextChar = match.input[afterMatchIndex]
if (
nextChar === '<' ||
nextChar === ','
) {
response.ignoreMatch()
return
}
if (nextChar === '>') {
if (!hasClosingTag(match, { after: afterMatchIndex })) {
response.ignoreMatch()
}
}
let m
const afterMatch = match.input.substr(afterMatchIndex)
if ((m = afterMatch.match(/^\s+extends\s+/))) {
if (m.index === 0) {
response.ignoreMatch()
return
}
}
}
}
const KEYWORDS$1 = {
$pattern: IDENT_RE,
keyword: KEYWORDS,
literal: LITERALS,
built_in: BUILT_INS,
'variable.language': BUILT_IN_VARIABLES
}
const decimalDigits = '[0-9](_?[0-9])*'
const frac = `\\.(${decimalDigits})`
const decimalInteger = `0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`
const NUMBER = {
className: 'number',
variants: [
{
begin:
`(\\b(${decimalInteger})((${frac})|\\.)?|(${frac}))` +
`[eE][+-]?(${decimalDigits})\\b`
},
{ begin: `\\b(${decimalInteger})\\b((${frac})\\b|\\.)?|(${frac})\\b` },
{ begin: `\\b(0|[1-9](_?[0-9])*)n\\b` },
{ begin: '\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b' },
{ begin: '\\b0[bB][0-1](_?[0-1])*n?\\b' },
{ begin: '\\b0[oO][0-7](_?[0-7])*n?\\b' },
{ begin: '\\b0[0-7]+n?\\b' }
],
relevance: 0
}
const SUBST = {
className: 'subst',
begin: '\\$\\{',
end: '\\}',
keywords: KEYWORDS$1,
contains: []
}
const HTML_TEMPLATE = {
begin: 'html`',
end: '',
starts: {
end: '`',
returnEnd: false,
contains: [hljs.BACKSLASH_ESCAPE, SUBST],
subLanguage: 'xml'
}
}
const CSS_TEMPLATE = {
begin: 'css`',
end: '',
starts: {
end: '`',
returnEnd: false,
contains: [hljs.BACKSLASH_ESCAPE, SUBST],
subLanguage: 'css'
}
}
const TEMPLATE_STRING = {
className: 'string',
begin: '`',
end: '`',
contains: [hljs.BACKSLASH_ESCAPE, SUBST]
}
const JSDOC_COMMENT = hljs.COMMENT(/\/\*\*(?!\/)/, '\\*/', {
relevance: 0,
contains: [
{
begin: '(?=@[A-Za-z]+)',
relevance: 0,
contains: [
{
className: 'doctag',
begin: '@[A-Za-z]+'
},
{
className: 'type',
begin: '\\{',
end: '\\}',
excludeEnd: true,
excludeBegin: true,
relevance: 0
},
{
className: 'variable',
begin: IDENT_RE$1 + '(?=\\s*(-)|$)',
endsParent: true,
relevance: 0
},
{
begin: /(?=[^\n])\s/,
relevance: 0
}
]
}
]
})
const COMMENT = {
className: 'comment',
variants: [
JSDOC_COMMENT,
hljs.C_BLOCK_COMMENT_MODE,
hljs.C_LINE_COMMENT_MODE
]
}
const SUBST_INTERNALS = [
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
HTML_TEMPLATE,
CSS_TEMPLATE,
TEMPLATE_STRING,
NUMBER
]
SUBST.contains = SUBST_INTERNALS.concat({
begin: /\{/,
end: /\}/,
keywords: KEYWORDS$1,
contains: ['self'].concat(SUBST_INTERNALS)
})
const SUBST_AND_COMMENTS = [].concat(COMMENT, SUBST.contains)
const PARAMS_CONTAINS = SUBST_AND_COMMENTS.concat([
{
begin: /\(/,
end: /\)/,
keywords: KEYWORDS$1,
contains: ['self'].concat(SUBST_AND_COMMENTS)
}
])
const PARAMS = {
className: 'params',
begin: /\(/,
end: /\)/,
excludeBegin: true,
excludeEnd: true,
keywords: KEYWORDS$1,
contains: PARAMS_CONTAINS
}
const CLASS_OR_EXTENDS = {
variants: [
{
match: [
/class/,
/\s+/,
IDENT_RE$1,
/\s+/,
/extends/,
/\s+/,
regex.concat(IDENT_RE$1, '(', regex.concat(/\./, IDENT_RE$1), ')*')
],
scope: {
1: 'keyword',
3: 'title.class',
5: 'keyword',
7: 'title.class.inherited'
}
},
{
match: [/class/, /\s+/, IDENT_RE$1],
scope: {
1: 'keyword',
3: 'title.class'
}
}
]
}
const CLASS_REFERENCE = {
relevance: 0,
match: regex.either(
/\bJSON/,
/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,
/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,
/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/
),
className: 'title.class',
keywords: {
_: [
...TYPES,
...ERROR_TYPES
]
}
}
const USE_STRICT = {
label: 'use_strict',
className: 'meta',
relevance: 10,
begin: /^\s*['"]use (strict|asm)['"]/
}
const FUNCTION_DEFINITION = {
variants: [
{
match: [/function/, /\s+/, IDENT_RE$1, /(?=\s*\()/]
},
{
match: [/function/, /\s*(?=\()/]
}
],
className: {
1: 'keyword',
3: 'title.function'
},
label: 'func.def',
contains: [PARAMS],
illegal: /%/
}
const UPPER_CASE_CONSTANT = {
relevance: 0,
match: /\b[A-Z][A-Z_0-9]+\b/,
className: 'variable.constant'
}
function noneOf(list) {
return regex.concat('(?!', list.join('|'), ')')
}
const FUNCTION_CALL = {
match: regex.concat(
/\b/,
noneOf([...BUILT_IN_GLOBALS, 'super']),
IDENT_RE$1,
regex.lookahead(/\(/)
),
className: 'title.function',
relevance: 0
}
const PROPERTY_ACCESS = {
begin: regex.concat(
/\./,
regex.lookahead(regex.concat(IDENT_RE$1, /(?![0-9A-Za-z$_(])/))
),
end: IDENT_RE$1,
excludeBegin: true,
keywords: 'prototype',
className: 'property',
relevance: 0
}
const GETTER_OR_SETTER = {
match: [/get|set/, /\s+/, IDENT_RE$1, /(?=\()/],
className: {
1: 'keyword',
3: 'title.function'
},
contains: [
{
begin: /\(\)/
},
PARAMS
]
}
const FUNC_LEAD_IN_RE =
'(\\(' +
'[^()]*(\\(' +
'[^()]*(\\(' +
'[^()]*' +
'\\)[^()]*)*' +
'\\)[^()]*)*' +
'\\)|' +
hljs.UNDERSCORE_IDENT_RE +
')\\s*=>'
const FUNCTION_VARIABLE = {
match: [
/const|var|let/,
/\s+/,
IDENT_RE$1,
/\s*/,
/=\s*/,
/(async\s*)?/,
regex.lookahead(FUNC_LEAD_IN_RE)
],
keywords: 'async',
className: {
1: 'keyword',
3: 'title.function'
},
contains: [PARAMS]
}
return {
name: 'Javascript',
aliases: ['js', 'jsx', 'mjs', 'cjs'],
keywords: KEYWORDS$1,
exports: { PARAMS_CONTAINS, CLASS_REFERENCE },
illegal: /#(?![$_A-z])/,
contains: [
hljs.SHEBANG({
label: 'shebang',
binary: 'node',
relevance: 5
}),
USE_STRICT,
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
HTML_TEMPLATE,
CSS_TEMPLATE,
TEMPLATE_STRING,
COMMENT,
NUMBER,
CLASS_REFERENCE,
{
className: 'attr',
begin: IDENT_RE$1 + regex.lookahead(':'),
relevance: 0
},
FUNCTION_VARIABLE,
{
begin: '(' + hljs.RE_STARTERS_RE + '|\\b(case|return|throw)\\b)\\s*',
keywords: 'return throw case',
relevance: 0,
contains: [
COMMENT,
hljs.REGEXP_MODE,
{
className: 'function',
begin: FUNC_LEAD_IN_RE,
returnBegin: true,
end: '\\s*=>',
contains: [
{
className: 'params',
variants: [
{
begin: hljs.UNDERSCORE_IDENT_RE,
relevance: 0
},
{
className: null,
begin: /\(\s*\)/,
skip: true
},
{
begin: /\(/,
end: /\)/,
excludeBegin: true,
excludeEnd: true,
keywords: KEYWORDS$1,
contains: PARAMS_CONTAINS
}
]
}
]
},
{
begin: /,/,
relevance: 0
},
{
match: /\s+/,
relevance: 0
},
{
variants: [
{ begin: FRAGMENT.begin, end: FRAGMENT.end },
{ match: XML_SELF_CLOSING },
{
begin: XML_TAG.begin,
'on:begin': XML_TAG.isTrulyOpeningTag,
end: XML_TAG.end
}
],
subLanguage: 'xml',
contains: [
{
begin: XML_TAG.begin,
end: XML_TAG.end,
skip: true,
contains: ['self']
}
]
}
]
},
FUNCTION_DEFINITION,
{
beginKeywords: 'while if switch catch for'
},
{
begin:
'\\b(?!function)' +
hljs.UNDERSCORE_IDENT_RE +
'\\(' +
'[^()]*(\\(' +
'[^()]*(\\(' +
'[^()]*' +
'\\)[^()]*)*' +
'\\)[^()]*)*' +
'\\)\\s*\\{',
returnBegin: true,
label: 'func.def',
contains: [
PARAMS,
hljs.inherit(hljs.TITLE_MODE, {
begin: IDENT_RE$1,
className: 'title.function'
})
]
},
{
match: /\.\.\./,
relevance: 0
},
PROPERTY_ACCESS,
{
match: '\\$' + IDENT_RE$1,
relevance: 0
},
{
match: [/\bconstructor(?=\s*\()/],
className: { 1: 'title.function' },
contains: [PARAMS]
},
FUNCTION_CALL,
UPPER_CASE_CONSTANT,
CLASS_OR_EXTENDS,
GETTER_OR_SETTER,
{
match: /\$[(.]/
}
]
}
}
| 20.614618 | 83 | 0.452861 | 577 | 4 | 0 | 6 | 46 | 0 | 2 | 0 | 0 | 0 | 6 | 119.25 | 3,781 | 0.002645 | 0.012166 | 0 | 0 | 0.001587 | 0 | 0 | 0.216756 | const IDENT_RE = '[A-Za-z$_][0-9A-Za-z$_]*'
const KEYWORDS = [
'as',
'in',
'of',
'if',
'for',
'while',
'finally',
'var',
'new',
'function',
'do',
'return',
'void',
'else',
'break',
'catch',
'instanceof',
'with',
'throw',
'case',
'default',
'try',
'switch',
'continue',
'typeof',
'delete',
'let',
'yield',
'const',
'class',
'debugger',
'async',
'await',
'static',
'import',
'from',
'export',
'extends'
] as const
const LITERALS = ['true', 'false', 'null', 'undefined', 'NaN', 'Infinity'] as const
const TYPES = [
'Object',
'Function',
'Boolean',
'Symbol',
'Math',
'Date',
'Number',
'BigInt',
'String',
'RegExp',
'Array',
'Float32Array',
'Float64Array',
'Int8Array',
'Uint8Array',
'Uint8ClampedArray',
'Int16Array',
'Int32Array',
'Uint16Array',
'Uint32Array',
'BigInt64Array',
'BigUint64Array',
'Set',
'Map',
'WeakSet',
'WeakMap',
'ArrayBuffer',
'SharedArrayBuffer',
'Atomics',
'DataView',
'JSON',
'Promise',
'Generator',
'GeneratorFunction',
'AsyncFunction',
'Reflect',
'Proxy',
'Intl',
'WebAssembly'
] as const
const ERROR_TYPES = [
'Error',
'EvalError',
'InternalError',
'RangeError',
'ReferenceError',
'SyntaxError',
'TypeError',
'URIError'
] as const
const BUILT_IN_GLOBALS = [
'setInterval',
'setTimeout',
'clearInterval',
'clearTimeout',
'require',
'exports',
'eval',
'isFinite',
'isNaN',
'parseFloat',
'parseInt',
'decodeURI',
'decodeURIComponent',
'encodeURI',
'encodeURIComponent',
'escape',
'unescape'
] as const
const BUILT_IN_VARIABLES = [
'arguments',
'this',
'super',
'console',
'window',
'document',
'localStorage',
'module',
'global'
] as const
const BUILT_INS = [].concat(BUILT_IN_GLOBALS, TYPES, ERROR_TYPES)
export const javascript = hljs => {
const regex = hljs.regex
/* Example usages of 'hasClosingTag' are shown below:
!hasClosingTag(match, { after: afterMatchIndex });
*/
const hasClosingTag = (match, { after }) => {
const tag = '</' + match[0].slice(1)
const pos = match.input.indexOf(tag, after)
return pos !== -1
}
const IDENT_RE$1 = IDENT_RE
const FRAGMENT = {
begin: '<>',
end: '</>'
}
const XML_SELF_CLOSING = /<[A-Za-z0-9\\._:-]+\s*\/>/
const XML_TAG = {
begin: /<[A-Za-z0-9\\._:-]+/,
end: /\/[A-Za-z0-9\\._:-]+>|\/>/,
isTrulyOpeningTag: (match, response) => {
const afterMatchIndex = match[0].length + match.index
const nextChar = match.input[afterMatchIndex]
if (
nextChar === '<' ||
nextChar === ','
) {
response.ignoreMatch()
return
}
if (nextChar === '>') {
if (!hasClosingTag(match, { after: afterMatchIndex })) {
response.ignoreMatch()
}
}
let m
const afterMatch = match.input.substr(afterMatchIndex)
if ((m = afterMatch.match(/^\s+extends\s+/))) {
if (m.index === 0) {
response.ignoreMatch()
return
}
}
}
}
const KEYWORDS$1 = {
$pattern: IDENT_RE,
keyword: KEYWORDS,
literal: LITERALS,
built_in: BUILT_INS,
'variable.language': BUILT_IN_VARIABLES
}
const decimalDigits = '[0-9](_?[0-9])*'
const frac = `\\.(${decimalDigits})`
const decimalInteger = `0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`
const NUMBER = {
className: 'number',
variants: [
{
begin:
`(\\b(${decimalInteger})((${frac})|\\.)?|(${frac}))` +
`[eE][+-]?(${decimalDigits})\\b`
},
{ begin: `\\b(${decimalInteger})\\b((${frac})\\b|\\.)?|(${frac})\\b` },
{ begin: `\\b(0|[1-9](_?[0-9])*)n\\b` },
{ begin: '\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b' },
{ begin: '\\b0[bB][0-1](_?[0-1])*n?\\b' },
{ begin: '\\b0[oO][0-7](_?[0-7])*n?\\b' },
{ begin: '\\b0[0-7]+n?\\b' }
],
relevance: 0
}
const SUBST = {
className: 'subst',
begin: '\\$\\{',
end: '\\}',
keywords: KEYWORDS$1,
contains: []
}
const HTML_TEMPLATE = {
begin: 'html`',
end: '',
starts: {
end: '`',
returnEnd: false,
contains: [hljs.BACKSLASH_ESCAPE, SUBST],
subLanguage: 'xml'
}
}
const CSS_TEMPLATE = {
begin: 'css`',
end: '',
starts: {
end: '`',
returnEnd: false,
contains: [hljs.BACKSLASH_ESCAPE, SUBST],
subLanguage: 'css'
}
}
const TEMPLATE_STRING = {
className: 'string',
begin: '`',
end: '`',
contains: [hljs.BACKSLASH_ESCAPE, SUBST]
}
const JSDOC_COMMENT = hljs.COMMENT(/\/\*\*(?!\/)/, '\\*/', {
relevance: 0,
contains: [
{
begin: '(?=@[A-Za-z]+)',
relevance: 0,
contains: [
{
className: 'doctag',
begin: '@[A-Za-z]+'
},
{
className: 'type',
begin: '\\{',
end: '\\}',
excludeEnd: true,
excludeBegin: true,
relevance: 0
},
{
className: 'variable',
begin: IDENT_RE$1 + '(?=\\s*(-)|$)',
endsParent: true,
relevance: 0
},
{
begin: /(?=[^\n])\s/,
relevance: 0
}
]
}
]
})
const COMMENT = {
className: 'comment',
variants: [
JSDOC_COMMENT,
hljs.C_BLOCK_COMMENT_MODE,
hljs.C_LINE_COMMENT_MODE
]
}
const SUBST_INTERNALS = [
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
HTML_TEMPLATE,
CSS_TEMPLATE,
TEMPLATE_STRING,
NUMBER
]
SUBST.contains = SUBST_INTERNALS.concat({
begin: /\{/,
end: /\}/,
keywords: KEYWORDS$1,
contains: ['self'].concat(SUBST_INTERNALS)
})
const SUBST_AND_COMMENTS = [].concat(COMMENT, SUBST.contains)
const PARAMS_CONTAINS = SUBST_AND_COMMENTS.concat([
{
begin: /\(/,
end: /\)/,
keywords: KEYWORDS$1,
contains: ['self'].concat(SUBST_AND_COMMENTS)
}
])
const PARAMS = {
className: 'params',
begin: /\(/,
end: /\)/,
excludeBegin: true,
excludeEnd: true,
keywords: KEYWORDS$1,
contains: PARAMS_CONTAINS
}
const CLASS_OR_EXTENDS = {
variants: [
{
match: [
/class/,
/\s+/,
IDENT_RE$1,
/\s+/,
/extends/,
/\s+/,
regex.concat(IDENT_RE$1, '(', regex.concat(/\./, IDENT_RE$1), ')*')
],
scope: {
1: 'keyword',
3: 'title.class',
5: 'keyword',
7: 'title.class.inherited'
}
},
{
match: [/class/, /\s+/, IDENT_RE$1],
scope: {
1: 'keyword',
3: 'title.class'
}
}
]
}
const CLASS_REFERENCE = {
relevance: 0,
match: regex.either(
/\bJSON/,
/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,
/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,
/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/
),
className: 'title.class',
keywords: {
_: [
...TYPES,
...ERROR_TYPES
]
}
}
const USE_STRICT = {
label: 'use_strict',
className: 'meta',
relevance: 10,
begin: /^\s*['"]use (strict|asm)['"]/
}
const FUNCTION_DEFINITION = {
variants: [
{
match: [/function/, /\s+/, IDENT_RE$1, /(?=\s*\()/]
},
{
match: [/function/, /\s*(?=\()/]
}
],
className: {
1: 'keyword',
3: 'title.function'
},
label: 'func.def',
contains: [PARAMS],
illegal: /%/
}
const UPPER_CASE_CONSTANT = {
relevance: 0,
match: /\b[A-Z][A-Z_0-9]+\b/,
className: 'variable.constant'
}
/* Example usages of 'noneOf' are shown below:
regex.concat(/\b/, noneOf([...BUILT_IN_GLOBALS, 'super']), IDENT_RE$1, regex.lookahead(/\(/));
*/
function noneOf(list) {
return regex.concat('(?!', list.join('|'), ')')
}
const FUNCTION_CALL = {
match: regex.concat(
/\b/,
noneOf([...BUILT_IN_GLOBALS, 'super']),
IDENT_RE$1,
regex.lookahead(/\(/)
),
className: 'title.function',
relevance: 0
}
const PROPERTY_ACCESS = {
begin: regex.concat(
/\./,
regex.lookahead(regex.concat(IDENT_RE$1, /(?![0-9A-Za-z$_(])/))
),
end: IDENT_RE$1,
excludeBegin: true,
keywords: 'prototype',
className: 'property',
relevance: 0
}
const GETTER_OR_SETTER = {
match: [/get|set/, /\s+/, IDENT_RE$1, /(?=\()/],
className: {
1: 'keyword',
3: 'title.function'
},
contains: [
{
begin: /\(\)/
},
PARAMS
]
}
const FUNC_LEAD_IN_RE =
'(\\(' +
'[^()]*(\\(' +
'[^()]*(\\(' +
'[^()]*' +
'\\)[^()]*)*' +
'\\)[^()]*)*' +
'\\)|' +
hljs.UNDERSCORE_IDENT_RE +
')\\s*=>'
const FUNCTION_VARIABLE = {
match: [
/const|var|let/,
/\s+/,
IDENT_RE$1,
/\s*/,
/=\s*/,
/(async\s*)?/,
regex.lookahead(FUNC_LEAD_IN_RE)
],
keywords: 'async',
className: {
1: 'keyword',
3: 'title.function'
},
contains: [PARAMS]
}
return {
name: 'Javascript',
aliases: ['js', 'jsx', 'mjs', 'cjs'],
keywords: KEYWORDS$1,
exports: { PARAMS_CONTAINS, CLASS_REFERENCE },
illegal: /#(?![$_A-z])/,
contains: [
hljs.SHEBANG({
label: 'shebang',
binary: 'node',
relevance: 5
}),
USE_STRICT,
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
HTML_TEMPLATE,
CSS_TEMPLATE,
TEMPLATE_STRING,
COMMENT,
NUMBER,
CLASS_REFERENCE,
{
className: 'attr',
begin: IDENT_RE$1 + regex.lookahead(':'),
relevance: 0
},
FUNCTION_VARIABLE,
{
begin: '(' + hljs.RE_STARTERS_RE + '|\\b(case|return|throw)\\b)\\s*',
keywords: 'return throw case',
relevance: 0,
contains: [
COMMENT,
hljs.REGEXP_MODE,
{
className: 'function',
begin: FUNC_LEAD_IN_RE,
returnBegin: true,
end: '\\s*=>',
contains: [
{
className: 'params',
variants: [
{
begin: hljs.UNDERSCORE_IDENT_RE,
relevance: 0
},
{
className: null,
begin: /\(\s*\)/,
skip: true
},
{
begin: /\(/,
end: /\)/,
excludeBegin: true,
excludeEnd: true,
keywords: KEYWORDS$1,
contains: PARAMS_CONTAINS
}
]
}
]
},
{
begin: /,/,
relevance: 0
},
{
match: /\s+/,
relevance: 0
},
{
variants: [
{ begin: FRAGMENT.begin, end: FRAGMENT.end },
{ match: XML_SELF_CLOSING },
{
begin: XML_TAG.begin,
'on:begin': XML_TAG.isTrulyOpeningTag,
end: XML_TAG.end
}
],
subLanguage: 'xml',
contains: [
{
begin: XML_TAG.begin,
end: XML_TAG.end,
skip: true,
contains: ['self']
}
]
}
]
},
FUNCTION_DEFINITION,
{
beginKeywords: 'while if switch catch for'
},
{
begin:
'\\b(?!function)' +
hljs.UNDERSCORE_IDENT_RE +
'\\(' +
'[^()]*(\\(' +
'[^()]*(\\(' +
'[^()]*' +
'\\)[^()]*)*' +
'\\)[^()]*)*' +
'\\)\\s*\\{',
returnBegin: true,
label: 'func.def',
contains: [
PARAMS,
hljs.inherit(hljs.TITLE_MODE, {
begin: IDENT_RE$1,
className: 'title.function'
})
]
},
{
match: /\.\.\./,
relevance: 0
},
PROPERTY_ACCESS,
{
match: '\\$' + IDENT_RE$1,
relevance: 0
},
{
match: [/\bconstructor(?=\s*\()/],
className: { 1: 'title.function' },
contains: [PARAMS]
},
FUNCTION_CALL,
UPPER_CASE_CONSTANT,
CLASS_OR_EXTENDS,
GETTER_OR_SETTER,
{
match: /\$[(.]/
}
]
}
}
|
e3e1ae0bf3fc152ff7fa092697484689abb8e7d5 | 1,903 | ts | TypeScript | modules/tinymce/src/core/main/ts/file/UploadStatus.ts | Nelyx/tinymce | 411993dd42c8f9bac8b2ba9d7f95686374b7b7e9 | [
"MIT"
] | null | null | null | modules/tinymce/src/core/main/ts/file/UploadStatus.ts | Nelyx/tinymce | 411993dd42c8f9bac8b2ba9d7f95686374b7b7e9 | [
"MIT"
] | null | null | null | modules/tinymce/src/core/main/ts/file/UploadStatus.ts | Nelyx/tinymce | 411993dd42c8f9bac8b2ba9d7f95686374b7b7e9 | [
"MIT"
] | 2 | 2022-03-04T03:00:16.000Z | 2022-03-27T15:53:55.000Z | /**
* Holds the current status of a blob uri, if it's pending or uploaded and what the result urls was.
*
* @private
* @class tinymce.file.UploadStatus
*/
export interface UploadStatus {
readonly hasBlobUri: (blobUri: string) => boolean;
readonly getResultUri: (blobUri: string) => string | null;
readonly isPending: (blobUri: string) => boolean;
readonly isUploaded: (blobUri: string) => boolean;
readonly markPending: (blobUri: string) => void;
readonly markUploaded: (blobUri: string, resultUri: string) => void;
readonly removeFailed: (blobUri: string) => void;
readonly destroy: () => void;
}
export const UploadStatus = (): UploadStatus => {
const PENDING = 1, UPLOADED = 2;
let blobUriStatuses = {};
const createStatus = (status: number, resultUri: string) => {
return {
status,
resultUri
};
};
const hasBlobUri = (blobUri: string) => {
return blobUri in blobUriStatuses;
};
const getResultUri = (blobUri: string) => {
const result = blobUriStatuses[blobUri];
return result ? result.resultUri : null;
};
const isPending = (blobUri: string) => {
return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === PENDING : false;
};
const isUploaded = (blobUri: string) => {
return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === UPLOADED : false;
};
const markPending = (blobUri: string) => {
blobUriStatuses[blobUri] = createStatus(PENDING, null);
};
const markUploaded = (blobUri: string, resultUri: string) => {
blobUriStatuses[blobUri] = createStatus(UPLOADED, resultUri);
};
const removeFailed = (blobUri: string) => {
delete blobUriStatuses[blobUri];
};
const destroy = () => {
blobUriStatuses = {};
};
return {
hasBlobUri,
getResultUri,
isPending,
isUploaded,
markPending,
markUploaded,
removeFailed,
destroy
};
};
| 25.373333 | 100 | 0.660011 | 55 | 10 | 0 | 10 | 14 | 8 | 2 | 0 | 26 | 1 | 0 | 5.6 | 515 | 0.038835 | 0.027184 | 0.015534 | 0.001942 | 0 | 0 | 0.619048 | 0.352601 | /**
* Holds the current status of a blob uri, if it's pending or uploaded and what the result urls was.
*
* @private
* @class tinymce.file.UploadStatus
*/
export interface UploadStatus {
readonly hasBlobUri;
readonly getResultUri;
readonly isPending;
readonly isUploaded;
readonly markPending;
readonly markUploaded;
readonly removeFailed;
readonly destroy;
}
export /* Example usages of 'UploadStatus' are shown below:
*
* Holds the current status of a blob uri, if it's pending or uploaded and what the result urls was.
*
* @private
* @class tinymce.file.UploadStatus
;
*/
const UploadStatus = () => {
const PENDING = 1, UPLOADED = 2;
let blobUriStatuses = {};
/* Example usages of 'createStatus' are shown below:
blobUriStatuses[blobUri] = createStatus(PENDING, null);
blobUriStatuses[blobUri] = createStatus(UPLOADED, resultUri);
*/
const createStatus = (status, resultUri) => {
return {
status,
resultUri
};
};
/* Example usages of 'hasBlobUri' are shown below:
;
hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === PENDING : false;
hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === UPLOADED : false;
*/
const hasBlobUri = (blobUri) => {
return blobUri in blobUriStatuses;
};
/* Example usages of 'getResultUri' are shown below:
;
*/
const getResultUri = (blobUri) => {
const result = blobUriStatuses[blobUri];
return result ? result.resultUri : null;
};
/* Example usages of 'isPending' are shown below:
;
*/
const isPending = (blobUri) => {
return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === PENDING : false;
};
/* Example usages of 'isUploaded' are shown below:
;
*/
const isUploaded = (blobUri) => {
return hasBlobUri(blobUri) ? blobUriStatuses[blobUri].status === UPLOADED : false;
};
/* Example usages of 'markPending' are shown below:
;
*/
const markPending = (blobUri) => {
blobUriStatuses[blobUri] = createStatus(PENDING, null);
};
/* Example usages of 'markUploaded' are shown below:
;
*/
const markUploaded = (blobUri, resultUri) => {
blobUriStatuses[blobUri] = createStatus(UPLOADED, resultUri);
};
/* Example usages of 'removeFailed' are shown below:
;
*/
const removeFailed = (blobUri) => {
delete blobUriStatuses[blobUri];
};
/* Example usages of 'destroy' are shown below:
;
*/
const destroy = () => {
blobUriStatuses = {};
};
return {
hasBlobUri,
getResultUri,
isPending,
isUploaded,
markPending,
markUploaded,
removeFailed,
destroy
};
};
|
b177dae6efb2e1045a01850eca6a570e7c90f763 | 1,750 | ts | TypeScript | frontend/src/utils.ts | stv0g/Gose | 2df5d067fb7f253c25d362fece60a006383a34ea | [
"Apache-2.0"
] | 1 | 2022-03-08T12:07:22.000Z | 2022-03-08T12:07:22.000Z | frontend/src/utils.ts | stv0g/Gose | 2df5d067fb7f253c25d362fece60a006383a34ea | [
"Apache-2.0"
] | null | null | null | frontend/src/utils.ts | stv0g/Gose | 2df5d067fb7f253c25d362fece60a006383a34ea | [
"Apache-2.0"
] | null | null | null | export function buf2hex(buf: ArrayBuffer): string {
return Array.prototype.map.call(new Uint8Array(buf), (x: number) => ("00" + x.toString(16)).slice(-2)).join("");
}
export function hex2buf(hex: string): ArrayBuffer {
let a = new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
return a.buffer;
}
export function arraybufferEqual(a: ArrayBuffer, b: ArrayBuffer) {
if (a === b) {
return true;
}
if (a.byteLength !== b.byteLength) {
return false;
}
var view1 = new DataView(a);
var view2 = new DataView(b);
var i = a.byteLength;
while (i--) {
if (view1.getUint8(i) !== view2.getUint8(i)) {
return false;
}
}
return true;
}
export function shortUrl(url: string, l?: number){
var l = typeof(l) != "undefined" ? l : 32;
var chunk_l = (l/2);
var url = url.replace("http://","").replace("https://","");
if (url.length <= l) {
return url;
}
var start_chunk = shortString(url, chunk_l, false);
var end_chunk = shortString(url, chunk_l, true);
return start_chunk + ".." + end_chunk;
}
function shortString(s: string, l: number, reverse?: boolean){
var stop_chars = [' ','/', '&'];
var acceptable_shortness = l * 0.80; // When to start looking for stop characters
var reverse = typeof(reverse) != "undefined" ? reverse : false;
var s = reverse ? s.split("").reverse().join("") : s;
var short_s = "";
for (var i=0; i < l-1; i++) {
short_s += s[i];
if (i >= acceptable_shortness && stop_chars.indexOf(s[i]) >= 0) {
break;
}
}
if (reverse) {
return short_s.split("").reverse().join("");
}
return short_s;
}
| 26.119403 | 116 | 0.563429 | 52 | 7 | 0 | 11 | 15 | 0 | 1 | 0 | 8 | 0 | 2 | 6.285714 | 535 | 0.033645 | 0.028037 | 0 | 0 | 0.003738 | 0 | 0.242424 | 0.339771 | export function buf2hex(buf) {
return Array.prototype.map.call(new Uint8Array(buf), (x) => ("00" + x.toString(16)).slice(-2)).join("");
}
export function hex2buf(hex) {
let a = new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
return a.buffer;
}
export function arraybufferEqual(a, b) {
if (a === b) {
return true;
}
if (a.byteLength !== b.byteLength) {
return false;
}
var view1 = new DataView(a);
var view2 = new DataView(b);
var i = a.byteLength;
while (i--) {
if (view1.getUint8(i) !== view2.getUint8(i)) {
return false;
}
}
return true;
}
export function shortUrl(url, l?){
var l = typeof(l) != "undefined" ? l : 32;
var chunk_l = (l/2);
var url = url.replace("http://","").replace("https://","");
if (url.length <= l) {
return url;
}
var start_chunk = shortString(url, chunk_l, false);
var end_chunk = shortString(url, chunk_l, true);
return start_chunk + ".." + end_chunk;
}
/* Example usages of 'shortString' are shown below:
shortString(url, chunk_l, false);
shortString(url, chunk_l, true);
*/
function shortString(s, l, reverse?){
var stop_chars = [' ','/', '&'];
var acceptable_shortness = l * 0.80; // When to start looking for stop characters
var reverse = typeof(reverse) != "undefined" ? reverse : false;
var s = reverse ? s.split("").reverse().join("") : s;
var short_s = "";
for (var i=0; i < l-1; i++) {
short_s += s[i];
if (i >= acceptable_shortness && stop_chars.indexOf(s[i]) >= 0) {
break;
}
}
if (reverse) {
return short_s.split("").reverse().join("");
}
return short_s;
}
|
f836221fa0d1dd85c981c37fc82c82995a7de287 | 7,732 | ts | TypeScript | src/module/tablesmith/expressions/mersennetwister.ts | cadowtin/tablesmith-like | 62c8068a27e01c3b528e682f177ccdb270a99002 | [
"MIT"
] | 4 | 2022-01-25T10:19:07.000Z | 2022-02-28T21:12:27.000Z | src/module/tablesmith/expressions/mersennetwister.ts | cadowtin/tablesmith-like | 62c8068a27e01c3b528e682f177ccdb270a99002 | [
"MIT"
] | 4 | 2022-02-01T01:42:56.000Z | 2022-03-11T21:47:29.000Z | src/module/tablesmith/expressions/mersennetwister.ts | cadowtin/tablesmith-like | 62c8068a27e01c3b528e682f177ccdb270a99002 | [
"MIT"
] | 1 | 2022-02-01T01:39:38.000Z | 2022-02-01T01:39:38.000Z | // eslint:disable
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
/**
* A standalone, pure JavaScript implementation of the Mersenne Twister pseudo random number generator.
*
* @author Raphael Pigulla <pigulla@four66.com>
* @version 0.2.3
* @license
* Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of its contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
class MersenneTwister {
/**
* Instantiates a new Mersenne Twister.
* @param {number} [seed] The initial seed value, if not provided the current timestamp will be used.
* @constructor
*/
constructor(seed: number) {
// Initial values
this.MAX_INT = 4294967296.0;
this.N = 624;
this.M = 397;
this.UPPER_MASK = 0x80000000;
this.LOWER_MASK = 0x7fffffff;
this.MATRIX_A = 0x9908b0df;
// Initialize sequences
this.mt = new Array(this.N);
this.mti = this.N + 1;
this.SEED = this.seed(seed ?? new Date().getTime());
}
/**
* Initializes the state vector by using one unsigned 32-bit integer "seed", which may be zero.
*
* @since 0.1.0
* @param {number} seed The seed value.
*/
seed(seed: number) {
this.SEED = seed;
let s;
this.mt[0] = seed >>> 0;
for (this.mti = 1; this.mti < this.N; this.mti++) {
s = this.mt[this.mti - 1] ^ (this.mt[this.mti - 1] >>> 30);
this.mt[this.mti] = ((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253 + this.mti;
this.mt[this.mti] >>>= 0;
}
return seed;
}
/**
* Initializes the state vector by using an array key[] of unsigned 32-bit integers of the specified length. If
* length is smaller than 624, then each array of 32-bit integers gives distinct initial state vector. This is
* useful if you want a larger seed space than 32-bit word.
*
* @since 0.1.0
* @param {array} vector The seed vector.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
seedArray(vector: Array<any>) {
let i = 1,
j = 0,
k = this.N > vector.length ? this.N : vector.length,
s;
this.seed(19650218);
for (; k > 0; k--) {
s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30);
this.mt[i] =
(this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + (s & 0x0000ffff) * 1664525)) + vector[j] + j;
this.mt[i] >>>= 0;
i++;
j++;
if (i >= this.N) {
this.mt[0] = this.mt[this.N - 1];
i = 1;
}
if (j >= vector.length) {
j = 0;
}
}
for (k = this.N - 1; k; k--) {
s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30);
this.mt[i] =
(this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941)) - i;
this.mt[i] >>>= 0;
i++;
if (i >= this.N) {
this.mt[0] = this.mt[this.N - 1];
i = 1;
}
}
this.mt[0] = 0x80000000;
}
/**
* Generates a random unsigned 32-bit integer.
*
* @since 0.1.0
* @returns {number}
*/
int(): number {
let y,
kk,
// eslint-disable-next-line prefer-const
mag01 = [0, this.MATRIX_A];
if (this.mti >= this.N) {
if (this.mti === this.N + 1) {
this.seed(5489);
}
for (kk = 0; kk < this.N - this.M; kk++) {
y = (this.mt[kk] & this.UPPER_MASK) | (this.mt[kk + 1] & this.LOWER_MASK);
this.mt[kk] = this.mt[kk + this.M] ^ (y >>> 1) ^ mag01[y & 1];
}
for (; kk < this.N - 1; kk++) {
y = (this.mt[kk] & this.UPPER_MASK) | (this.mt[kk + 1] & this.LOWER_MASK);
this.mt[kk] = this.mt[kk + (this.M - this.N)] ^ (y >>> 1) ^ mag01[y & 1];
}
y = (this.mt[this.N - 1] & this.UPPER_MASK) | (this.mt[0] & this.LOWER_MASK);
this.mt[this.N - 1] = this.mt[this.M - 1] ^ (y >>> 1) ^ mag01[y & 1];
this.mti = 0;
}
y = this.mt[this.mti++];
y ^= y >>> 11;
y ^= (y << 7) & 0x9d2c5680;
y ^= (y << 15) & 0xefc60000;
y ^= y >>> 18;
return y >>> 0;
}
/**
* Generates a random unsigned 31-bit integer.
*
* @since 0.1.0
* @returns {number}
*/
int31(): number {
return this.int() >>> 1;
}
/**
* Generates a random real in the interval [0;1] with 32-bit resolution.
*
* @since 0.1.0
* @returns {number}
*/
real(): number {
return this.int() * (1.0 / (this.MAX_INT - 1));
}
/**
* Generates a random real in the interval ]0;1[ with 32-bit resolution.
*
* @since 0.1.0
* @returns {number}
*/
realx(): number {
return (this.int() + 0.5) * (1.0 / this.MAX_INT);
}
/**
* Generates a random real in the interval [0;1[ with 32-bit resolution.
*
* @since 0.1.0
* @returns {number}
*/
rnd(): number {
return this.int() * (1.0 / this.MAX_INT);
}
/**
* Generates a random real in the interval [0;1[ with 32-bit resolution.
*
* Same as .rnd() method - for consistency with Math.random() interface.
*
* @since 0.2.0
* @returns {number}
*/
random(): number {
return this.rnd();
}
/**
* Generates a random real in the interval [0;1[ with 53-bit resolution.
*
* @since 0.1.0
* @returns {number}
*/
rndHiRes(): number {
const a = this.int() >>> 5;
const b = this.int() >>> 6;
return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0);
}
/**
* A pseudo-normal distribution using the Box-Muller transform.
* @param {number} mu The normal distribution mean
* @param {number} sigma The normal distribution standard deviation
* @returns {number}
*/
normal(mu: number, sigma: number): number {
let u = 0;
while (u === 0) u = this.random(); //Converting [0,1) to (0,1)
let v = 0;
while (v === 0) v = this.random(); //Converting [0,1) to (0,1)
const n = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
return n * sigma + mu;
}
/**
* A factory method for generating random uniform rolls
* @return {number}
*/
static random(): number {
return twist.random();
}
/**
* A factory method for generating random normal rolls
* @return {number}
*/
static normal(...args): number {
return twist.normal(...args);
}
}
const twist = new MersenneTwister(Date.now());
export default twist;
| 28.958801 | 118 | 0.5873 | 121 | 13 | 0 | 6 | 14 | 0 | 5 | 1 | 14 | 1 | 0 | 7 | 2,690 | 0.007063 | 0.005204 | 0 | 0.000372 | 0 | 0.030303 | 0.424242 | 0.2044 | // eslint:disable
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
/**
* A standalone, pure JavaScript implementation of the Mersenne Twister pseudo random number generator.
*
* @author Raphael Pigulla <pigulla@four66.com>
* @version 0.2.3
* @license
* Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The names of its contributors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
class MersenneTwister {
/**
* Instantiates a new Mersenne Twister.
* @param {number} [seed] The initial seed value, if not provided the current timestamp will be used.
* @constructor
*/
constructor(seed) {
// Initial values
this.MAX_INT = 4294967296.0;
this.N = 624;
this.M = 397;
this.UPPER_MASK = 0x80000000;
this.LOWER_MASK = 0x7fffffff;
this.MATRIX_A = 0x9908b0df;
// Initialize sequences
this.mt = new Array(this.N);
this.mti = this.N + 1;
this.SEED = this.seed(seed ?? new Date().getTime());
}
/**
* Initializes the state vector by using one unsigned 32-bit integer "seed", which may be zero.
*
* @since 0.1.0
* @param {number} seed The seed value.
*/
seed(seed) {
this.SEED = seed;
let s;
this.mt[0] = seed >>> 0;
for (this.mti = 1; this.mti < this.N; this.mti++) {
s = this.mt[this.mti - 1] ^ (this.mt[this.mti - 1] >>> 30);
this.mt[this.mti] = ((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253 + this.mti;
this.mt[this.mti] >>>= 0;
}
return seed;
}
/**
* Initializes the state vector by using an array key[] of unsigned 32-bit integers of the specified length. If
* length is smaller than 624, then each array of 32-bit integers gives distinct initial state vector. This is
* useful if you want a larger seed space than 32-bit word.
*
* @since 0.1.0
* @param {array} vector The seed vector.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
seedArray(vector) {
let i = 1,
j = 0,
k = this.N > vector.length ? this.N : vector.length,
s;
this.seed(19650218);
for (; k > 0; k--) {
s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30);
this.mt[i] =
(this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1664525) << 16) + (s & 0x0000ffff) * 1664525)) + vector[j] + j;
this.mt[i] >>>= 0;
i++;
j++;
if (i >= this.N) {
this.mt[0] = this.mt[this.N - 1];
i = 1;
}
if (j >= vector.length) {
j = 0;
}
}
for (k = this.N - 1; k; k--) {
s = this.mt[i - 1] ^ (this.mt[i - 1] >>> 30);
this.mt[i] =
(this.mt[i] ^ (((((s & 0xffff0000) >>> 16) * 1566083941) << 16) + (s & 0x0000ffff) * 1566083941)) - i;
this.mt[i] >>>= 0;
i++;
if (i >= this.N) {
this.mt[0] = this.mt[this.N - 1];
i = 1;
}
}
this.mt[0] = 0x80000000;
}
/**
* Generates a random unsigned 32-bit integer.
*
* @since 0.1.0
* @returns {number}
*/
int() {
let y,
kk,
// eslint-disable-next-line prefer-const
mag01 = [0, this.MATRIX_A];
if (this.mti >= this.N) {
if (this.mti === this.N + 1) {
this.seed(5489);
}
for (kk = 0; kk < this.N - this.M; kk++) {
y = (this.mt[kk] & this.UPPER_MASK) | (this.mt[kk + 1] & this.LOWER_MASK);
this.mt[kk] = this.mt[kk + this.M] ^ (y >>> 1) ^ mag01[y & 1];
}
for (; kk < this.N - 1; kk++) {
y = (this.mt[kk] & this.UPPER_MASK) | (this.mt[kk + 1] & this.LOWER_MASK);
this.mt[kk] = this.mt[kk + (this.M - this.N)] ^ (y >>> 1) ^ mag01[y & 1];
}
y = (this.mt[this.N - 1] & this.UPPER_MASK) | (this.mt[0] & this.LOWER_MASK);
this.mt[this.N - 1] = this.mt[this.M - 1] ^ (y >>> 1) ^ mag01[y & 1];
this.mti = 0;
}
y = this.mt[this.mti++];
y ^= y >>> 11;
y ^= (y << 7) & 0x9d2c5680;
y ^= (y << 15) & 0xefc60000;
y ^= y >>> 18;
return y >>> 0;
}
/**
* Generates a random unsigned 31-bit integer.
*
* @since 0.1.0
* @returns {number}
*/
int31() {
return this.int() >>> 1;
}
/**
* Generates a random real in the interval [0;1] with 32-bit resolution.
*
* @since 0.1.0
* @returns {number}
*/
real() {
return this.int() * (1.0 / (this.MAX_INT - 1));
}
/**
* Generates a random real in the interval ]0;1[ with 32-bit resolution.
*
* @since 0.1.0
* @returns {number}
*/
realx() {
return (this.int() + 0.5) * (1.0 / this.MAX_INT);
}
/**
* Generates a random real in the interval [0;1[ with 32-bit resolution.
*
* @since 0.1.0
* @returns {number}
*/
rnd() {
return this.int() * (1.0 / this.MAX_INT);
}
/**
* Generates a random real in the interval [0;1[ with 32-bit resolution.
*
* Same as .rnd() method - for consistency with Math.random() interface.
*
* @since 0.2.0
* @returns {number}
*/
random() {
return this.rnd();
}
/**
* Generates a random real in the interval [0;1[ with 53-bit resolution.
*
* @since 0.1.0
* @returns {number}
*/
rndHiRes() {
const a = this.int() >>> 5;
const b = this.int() >>> 6;
return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0);
}
/**
* A pseudo-normal distribution using the Box-Muller transform.
* @param {number} mu The normal distribution mean
* @param {number} sigma The normal distribution standard deviation
* @returns {number}
*/
normal(mu, sigma) {
let u = 0;
while (u === 0) u = this.random(); //Converting [0,1) to (0,1)
let v = 0;
while (v === 0) v = this.random(); //Converting [0,1) to (0,1)
const n = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
return n * sigma + mu;
}
/**
* A factory method for generating random uniform rolls
* @return {number}
*/
static random() {
return twist.random();
}
/**
* A factory method for generating random normal rolls
* @return {number}
*/
static normal(...args) {
return twist.normal(...args);
}
}
const twist = new MersenneTwister(Date.now());
export default twist;
|
f89c464b7e834a701b6bf3d03c1edfc6dbeca7ff | 3,256 | ts | TypeScript | RecommenederSystem/api/controllers/MiArticuloController.ts | JonathanPachacama/AplicacionFer | 3a606e22b7c6a8d777e251f695e8dd6d12a54352 | [
"MIT"
] | null | null | null | RecommenederSystem/api/controllers/MiArticuloController.ts | JonathanPachacama/AplicacionFer | 3a606e22b7c6a8d777e251f695e8dd6d12a54352 | [
"MIT"
] | 1 | 2022-02-10T19:23:59.000Z | 2022-02-10T19:23:59.000Z | RecommenederSystem/api/controllers/MiArticuloController.ts | JonathanPachacama/AplicacionFer | 3a606e22b7c6a8d777e251f695e8dd6d12a54352 | [
"MIT"
] | null | null | null | /**
* Created by CEDIA on 25/09/2017.
*/
declare var module;
declare var sails;
declare var Usuario;
declare var Articulo;
declare var MiArticulo;
declare var MiFile;
// /Saludo/crearMiArticulo
module.exports = {
homepage: (req,res) => {
sails.models.MiArticulo.find().exec(
(err, MiArticuloEncontrados) => {
if (err) return res.serverError(err)
return res.view('MisArticulos',{MiArticulo:MiArticuloEncontrados})
}
)
},
editanota:(req,res)=>{
let parametros = req.allParams();
if (parametros.idMiArticulo&&
parametros.title&&
parametros.country&&
parametros.number&&
parametros.volume&&
parametros.year&&
parametros.journal&&
parametros.editorial&&
parametros.abstract&&
parametros.issns&&
parametros.doi&&
parametros.language&&
parametros.keywords&&
parametros.authors&&
parametros.category&&
parametros.pages&&
parametros.notas
){
MiArticulo.update({
id:parametros.idMiArticulo
},{
title:parametros.title,
country:parametros.country,
number:parametros.number,
volume:parametros.volume,
year:parametros.year,
journal:parametros.journal,
editorial:parametros.editorial,
abstract:parametros.abstract,
issns:parametros.issns,
doi:parametros.doi,
language:parametros.language,
keywords:parametros.keywords,
authors:parametros.authors,
category:parametros.category,
pages:parametros.pages,
notas:parametros.notas
})
.exec((err,Editado)=>{
if(err) return res.serverError(err);
if(Editado){
//Si encontro
return res.redirect('/VerMisArticulo?id=' + parametros.idMiArticulo)
}else{
//No encontro
return res.notFound()
}
})
}else{
return res.badRequest()
}
},
viewMiFile:(req,res)=>{
MiFile.find().exec((err,MiFile)=>{
if(err) return res.negotiate(err);
sails.log.info("file",MiFile);
return res.view('VerMisArticulos',{
MiFile:MiFile
})
})
},
///parece no ser necesario///
VerMiFile:(req,res)=>{
let parametros = req.allParams();
if(parametros.id){
MiArticulo.findOne({
id:parametros.id
})
.exec((err,articuloEditado)=>{
if(err) return res.serverError(err);
if(articuloEditado){
//Si encontro
MiFile.findOne({fkIdMiArticulo:parametros.id}).exec(
(error,MiFile)=>{
if(error){
return res.serverError(error);
}
if (!MiFile) {
return res.view('VerMisArticulos',{
MiFile:articuloEditado
})
}
return res.view('VerMisArticulos',{
MiArticulo:articuloEditado,
MiFile:MiFile
})
}
)
}else{
//No encontro
return res.view('MisArticulos')
}
})
}else{
return res.view('MisArticulos')
}
},
};
| 23.594203 | 80 | 0.550676 | 110 | 9 | 0 | 18 | 8 | 0 | 0 | 0 | 0 | 0 | 0 | 15.555556 | 829 | 0.032569 | 0.00965 | 0 | 0 | 0 | 0 | 0 | 0.277825 | /**
* Created by CEDIA on 25/09/2017.
*/
declare var module;
declare var sails;
declare var Usuario;
declare var Articulo;
declare var MiArticulo;
declare var MiFile;
// /Saludo/crearMiArticulo
module.exports = {
homepage: (req,res) => {
sails.models.MiArticulo.find().exec(
(err, MiArticuloEncontrados) => {
if (err) return res.serverError(err)
return res.view('MisArticulos',{MiArticulo:MiArticuloEncontrados})
}
)
},
editanota:(req,res)=>{
let parametros = req.allParams();
if (parametros.idMiArticulo&&
parametros.title&&
parametros.country&&
parametros.number&&
parametros.volume&&
parametros.year&&
parametros.journal&&
parametros.editorial&&
parametros.abstract&&
parametros.issns&&
parametros.doi&&
parametros.language&&
parametros.keywords&&
parametros.authors&&
parametros.category&&
parametros.pages&&
parametros.notas
){
MiArticulo.update({
id:parametros.idMiArticulo
},{
title:parametros.title,
country:parametros.country,
number:parametros.number,
volume:parametros.volume,
year:parametros.year,
journal:parametros.journal,
editorial:parametros.editorial,
abstract:parametros.abstract,
issns:parametros.issns,
doi:parametros.doi,
language:parametros.language,
keywords:parametros.keywords,
authors:parametros.authors,
category:parametros.category,
pages:parametros.pages,
notas:parametros.notas
})
.exec((err,Editado)=>{
if(err) return res.serverError(err);
if(Editado){
//Si encontro
return res.redirect('/VerMisArticulo?id=' + parametros.idMiArticulo)
}else{
//No encontro
return res.notFound()
}
})
}else{
return res.badRequest()
}
},
viewMiFile:(req,res)=>{
MiFile.find().exec((err,MiFile)=>{
if(err) return res.negotiate(err);
sails.log.info("file",MiFile);
return res.view('VerMisArticulos',{
MiFile:MiFile
})
})
},
///parece no ser necesario///
VerMiFile:(req,res)=>{
let parametros = req.allParams();
if(parametros.id){
MiArticulo.findOne({
id:parametros.id
})
.exec((err,articuloEditado)=>{
if(err) return res.serverError(err);
if(articuloEditado){
//Si encontro
MiFile.findOne({fkIdMiArticulo:parametros.id}).exec(
(error,MiFile)=>{
if(error){
return res.serverError(error);
}
if (!MiFile) {
return res.view('VerMisArticulos',{
MiFile:articuloEditado
})
}
return res.view('VerMisArticulos',{
MiArticulo:articuloEditado,
MiFile:MiFile
})
}
)
}else{
//No encontro
return res.view('MisArticulos')
}
})
}else{
return res.view('MisArticulos')
}
},
};
|
d7180447147db133f246707f18b8bdb014643e7a | 3,243 | ts | TypeScript | src/rest/utils/balanced.ts | dynabloxjs/opencloud | be8107c3258a6fdb96deae03dc6cb1142647adfd | [
"MIT"
] | 2 | 2022-03-30T01:16:35.000Z | 2022-03-30T03:57:19.000Z | src/rest/utils/balanced.ts | dynabloxjs/opencloud | be8107c3258a6fdb96deae03dc6cb1142647adfd | [
"MIT"
] | null | null | null | src/rest/utils/balanced.ts | dynabloxjs/opencloud | be8107c3258a6fdb96deae03dc6cb1142647adfd | [
"MIT"
] | 1 | 2022-03-30T03:54:43.000Z | 2022-03-30T03:54:43.000Z | // Get balanced parentheses
// Ported from: https://github.com/juliangruber/balanced-match/blob/master/index.js
export interface Output {
/**
* The index of the first match of a
*/
start: number;
/**
* The index of the matching b
*/
end: number;
/**
* The preamble, a and b not included
*/
pre: string;
/**
* The match, a and b not included
*/
body: string;
/**
* The postscript, a and b not included
*/
post: string;
}
function maybeMatch(reg: RegExp, str: string): string | null {
const m = str.match(reg);
return m ? m[0] : null;
}
/**
* For the first non-nested matching pair of a and b in str, return an object with those keys:
* start the index of the first match of
* `end` the index of the matching b
* `pre` the preamble, a and b not included
* `body` the match, a and b not included
* `post` the postscript, a and b not included
* If there's no match, `undefined` will be returned.
* If the `str` contains more a than b / there are unmatched pairs,
* the first match that was closed will be used.
* For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`
*/
export function balanced(
a: string | RegExp,
b: string | RegExp,
str: string,
): Output | void {
if (a instanceof RegExp) a = maybeMatch(a, str)!;
if (b instanceof RegExp) b = maybeMatch(b, str)!;
const r = range(a, b, str);
return (
r && {
start: r[0] ?? 0,
end: r[1] ?? 0,
pre: str.slice(0, r[0]),
body: str.slice(r[0]! + (a as string).length, r[1]),
post: str.slice(r[1]! + (b as string).length),
}
);
}
/**
* For the first non-nested matching pair of `a` and `b` in `str`,
* return an array with indexes: `[ <a index>, <b index> ]`.
*/
export function range(a: string, b: string, str: string) {
let begs, beg, left, right, result;
let ai = str.indexOf(a);
let bi = str.indexOf(b, ai + 1);
let i = ai;
if (ai >= 0 && bi > 0) {
if (a === b) {
return [ai, bi];
}
begs = [];
left = str.length;
while (i >= 0 && !result) {
if (i === ai) {
begs.push(i);
ai = str.indexOf(a, i + 1);
} else if (begs.length === 1) {
result = [begs.pop(), bi];
} else {
beg = begs.pop();
if (beg! < left!) {
left = beg;
right = bi;
}
bi = str.indexOf(b, i + 1);
}
i = ai < bi && ai >= 0 ? ai : bi;
}
if (begs.length) {
result = [left, right];
}
}
return result;
}
// Ported from: https://github.com/mugendi/balanced-match-all/blob/master/index.js
export function balancedAll(
pre: string,
post: string,
str: string,
includeInside = false,
includeOutside = true,
level = 0,
arr: Output[] = [],
) {
const o = balanced(pre, post, str);
if (o) {
arr.push(o);
const idx = arr.length - 1;
if (idx > 0) {
o.start += arr[idx - 1].start + pre.length;
o.end += arr[idx - 1].start + post.length;
}
// loop till all are called
if (includeInside) {
arr = balancedAll(
pre,
post,
o.body,
includeInside,
includeOutside,
level++,
arr,
);
}
if (includeOutside && arr[idx].end < (str.length - 1)) {
arr = balancedAll(
pre,
post,
str.slice(arr[idx].end - 1),
includeInside,
true,
0,
arr,
);
}
}
return arr;
}
| 20.656051 | 94 | 0.575393 | 104 | 4 | 0 | 15 | 12 | 5 | 4 | 0 | 19 | 1 | 4 | 19.25 | 1,213 | 0.015664 | 0.009893 | 0.004122 | 0.000824 | 0.003298 | 0 | 0.527778 | 0.24024 | // Get balanced parentheses
// Ported from: https://github.com/juliangruber/balanced-match/blob/master/index.js
export interface Output {
/**
* The index of the first match of a
*/
start;
/**
* The index of the matching b
*/
end;
/**
* The preamble, a and b not included
*/
pre;
/**
* The match, a and b not included
*/
body;
/**
* The postscript, a and b not included
*/
post;
}
/* Example usages of 'maybeMatch' are shown below:
maybeMatch(a, str);
maybeMatch(b, str);
*/
function maybeMatch(reg, str) {
const m = str.match(reg);
return m ? m[0] : null;
}
/**
* For the first non-nested matching pair of a and b in str, return an object with those keys:
* start the index of the first match of
* `end` the index of the matching b
* `pre` the preamble, a and b not included
* `body` the match, a and b not included
* `post` the postscript, a and b not included
* If there's no match, `undefined` will be returned.
* If the `str` contains more a than b / there are unmatched pairs,
* the first match that was closed will be used.
* For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`
*/
export /* Example usages of 'balanced' are shown below:
balanced(pre, post, str);
*/
function balanced(
a,
b,
str,
) {
if (a instanceof RegExp) a = maybeMatch(a, str)!;
if (b instanceof RegExp) b = maybeMatch(b, str)!;
const r = range(a, b, str);
return (
r && {
start: r[0] ?? 0,
end: r[1] ?? 0,
pre: str.slice(0, r[0]),
body: str.slice(r[0]! + (a as string).length, r[1]),
post: str.slice(r[1]! + (b as string).length),
}
);
}
/**
* For the first non-nested matching pair of `a` and `b` in `str`,
* return an array with indexes: `[ <a index>, <b index> ]`.
*/
export /* Example usages of 'range' are shown below:
range(a, b, str);
*/
function range(a, b, str) {
let begs, beg, left, right, result;
let ai = str.indexOf(a);
let bi = str.indexOf(b, ai + 1);
let i = ai;
if (ai >= 0 && bi > 0) {
if (a === b) {
return [ai, bi];
}
begs = [];
left = str.length;
while (i >= 0 && !result) {
if (i === ai) {
begs.push(i);
ai = str.indexOf(a, i + 1);
} else if (begs.length === 1) {
result = [begs.pop(), bi];
} else {
beg = begs.pop();
if (beg! < left!) {
left = beg;
right = bi;
}
bi = str.indexOf(b, i + 1);
}
i = ai < bi && ai >= 0 ? ai : bi;
}
if (begs.length) {
result = [left, right];
}
}
return result;
}
// Ported from: https://github.com/mugendi/balanced-match-all/blob/master/index.js
export /* Example usages of 'balancedAll' are shown below:
arr = balancedAll(pre, post, o.body, includeInside, includeOutside, level++, arr);
arr = balancedAll(pre, post, str.slice(arr[idx].end - 1), includeInside, true, 0, arr);
*/
function balancedAll(
pre,
post,
str,
includeInside = false,
includeOutside = true,
level = 0,
arr = [],
) {
const o = balanced(pre, post, str);
if (o) {
arr.push(o);
const idx = arr.length - 1;
if (idx > 0) {
o.start += arr[idx - 1].start + pre.length;
o.end += arr[idx - 1].start + post.length;
}
// loop till all are called
if (includeInside) {
arr = balancedAll(
pre,
post,
o.body,
includeInside,
includeOutside,
level++,
arr,
);
}
if (includeOutside && arr[idx].end < (str.length - 1)) {
arr = balancedAll(
pre,
post,
str.slice(arr[idx].end - 1),
includeInside,
true,
0,
arr,
);
}
}
return arr;
}
|
d7288789b6e870c947d9b5d2c8fe51bb8de33ca3 | 1,589 | ts | TypeScript | src/core/infra/HttpResponse.ts | davydcardoso/WhatsappAPI | d0a1aa2ed22bc15a2a9ca30b507fc0955600e6e4 | [
"MIT"
] | 5 | 2022-01-08T17:13:08.000Z | 2022-01-26T02:17:40.000Z | src/core/infra/HttpResponse.ts | davydcardoso/rocketapi | 893bdad7a48bc4e7eb6db323ad52ab43ca7fbdac | [
"MIT"
] | null | null | null | src/core/infra/HttpResponse.ts | davydcardoso/rocketapi | 893bdad7a48bc4e7eb6db323ad52ab43ca7fbdac | [
"MIT"
] | null | null | null | export type HttpResponse = {
statusCode: number;
body: any;
};
export function ok<T>(dto?: T): HttpResponse {
return {
statusCode: 200,
body: dto,
};
}
export function created(body?: Object): HttpResponse {
return {
statusCode: 201,
body: body !== undefined ? body : undefined,
};
}
export function noContent(body?: Object): HttpResponse {
return {
statusCode: 204,
body: body !== undefined ? body : undefined,
};
}
export function clientError(error: Error): HttpResponse {
return {
statusCode: 400,
body: {
error: error.message,
},
};
}
export function unauthorized(error: Error): HttpResponse {
return {
statusCode: 401,
body: {
error: error.message,
},
};
}
export function forbidden(error: Error): HttpResponse {
return {
statusCode: 403,
body: {
error: error.message,
},
};
}
export function notFound(error: Error): HttpResponse {
return {
statusCode: 404,
body: {
error: error.message,
},
};
}
export function notAcceptable(error: Error): HttpResponse {
return {
statusCode: 406,
body: {
error: error.message,
},
};
}
export function conflict(error: Error): HttpResponse {
return {
statusCode: 409,
body: {
error: error.message,
},
};
}
export function tooMany(error: Error): HttpResponse {
return {
statusCode: 429,
body: {
error: error.message,
},
};
}
export function fail(error: Error) {
return {
statusCode: 500,
body: {
error: error.message,
},
};
}
| 16.214286 | 59 | 0.602895 | 86 | 11 | 0 | 11 | 0 | 2 | 0 | 1 | 1 | 1 | 0 | 5.454545 | 453 | 0.048565 | 0 | 0.004415 | 0.002208 | 0 | 0.041667 | 0.041667 | 0.286532 | export type HttpResponse = {
statusCode;
body;
};
export function ok<T>(dto?) {
return {
statusCode: 200,
body: dto,
};
}
export function created(body?) {
return {
statusCode: 201,
body: body !== undefined ? body : undefined,
};
}
export function noContent(body?) {
return {
statusCode: 204,
body: body !== undefined ? body : undefined,
};
}
export function clientError(error) {
return {
statusCode: 400,
body: {
error: error.message,
},
};
}
export function unauthorized(error) {
return {
statusCode: 401,
body: {
error: error.message,
},
};
}
export function forbidden(error) {
return {
statusCode: 403,
body: {
error: error.message,
},
};
}
export function notFound(error) {
return {
statusCode: 404,
body: {
error: error.message,
},
};
}
export function notAcceptable(error) {
return {
statusCode: 406,
body: {
error: error.message,
},
};
}
export function conflict(error) {
return {
statusCode: 409,
body: {
error: error.message,
},
};
}
export function tooMany(error) {
return {
statusCode: 429,
body: {
error: error.message,
},
};
}
export function fail(error) {
return {
statusCode: 500,
body: {
error: error.message,
},
};
}
|
d7888589a5edea554ef38b5038cfe5db0eca64de | 6,894 | ts | TypeScript | problemset/cat-and-mouse-2/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/cat-and-mouse-2/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/cat-and-mouse-2/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | type StateType = [number, number, TURN]
type ResultType = [
mouseResult: [result: RESULT_FLAG, move: number],
catResult: [result: RESULT_FLAG, move: number],
]
enum TURN {
MOUSE_TURN = 0,
CAT_TURN = 1,
}
enum RESULT_FLAG {
UNKNOWN = 0,
MOUSE_WIN = 1,
CAT_WIN = 2,
}
const MAX_MOVES = 1000
const DIRS = [[-1, 0], [1, 0], [0, -1], [0, 1]]
/**
* 拓扑排序
* @desc 时间复杂度 O(M²N²(M+N)) 空间复杂度 O(M²N²)
* @param grid
* @param catJump
* @param mouseJump
* @returns
*/
export function canMouseWin(
grid: string[],
catJump: number,
mouseJump: number,
): boolean {
const rows = grid.length
const cols = grid[0].length
let startMouse = -1
let startCat = -1
let food = -1
const getPosKey = (row: number, col: number): number => row * cols + col
const getPos = (key: number): [number, number] => [(key / cols) >> 0, key % cols]
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const c = grid[i][j]
if (c === 'M')
startMouse = getPosKey(i, j)
else if (c === 'C')
startCat = getPosKey(i, j)
else if (c === 'F')
food = getPosKey(i, j)
}
}
const total = rows * cols
const degrees: [mouse: number, cat: number][][]
= new Array(total).fill(0).map(() => new Array(total).fill(0).map(() => [0, 0]))
// 计算每个状态的度
for (let mouse = 0; mouse < total; mouse++) {
const [mouseRow, mouseCol] = getPos(mouse)
if (grid[mouseRow][mouseCol] === '#') continue
for (let cat = 0; cat < total; cat++) {
const [catRow, catCol] = getPos(cat)
if (grid[catRow][catCol] === '#') continue
degrees[mouse][cat][TURN.MOUSE_TURN]++
degrees[mouse][cat][TURN.CAT_TURN]++
for (const dir of DIRS) {
for (
let row = mouseRow + dir[0], col = mouseCol + dir[1], jump = 1;
row >= 0 && row < rows && col >= 0 && col < cols && grid[row][col] !== '#' && jump <= mouseJump;
row += dir[0], col += dir[1], jump++
) {
const nextMouse = getPosKey(row, col)
const nextCat = getPosKey(catRow, catCol)
degrees[nextMouse][nextCat][TURN.MOUSE_TURN]++
}
for (
let row = catRow + dir[0], col = catCol + dir[1], jump = 1;
row >= 0 && row < rows && col >= 0 && col < cols && grid[row][col] !== '#' && jump <= catJump;
row += dir[0], col += dir[1], jump++
) {
const nextMouse = getPosKey(mouseRow, mouseCol)
const nextCat = getPosKey(row, col)
degrees[nextMouse][nextCat][TURN.CAT_TURN]++
}
}
}
}
const results: ResultType[][]
= new Array(total).fill(0)
.map(() => new Array(total).fill(0)
.map(() => [[RESULT_FLAG.UNKNOWN, 0], [RESULT_FLAG.UNKNOWN, 0]]),
)
const queue: StateType[] = []
// 猫和老鼠在同一个单元格,猫获胜
for (let pos = 0; pos < total; pos++) {
const [row, col] = getPos(pos)
if (grid[row][col] === '#') continue
results[pos][pos][TURN.MOUSE_TURN][0] = RESULT_FLAG.CAT_WIN
results[pos][pos][TURN.MOUSE_TURN][1] = 0
results[pos][pos][TURN.CAT_TURN][0] = RESULT_FLAG.CAT_WIN
results[pos][pos][TURN.CAT_TURN][1] = 0
queue.push([pos, pos, TURN.MOUSE_TURN])
queue.push([pos, pos, TURN.CAT_TURN])
}
// 猫和食物在同一个单元格,猫获胜
for (let mouse = 0; mouse < total; mouse++) {
const [mouseRow, mouseCol] = getPos(mouse)
if (grid[mouseRow][mouseCol] === '#' || mouse === food) continue
results[mouse][food][TURN.MOUSE_TURN][0] = RESULT_FLAG.CAT_WIN
results[mouse][food][TURN.MOUSE_TURN][1] = 0
results[mouse][food][TURN.CAT_TURN][0] = RESULT_FLAG.CAT_WIN
results[mouse][food][TURN.CAT_TURN][1] = 0
queue.push([mouse, food, TURN.MOUSE_TURN])
queue.push([mouse, food, TURN.CAT_TURN])
}
// 老鼠和食物在同一个单元格且猫和食物不在同一个单元格,老鼠获胜
for (let cat = 0; cat < total; cat++) {
const [catRow, catCol] = getPos(cat)
if (grid[catRow][catCol] === '#' || cat === food) continue
results[food][cat][TURN.MOUSE_TURN][0] = RESULT_FLAG.MOUSE_WIN
results[food][cat][TURN.MOUSE_TURN][1] = 0
results[food][cat][TURN.CAT_TURN][0] = RESULT_FLAG.MOUSE_WIN
results[food][cat][TURN.CAT_TURN][1] = 0
queue.push([food, cat, TURN.MOUSE_TURN])
queue.push([food, cat, TURN.CAT_TURN])
}
// 拓扑排序
while (queue.length) {
const [mouse, cat, turn] = queue.shift()!
const [result, moves] = results[mouse][cat][turn]
const prevStates = getPrevStates(mouse, cat, turn)
for (const prevState of prevStates) {
const [prevMouse, prevCat, prevTurn] = prevState
if (results[prevMouse][prevCat][prevTurn][0] === RESULT_FLAG.UNKNOWN) {
const canWin
= (result === RESULT_FLAG.MOUSE_WIN && prevTurn === TURN.MOUSE_TURN)
|| (result === RESULT_FLAG.CAT_WIN && prevTurn === TURN.CAT_TURN)
if (canWin) {
results[prevMouse][prevCat][prevTurn][0] = result
results[prevMouse][prevCat][prevTurn][1] = moves + 1
queue.push([prevMouse, prevCat, prevTurn])
}
else {
degrees[prevMouse][prevCat][prevTurn]--
if (degrees[prevMouse][prevCat][prevTurn] === 0) {
const loseResult = prevTurn === TURN.MOUSE_TURN ? RESULT_FLAG.CAT_WIN : RESULT_FLAG.MOUSE_WIN
results[prevMouse][prevCat][prevTurn][0] = loseResult
results[prevMouse][prevCat][prevTurn][1] = moves + 1
queue.push([prevMouse, prevCat, prevTurn])
}
}
}
}
}
const [result, move] = results[startMouse][startCat][TURN.MOUSE_TURN]
return result === RESULT_FLAG.MOUSE_WIN && move <= MAX_MOVES
function getPrevStates(mouse: number, cat: number, turn: TURN): StateType[] {
const prevStates: StateType[] = []
const [mouseRow, mouseCol] = getPos(mouse)
const [catRow, catCol] = getPos(cat)
const prevTurn = turn === TURN.MOUSE_TURN ? TURN.CAT_TURN : TURN.MOUSE_TURN
const maxJump = prevTurn === TURN.MOUSE_TURN ? mouseJump : catJump
const startRow = prevTurn === TURN.MOUSE_TURN ? mouseRow : catRow
const startCol = prevTurn === TURN.MOUSE_TURN ? mouseCol : catCol
prevStates.push([mouse, cat, prevTurn])
for (const dir of DIRS) {
for (
let i = startRow + dir[0], j = startCol + dir[1], jump = 1;
i >= 0 && i < rows && j >= 0 && j < cols && grid[i][j] !== '#' && jump <= maxJump;
i += dir[0], j += dir[1], jump++
) {
const prevMouseRow = prevTurn === TURN.MOUSE_TURN ? i : mouseRow
const prevMouseCol = prevTurn === TURN.MOUSE_TURN ? j : mouseCol
const prevCatRow = prevTurn === TURN.MOUSE_TURN ? catRow : i
const prevCatCol = prevTurn === TURN.MOUSE_TURN ? catCol : j
const prevMouse = getPosKey(prevMouseRow, prevMouseCol)
const prevCat = getPosKey(prevCatRow, prevCatCol)
prevStates.push([prevMouse, prevCat, prevTurn])
}
}
return prevStates
}
}
| 34.128713 | 106 | 0.587903 | 164 | 8 | 0 | 9 | 59 | 0 | 3 | 0 | 18 | 2 | 0 | 21.625 | 2,311 | 0.007356 | 0.02553 | 0 | 0.000865 | 0 | 0 | 0.236842 | 0.272587 | type StateType = [number, number, TURN]
type ResultType = [
mouseResult,
catResult,
]
enum TURN {
MOUSE_TURN = 0,
CAT_TURN = 1,
}
enum RESULT_FLAG {
UNKNOWN = 0,
MOUSE_WIN = 1,
CAT_WIN = 2,
}
const MAX_MOVES = 1000
const DIRS = [[-1, 0], [1, 0], [0, -1], [0, 1]]
/**
* 拓扑排序
* @desc 时间复杂度 O(M²N²(M+N)) 空间复杂度 O(M²N²)
* @param grid
* @param catJump
* @param mouseJump
* @returns
*/
export function canMouseWin(
grid,
catJump,
mouseJump,
) {
const rows = grid.length
const cols = grid[0].length
let startMouse = -1
let startCat = -1
let food = -1
/* Example usages of 'getPosKey' are shown below:
startMouse = getPosKey(i, j);
startCat = getPosKey(i, j);
food = getPosKey(i, j);
getPosKey(row, col);
getPosKey(catRow, catCol);
getPosKey(mouseRow, mouseCol);
getPosKey(prevMouseRow, prevMouseCol);
getPosKey(prevCatRow, prevCatCol);
*/
const getPosKey = (row, col) => row * cols + col
/* Example usages of 'getPos' are shown below:
getPos(mouse);
getPos(cat);
getPos(pos);
*/
const getPos = (key) => [(key / cols) >> 0, key % cols]
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const c = grid[i][j]
if (c === 'M')
startMouse = getPosKey(i, j)
else if (c === 'C')
startCat = getPosKey(i, j)
else if (c === 'F')
food = getPosKey(i, j)
}
}
const total = rows * cols
const degrees
= new Array(total).fill(0).map(() => new Array(total).fill(0).map(() => [0, 0]))
// 计算每个状态的度
for (let mouse = 0; mouse < total; mouse++) {
const [mouseRow, mouseCol] = getPos(mouse)
if (grid[mouseRow][mouseCol] === '#') continue
for (let cat = 0; cat < total; cat++) {
const [catRow, catCol] = getPos(cat)
if (grid[catRow][catCol] === '#') continue
degrees[mouse][cat][TURN.MOUSE_TURN]++
degrees[mouse][cat][TURN.CAT_TURN]++
for (const dir of DIRS) {
for (
let row = mouseRow + dir[0], col = mouseCol + dir[1], jump = 1;
row >= 0 && row < rows && col >= 0 && col < cols && grid[row][col] !== '#' && jump <= mouseJump;
row += dir[0], col += dir[1], jump++
) {
const nextMouse = getPosKey(row, col)
const nextCat = getPosKey(catRow, catCol)
degrees[nextMouse][nextCat][TURN.MOUSE_TURN]++
}
for (
let row = catRow + dir[0], col = catCol + dir[1], jump = 1;
row >= 0 && row < rows && col >= 0 && col < cols && grid[row][col] !== '#' && jump <= catJump;
row += dir[0], col += dir[1], jump++
) {
const nextMouse = getPosKey(mouseRow, mouseCol)
const nextCat = getPosKey(row, col)
degrees[nextMouse][nextCat][TURN.CAT_TURN]++
}
}
}
}
const results
= new Array(total).fill(0)
.map(() => new Array(total).fill(0)
.map(() => [[RESULT_FLAG.UNKNOWN, 0], [RESULT_FLAG.UNKNOWN, 0]]),
)
const queue = []
// 猫和老鼠在同一个单元格,猫获胜
for (let pos = 0; pos < total; pos++) {
const [row, col] = getPos(pos)
if (grid[row][col] === '#') continue
results[pos][pos][TURN.MOUSE_TURN][0] = RESULT_FLAG.CAT_WIN
results[pos][pos][TURN.MOUSE_TURN][1] = 0
results[pos][pos][TURN.CAT_TURN][0] = RESULT_FLAG.CAT_WIN
results[pos][pos][TURN.CAT_TURN][1] = 0
queue.push([pos, pos, TURN.MOUSE_TURN])
queue.push([pos, pos, TURN.CAT_TURN])
}
// 猫和食物在同一个单元格,猫获胜
for (let mouse = 0; mouse < total; mouse++) {
const [mouseRow, mouseCol] = getPos(mouse)
if (grid[mouseRow][mouseCol] === '#' || mouse === food) continue
results[mouse][food][TURN.MOUSE_TURN][0] = RESULT_FLAG.CAT_WIN
results[mouse][food][TURN.MOUSE_TURN][1] = 0
results[mouse][food][TURN.CAT_TURN][0] = RESULT_FLAG.CAT_WIN
results[mouse][food][TURN.CAT_TURN][1] = 0
queue.push([mouse, food, TURN.MOUSE_TURN])
queue.push([mouse, food, TURN.CAT_TURN])
}
// 老鼠和食物在同一个单元格且猫和食物不在同一个单元格,老鼠获胜
for (let cat = 0; cat < total; cat++) {
const [catRow, catCol] = getPos(cat)
if (grid[catRow][catCol] === '#' || cat === food) continue
results[food][cat][TURN.MOUSE_TURN][0] = RESULT_FLAG.MOUSE_WIN
results[food][cat][TURN.MOUSE_TURN][1] = 0
results[food][cat][TURN.CAT_TURN][0] = RESULT_FLAG.MOUSE_WIN
results[food][cat][TURN.CAT_TURN][1] = 0
queue.push([food, cat, TURN.MOUSE_TURN])
queue.push([food, cat, TURN.CAT_TURN])
}
// 拓扑排序
while (queue.length) {
const [mouse, cat, turn] = queue.shift()!
const [result, moves] = results[mouse][cat][turn]
const prevStates = getPrevStates(mouse, cat, turn)
for (const prevState of prevStates) {
const [prevMouse, prevCat, prevTurn] = prevState
if (results[prevMouse][prevCat][prevTurn][0] === RESULT_FLAG.UNKNOWN) {
const canWin
= (result === RESULT_FLAG.MOUSE_WIN && prevTurn === TURN.MOUSE_TURN)
|| (result === RESULT_FLAG.CAT_WIN && prevTurn === TURN.CAT_TURN)
if (canWin) {
results[prevMouse][prevCat][prevTurn][0] = result
results[prevMouse][prevCat][prevTurn][1] = moves + 1
queue.push([prevMouse, prevCat, prevTurn])
}
else {
degrees[prevMouse][prevCat][prevTurn]--
if (degrees[prevMouse][prevCat][prevTurn] === 0) {
const loseResult = prevTurn === TURN.MOUSE_TURN ? RESULT_FLAG.CAT_WIN : RESULT_FLAG.MOUSE_WIN
results[prevMouse][prevCat][prevTurn][0] = loseResult
results[prevMouse][prevCat][prevTurn][1] = moves + 1
queue.push([prevMouse, prevCat, prevTurn])
}
}
}
}
}
const [result, move] = results[startMouse][startCat][TURN.MOUSE_TURN]
return result === RESULT_FLAG.MOUSE_WIN && move <= MAX_MOVES
/* Example usages of 'getPrevStates' are shown below:
getPrevStates(mouse, cat, turn);
*/
function getPrevStates(mouse, cat, turn) {
const prevStates = []
const [mouseRow, mouseCol] = getPos(mouse)
const [catRow, catCol] = getPos(cat)
const prevTurn = turn === TURN.MOUSE_TURN ? TURN.CAT_TURN : TURN.MOUSE_TURN
const maxJump = prevTurn === TURN.MOUSE_TURN ? mouseJump : catJump
const startRow = prevTurn === TURN.MOUSE_TURN ? mouseRow : catRow
const startCol = prevTurn === TURN.MOUSE_TURN ? mouseCol : catCol
prevStates.push([mouse, cat, prevTurn])
for (const dir of DIRS) {
for (
let i = startRow + dir[0], j = startCol + dir[1], jump = 1;
i >= 0 && i < rows && j >= 0 && j < cols && grid[i][j] !== '#' && jump <= maxJump;
i += dir[0], j += dir[1], jump++
) {
const prevMouseRow = prevTurn === TURN.MOUSE_TURN ? i : mouseRow
const prevMouseCol = prevTurn === TURN.MOUSE_TURN ? j : mouseCol
const prevCatRow = prevTurn === TURN.MOUSE_TURN ? catRow : i
const prevCatCol = prevTurn === TURN.MOUSE_TURN ? catCol : j
const prevMouse = getPosKey(prevMouseRow, prevMouseCol)
const prevCat = getPosKey(prevCatRow, prevCatCol)
prevStates.push([prevMouse, prevCat, prevTurn])
}
}
return prevStates
}
}
|
d7fb9092fdb59a5468c3a31287ec18c440855fd2 | 7,341 | ts | TypeScript | lib/poly/matrix.ts | dra2020/baseclient | 8dccdf6c247f0dc0a5ce4bf7f8966825d7a2f5c8 | [
"MIT"
] | 1 | 2022-01-19T20:29:12.000Z | 2022-01-19T20:29:12.000Z | lib/poly/matrix.ts | dra2020/baseclient | 8dccdf6c247f0dc0a5ce4bf7f8966825d7a2f5c8 | [
"MIT"
] | null | null | null | lib/poly/matrix.ts | dra2020/baseclient | 8dccdf6c247f0dc0a5ce4bf7f8966825d7a2f5c8 | [
"MIT"
] | null | null | null | //
// SOME BASIC MATRIX OPERATIONS FOR MBR
//
/*
These custom functions are used by minimumBoundingRectangle(), instead of the
same-named mathjs versions. They are tailored specifically for that routine and
are NOT intended for general use.
export declare function matrix(x: Matrix): Matrix;
export declare function multiply(a: Matrix, b: Matrix): Matrix;
export declare function transpose(a: Matrix, b: Matrix): Matrix;
export declare function apply((a: Matrix, over: Dim, cb: applyCB): Vector;
export declare function min(a: Vector): number;
export declare function max(a: Vector): number;
export declare function concat(a: Matrix, b: Matrix, by: Dim): Matrix;
export declare function row(a: Matrix, i: number): Vector;
export declare function subtract(a: Vector, b: Vector): Vector;
export declare function dotMultiply(a: Vector, b: Vector): Vector;
export declare function index(a: Range, b: Range): Index;
export declare function range(start: number, end: number, includeEnd: boolean = false): Vector;
export declare function subset(a: Matrix, select: Index): Matrix;
*/
export type Matrix = number[][];
export type Vector = number[]; // A general vector or a row or a column
export type Range = number[];
export type Index = number[][];
export type applyCB = (v: Vector) => number;
export const enum Dim
{
Rows,
Columns
}
export function matrix(a: Matrix): Matrix
{
return a;
}
export function multiply(a: Matrix, b: Matrix): Matrix
{
protect((nRows(a) > 0), "In multiply, input matrix 'a' has no rows. ");
protect((nCols(a) > 0), "In multiply, input matrix 'a' has no columns. ");
protect((nRows(b) > 0), "In multiply, input matrix 'b' has no rows. ");
protect((nCols(b) > 0), "In multiply, input matrix 'b' has no columns. ");
const m = nRows(a);
const n = nCols(a);
const p = nRows(b);
const q = nCols(b);
protect((p == n), "In multiply, the # rows in matrix 'b' doesn't match the number of columns in matrix 'a'.");
let c: Matrix = initialize(m, n);
for (let i = 0; i < m; i++)
{
for (let j = 0; j < q; j++)
{
const aRow = row(a, i);
const bCol = column(b, j);
c[i][j] = dotProduct(aRow, bCol);
}
}
return c;
}
export function transpose(a: Matrix): Matrix
{
protect((nRows(a) > 0), "In transpose, input matrix has no rows. ");
protect((nCols(a) > 0), "In transpose, input matrix has no columns. ");
const j = nRows(a);
const i = nCols(a);
let b: Matrix = initialize(i, j);
for (let m = 0; m < j; m++)
{
for (let n = 0; n < i; n++)
{
b[n][m] = a[m][n];
}
}
return b;
}
export function apply(a: Matrix, over: Dim, cb: applyCB): Vector
{
protect((nRows(a) > 0), "In apply, input matrix has no rows. ");
protect((nCols(a) > 0), "In apply, input matrix has no columns. ");
let m = nRows(a);
let n = nCols(a);
let result: Vector = [];
const iEnd = (over == Dim.Rows) ? m : n;
const extractFn = (over == Dim.Rows) ? row : column;
for (let i = 0; i < iEnd; i++)
{
const v: Vector = extractFn(a, i);
result.push(cb(v));
}
return result;
}
export function min(v: Vector): number
{
return Math.min(...v);
}
export function max(v: Vector): number
{
return Math.max(...v);
}
export function concat(a: Matrix, b: Matrix, by: Dim): Matrix
{
protect((nRows(a) > 0), "In concat, input matrix 'a' has no rows. ");
protect((nCols(a) > 0), "In concat, input matrix 'a' has no columns. ");
protect((nRows(b) > 0), "In concat, input matrix 'b' has no rows. ");
protect((nCols(b) > 0), "In concat, input matrix 'b' has no columns. ");
let m = nRows(a);
let n = nCols(a);
const p = nRows(b);
const q = nCols(b);
const {i, j} = (by == Dim.Columns) ? {i: m, j: n + q} : {i: m + p, j: n};
let c: Matrix = initialize(i, j);
if (by == Dim.Rows)
protect((n == q), "In concat, concatenating rows but the # of columns don't match. ");
else // (by == Dim.Columns)
protect((m == p), "In concat, concatenating columns but the # of rows don't match. ");
// Copy the first array
for (let i = 0; i < m; i++)
{
for (let j = 0; j < n; j++)
{
c[i][j] = a[i][j];
}
}
m = (by == Dim.Rows) ? m : 0;
n = (by == Dim.Columns) ? n : 0;
// Copy the second array to the right (by columns) or below (by rows)
for (let i = 0; i < p; i++)
{
for (let j = 0; j < q; j++)
{
c[i+m][j+n] = b[i][j];
}
}
return c;
}
export function row(a: Matrix, i: number): Vector
{
protect((nRows(a) > 0), "In row, input matrix has no rows. ");
protect((nCols(a) > 0), "In row, input matrix has no columns. ");
protect((i >= 0), "In row, invalid row index.");
return a[i];
}
export function column(a: Matrix, j: number): Vector
{
protect((nRows(a) > 0), "In column, input matrix has no rows. ");
protect((nCols(a) > 0), "In column, input matrix has no columns. ");
protect((j >= 0), "In row, invalid column index.");
let v: any = [];
for (let i = 0; i < nRows(a); i++)
{
v.push(a[i][j]);
}
return v;
}
export function subtract(a: Vector, b: Vector): Vector
{
protect((a.length == b.length), "In subtract, the input vectors have different lengths.");
let c: Vector = [];
for (let i = 0; i < a.length; i++)
{
c.push(a[i] - b[i]);
}
return c;
}
export function dotMultiply(a: Vector, b: Vector): Vector
{
protect((a.length > 0) && (a.length == b.length), "In dotMultiply, the vectors aren't the same length. ");
let c: Vector = [];
for (let i = 0; i < a.length; i++)
{
c.push(a[i] * b[i]);
}
return c;
}
export function index(a: Range, b: Range): Index
{
return [a, b];
}
export function range(start: number, end: number, includeEnd: boolean = false): Vector
{
let r: Vector = [];
end += includeEnd ? 1 : 0;
for (let i = start; i < end; i++)
{
r.push(i);
}
return r;
}
export function subset(a: Matrix, select: Index): Matrix
{
protect((nRows(a) > 0), "In subset, input matrix has no rows. ");
protect((nCols(a) > 0), "In subset, input matrix has no columns. ");
protect((nRows(select) > 0), "In subset, input matrix has no rows. ");
protect((nCols(select) > 0), "In subset, input matrix has no columns. ");
const m = nRows(a);
const n = nCols(a);
const rowRange = row(select, 0) as Range;
const colRange = row(select, 1) as Range;
const p = rowRange.length;
const q = colRange.length;
let b: Matrix = initialize(p, q);
for (let i = 0; i < p; i++)
{
for (let j = 0; j < q; j++)
{
b[i][j] = a[rowRange[i]][colRange[j]];
}
}
return b;
}
// HELPERS
function initialize(rows: number, cols: number): Matrix
{
protect(((rows > 0) || (cols > 0)), "In initialize, the # of rows or columns is not positive. ");
return [...Array(rows)].fill(0).map(() => [...Array(cols)].fill(0));
};
const nRows = (a: Matrix | Index) => a.length;
const nCols = (a: Matrix | Index) => (a.length > 0) ? a[0].length : 0;
export function dotProduct(a: Vector, b: Vector): number
{
protect((a.length > 0) && (a.length == b.length), "In dotProduct, the vectors aren't the same length. ");
return a.map((value, i) => value * b[i]).reduce((acc, val) => acc + val, 0);
};
function protect(condition: boolean, message: string): void
{
if (!condition)
throw new Error(message);
}
| 23.680645 | 112 | 0.598692 | 203 | 22 | 0 | 39 | 50 | 0 | 9 | 1 | 18 | 5 | 2 | 6.590909 | 2,472 | 0.024676 | 0.020227 | 0 | 0.002023 | 0.000809 | 0.009009 | 0.162162 | 0.298963 | //
// SOME BASIC MATRIX OPERATIONS FOR MBR
//
/*
These custom functions are used by minimumBoundingRectangle(), instead of the
same-named mathjs versions. They are tailored specifically for that routine and
are NOT intended for general use.
export declare function matrix(x: Matrix): Matrix;
export declare function multiply(a: Matrix, b: Matrix): Matrix;
export declare function transpose(a: Matrix, b: Matrix): Matrix;
export declare function apply((a: Matrix, over: Dim, cb: applyCB): Vector;
export declare function min(a: Vector): number;
export declare function max(a: Vector): number;
export declare function concat(a: Matrix, b: Matrix, by: Dim): Matrix;
export declare function row(a: Matrix, i: number): Vector;
export declare function subtract(a: Vector, b: Vector): Vector;
export declare function dotMultiply(a: Vector, b: Vector): Vector;
export declare function index(a: Range, b: Range): Index;
export declare function range(start: number, end: number, includeEnd: boolean = false): Vector;
export declare function subset(a: Matrix, select: Index): Matrix;
*/
export type Matrix = number[][];
export type Vector = number[]; // A general vector or a row or a column
export type Range = number[];
export type Index = number[][];
export type applyCB = (v) => number;
export const enum Dim
{
Rows,
Columns
}
export function matrix(a)
{
return a;
}
export function multiply(a, b)
{
protect((nRows(a) > 0), "In multiply, input matrix 'a' has no rows. ");
protect((nCols(a) > 0), "In multiply, input matrix 'a' has no columns. ");
protect((nRows(b) > 0), "In multiply, input matrix 'b' has no rows. ");
protect((nCols(b) > 0), "In multiply, input matrix 'b' has no columns. ");
const m = nRows(a);
const n = nCols(a);
const p = nRows(b);
const q = nCols(b);
protect((p == n), "In multiply, the # rows in matrix 'b' doesn't match the number of columns in matrix 'a'.");
let c = initialize(m, n);
for (let i = 0; i < m; i++)
{
for (let j = 0; j < q; j++)
{
const aRow = row(a, i);
const bCol = column(b, j);
c[i][j] = dotProduct(aRow, bCol);
}
}
return c;
}
export function transpose(a)
{
protect((nRows(a) > 0), "In transpose, input matrix has no rows. ");
protect((nCols(a) > 0), "In transpose, input matrix has no columns. ");
const j = nRows(a);
const i = nCols(a);
let b = initialize(i, j);
for (let m = 0; m < j; m++)
{
for (let n = 0; n < i; n++)
{
b[n][m] = a[m][n];
}
}
return b;
}
export function apply(a, over, cb)
{
protect((nRows(a) > 0), "In apply, input matrix has no rows. ");
protect((nCols(a) > 0), "In apply, input matrix has no columns. ");
let m = nRows(a);
let n = nCols(a);
let result = [];
const iEnd = (over == Dim.Rows) ? m : n;
const extractFn = (over == Dim.Rows) ? row : column;
for (let i = 0; i < iEnd; i++)
{
const v = extractFn(a, i);
result.push(cb(v));
}
return result;
}
export /* Example usages of 'min' are shown below:
Math.min(...v);
*/
function min(v)
{
return Math.min(...v);
}
export /* Example usages of 'max' are shown below:
Math.max(...v);
*/
function max(v)
{
return Math.max(...v);
}
export function concat(a, b, by)
{
protect((nRows(a) > 0), "In concat, input matrix 'a' has no rows. ");
protect((nCols(a) > 0), "In concat, input matrix 'a' has no columns. ");
protect((nRows(b) > 0), "In concat, input matrix 'b' has no rows. ");
protect((nCols(b) > 0), "In concat, input matrix 'b' has no columns. ");
let m = nRows(a);
let n = nCols(a);
const p = nRows(b);
const q = nCols(b);
const {i, j} = (by == Dim.Columns) ? {i: m, j: n + q} : {i: m + p, j: n};
let c = initialize(i, j);
if (by == Dim.Rows)
protect((n == q), "In concat, concatenating rows but the # of columns don't match. ");
else // (by == Dim.Columns)
protect((m == p), "In concat, concatenating columns but the # of rows don't match. ");
// Copy the first array
for (let i = 0; i < m; i++)
{
for (let j = 0; j < n; j++)
{
c[i][j] = a[i][j];
}
}
m = (by == Dim.Rows) ? m : 0;
n = (by == Dim.Columns) ? n : 0;
// Copy the second array to the right (by columns) or below (by rows)
for (let i = 0; i < p; i++)
{
for (let j = 0; j < q; j++)
{
c[i+m][j+n] = b[i][j];
}
}
return c;
}
export /* Example usages of 'row' are shown below:
row(a, i);
(over == Dim.Rows) ? row : column;
row(select, 0);
row(select, 1);
*/
function row(a, i)
{
protect((nRows(a) > 0), "In row, input matrix has no rows. ");
protect((nCols(a) > 0), "In row, input matrix has no columns. ");
protect((i >= 0), "In row, invalid row index.");
return a[i];
}
export /* Example usages of 'column' are shown below:
column(b, j);
(over == Dim.Rows) ? row : column;
*/
function column(a, j)
{
protect((nRows(a) > 0), "In column, input matrix has no rows. ");
protect((nCols(a) > 0), "In column, input matrix has no columns. ");
protect((j >= 0), "In row, invalid column index.");
let v = [];
for (let i = 0; i < nRows(a); i++)
{
v.push(a[i][j]);
}
return v;
}
export function subtract(a, b)
{
protect((a.length == b.length), "In subtract, the input vectors have different lengths.");
let c = [];
for (let i = 0; i < a.length; i++)
{
c.push(a[i] - b[i]);
}
return c;
}
export function dotMultiply(a, b)
{
protect((a.length > 0) && (a.length == b.length), "In dotMultiply, the vectors aren't the same length. ");
let c = [];
for (let i = 0; i < a.length; i++)
{
c.push(a[i] * b[i]);
}
return c;
}
export function index(a, b)
{
return [a, b];
}
export function range(start, end, includeEnd = false)
{
let r = [];
end += includeEnd ? 1 : 0;
for (let i = start; i < end; i++)
{
r.push(i);
}
return r;
}
export function subset(a, select)
{
protect((nRows(a) > 0), "In subset, input matrix has no rows. ");
protect((nCols(a) > 0), "In subset, input matrix has no columns. ");
protect((nRows(select) > 0), "In subset, input matrix has no rows. ");
protect((nCols(select) > 0), "In subset, input matrix has no columns. ");
const m = nRows(a);
const n = nCols(a);
const rowRange = row(select, 0) as Range;
const colRange = row(select, 1) as Range;
const p = rowRange.length;
const q = colRange.length;
let b = initialize(p, q);
for (let i = 0; i < p; i++)
{
for (let j = 0; j < q; j++)
{
b[i][j] = a[rowRange[i]][colRange[j]];
}
}
return b;
}
// HELPERS
/* Example usages of 'initialize' are shown below:
initialize(m, n);
initialize(i, j);
initialize(p, q);
*/
function initialize(rows, cols)
{
protect(((rows > 0) || (cols > 0)), "In initialize, the # of rows or columns is not positive. ");
return [...Array(rows)].fill(0).map(() => [...Array(cols)].fill(0));
};
/* Example usages of 'nRows' are shown below:
nRows(a) > 0;
nRows(b) > 0;
nRows(a);
nRows(b);
i < nRows(a);
nRows(select) > 0;
*/
const nRows = (a) => a.length;
/* Example usages of 'nCols' are shown below:
nCols(a) > 0;
nCols(b) > 0;
nCols(a);
nCols(b);
nCols(select) > 0;
*/
const nCols = (a) => (a.length > 0) ? a[0].length : 0;
export /* Example usages of 'dotProduct' are shown below:
c[i][j] = dotProduct(aRow, bCol);
*/
function dotProduct(a, b)
{
protect((a.length > 0) && (a.length == b.length), "In dotProduct, the vectors aren't the same length. ");
return a.map((value, i) => value * b[i]).reduce((acc, val) => acc + val, 0);
};
/* Example usages of 'protect' are shown below:
protect((nRows(a) > 0), "In multiply, input matrix 'a' has no rows. ");
protect((nCols(a) > 0), "In multiply, input matrix 'a' has no columns. ");
protect((nRows(b) > 0), "In multiply, input matrix 'b' has no rows. ");
protect((nCols(b) > 0), "In multiply, input matrix 'b' has no columns. ");
protect((p == n), "In multiply, the # rows in matrix 'b' doesn't match the number of columns in matrix 'a'.");
protect((nRows(a) > 0), "In transpose, input matrix has no rows. ");
protect((nCols(a) > 0), "In transpose, input matrix has no columns. ");
protect((nRows(a) > 0), "In apply, input matrix has no rows. ");
protect((nCols(a) > 0), "In apply, input matrix has no columns. ");
protect((nRows(a) > 0), "In concat, input matrix 'a' has no rows. ");
protect((nCols(a) > 0), "In concat, input matrix 'a' has no columns. ");
protect((nRows(b) > 0), "In concat, input matrix 'b' has no rows. ");
protect((nCols(b) > 0), "In concat, input matrix 'b' has no columns. ");
protect((n == q), "In concat, concatenating rows but the # of columns don't match. ");
protect((m == p), "In concat, concatenating columns but the # of rows don't match. ");
protect((nRows(a) > 0), "In row, input matrix has no rows. ");
protect((nCols(a) > 0), "In row, input matrix has no columns. ");
protect((i >= 0), "In row, invalid row index.");
protect((nRows(a) > 0), "In column, input matrix has no rows. ");
protect((nCols(a) > 0), "In column, input matrix has no columns. ");
protect((j >= 0), "In row, invalid column index.");
protect((a.length == b.length), "In subtract, the input vectors have different lengths.");
protect((a.length > 0) && (a.length == b.length), "In dotMultiply, the vectors aren't the same length. ");
protect((nRows(a) > 0), "In subset, input matrix has no rows. ");
protect((nCols(a) > 0), "In subset, input matrix has no columns. ");
protect((nRows(select) > 0), "In subset, input matrix has no rows. ");
protect((nCols(select) > 0), "In subset, input matrix has no columns. ");
protect(((rows > 0) || (cols > 0)), "In initialize, the # of rows or columns is not positive. ");
protect((a.length > 0) && (a.length == b.length), "In dotProduct, the vectors aren't the same length. ");
*/
function protect(condition, message)
{
if (!condition)
throw new Error(message);
}
|
b31a5e2a1789d50d26c605d881b979a28beb80a4 | 3,607 | ts | TypeScript | src/index.ts | x6ud/closest-points-between-two-lines | 0407eb2574defb61fc24175fd20b06e0f716bff8 | [
"MIT"
] | 1 | 2022-01-09T06:29:47.000Z | 2022-01-09T06:29:47.000Z | src/index.ts | x6ud/closest-points-between-two-lines | 0407eb2574defb61fc24175fd20b06e0f716bff8 | [
"MIT"
] | null | null | null | src/index.ts | x6ud/closest-points-between-two-lines | 0407eb2574defb61fc24175fd20b06e0f716bff8 | [
"MIT"
] | null | null | null | type Vec3 = [number, number, number] | Float32Array | Float64Array;
/**
* Find the two closest points on two 3D lines.
* Return true if two lines are parallel.
*
* @param out1 Output - The closest point on line 1.
* @param out2 Output - The closest point on line 2.
* @param p1x X of a point on line 1.
* @param p1y Y of a point on line 1.
* @param p1z Z of a point on line 1.
* @param n1x X of the unit vector of the direction of line 1.
* @param n1y Y of the unit vector of the direction of line 1.
* @param n1z Z of the unit vector of the direction of line 1.
* @param p2x X of a point on line 2.
* @param p2y Y of a point on line 2.
* @param p2z Z of a point on line 2.
* @param n2x X of the unit vector of the direction of line 2.
* @param n2y Y of the unit vector of the direction of line 2.
* @param n2z Z of the unit vector of the direction of line 2.
*/
export default function closestPointsBetweenTwoLines(
out1: Vec3 | null, out2: Vec3 | null,
p1x: number, p1y: number, p1z: number,
n1x: number, n1y: number, n1z: number,
p2x: number, p2y: number, p2z: number,
n2x: number, n2y: number, n2z: number
): boolean {
let d = n1x ** 2 * n2y ** 2
+ n1x ** 2 * n2z ** 2
- 2 * n1x * n1y * n2x * n2y
- 2 * n1x * n1z * n2x * n2z
+ n1y ** 2 * n2x ** 2
+ n1y ** 2 * n2z ** 2
- 2 * n1y * n1z * n2y * n2z
+ n1z ** 2 * n2x ** 2
+ n1z ** 2 * n2y ** 2;
let parallel = false;
let t1 = (
n1x * n2x * n2y * p1y
- n1x * n2x * n2y * p2y
+ n1x * n2x * n2z * p1z
- n1x * n2x * n2z * p2z
- n1x * n2y ** 2 * p1x
+ n1x * n2y ** 2 * p2x
- n1x * n2z ** 2 * p1x
+ n1x * n2z ** 2 * p2x
- n1y * n2x ** 2 * p1y
+ n1y * n2x ** 2 * p2y
+ n1y * n2x * n2y * p1x
- n1y * n2x * n2y * p2x
+ n1y * n2y * n2z * p1z
- n1y * n2y * n2z * p2z
- n1y * n2z ** 2 * p1y
+ n1y * n2z ** 2 * p2y
- n1z * n2x ** 2 * p1z
+ n1z * n2x ** 2 * p2z
+ n1z * n2x * n2z * p1x
- n1z * n2x * n2z * p2x
- n1z * n2y ** 2 * p1z
+ n1z * n2y ** 2 * p2z
+ n1z * n2y * n2z * p1y
- n1z * n2y * n2z * p2y) / d;
if (!isFinite(t1)) {
parallel = true;
t1 = 0;
}
let o1x = p1x + n1x * t1;
let o1y = p1y + n1y * t1;
let o1z = p1z + n1z * t1;
if (out1) {
out1[0] = o1x;
out1[1] = o1y;
out1[2] = o1z;
}
if (out2) {
let t3 = (
-n1x * n2y * p1z
+ n1x * n2y * p2z
+ n1x * n2z * p1y
- n1x * n2z * p2y
+ n1y * n2x * p1z
- n1y * n2x * p2z
- n1y * n2z * p1x
+ n1y * n2z * p2x
- n1z * n2x * p1y
+ n1z * n2x * p2y
+ n1z * n2y * p1x
- n1z * n2y * p2x) / d;
if (isFinite(t3)) {
let n3x = n1y * n2z - n1z * n2y;
let n3y = -n1x * n2z + n1z * n2x;
let n3z = n1x * n2y - n1y * n2x;
out2[0] = o1x + n3x * t3;
out2[1] = o1y + n3y * t3;
out2[2] = o1z + n3z * t3;
} else {
parallel = true;
let n3x = n1y * (p1z - p2z) - n1z * (p1y - p2y);
let n3y = -n1x * (p1z - p2z) + n1z * (p1x - p2x);
let n3z = n1x * (p1y - p2y) - n1y * (p1x - p2x);
out2[0] = o1x + n1y * n3z - n1z * n3y;
out2[1] = o1y + -n1x * n3z + n1z * n3x;
out2[2] = o1z + n1x * n3y - n1y * n3x;
}
}
return parallel;
} | 33.398148 | 67 | 0.45883 | 88 | 1 | 0 | 14 | 13 | 0 | 0 | 0 | 16 | 1 | 0 | 79 | 1,591 | 0.009428 | 0.008171 | 0 | 0.000629 | 0 | 0 | 0.571429 | 0.219399 | type Vec3 = [number, number, number] | Float32Array | Float64Array;
/**
* Find the two closest points on two 3D lines.
* Return true if two lines are parallel.
*
* @param out1 Output - The closest point on line 1.
* @param out2 Output - The closest point on line 2.
* @param p1x X of a point on line 1.
* @param p1y Y of a point on line 1.
* @param p1z Z of a point on line 1.
* @param n1x X of the unit vector of the direction of line 1.
* @param n1y Y of the unit vector of the direction of line 1.
* @param n1z Z of the unit vector of the direction of line 1.
* @param p2x X of a point on line 2.
* @param p2y Y of a point on line 2.
* @param p2z Z of a point on line 2.
* @param n2x X of the unit vector of the direction of line 2.
* @param n2y Y of the unit vector of the direction of line 2.
* @param n2z Z of the unit vector of the direction of line 2.
*/
export default function closestPointsBetweenTwoLines(
out1, out2,
p1x, p1y, p1z,
n1x, n1y, n1z,
p2x, p2y, p2z,
n2x, n2y, n2z
) {
let d = n1x ** 2 * n2y ** 2
+ n1x ** 2 * n2z ** 2
- 2 * n1x * n1y * n2x * n2y
- 2 * n1x * n1z * n2x * n2z
+ n1y ** 2 * n2x ** 2
+ n1y ** 2 * n2z ** 2
- 2 * n1y * n1z * n2y * n2z
+ n1z ** 2 * n2x ** 2
+ n1z ** 2 * n2y ** 2;
let parallel = false;
let t1 = (
n1x * n2x * n2y * p1y
- n1x * n2x * n2y * p2y
+ n1x * n2x * n2z * p1z
- n1x * n2x * n2z * p2z
- n1x * n2y ** 2 * p1x
+ n1x * n2y ** 2 * p2x
- n1x * n2z ** 2 * p1x
+ n1x * n2z ** 2 * p2x
- n1y * n2x ** 2 * p1y
+ n1y * n2x ** 2 * p2y
+ n1y * n2x * n2y * p1x
- n1y * n2x * n2y * p2x
+ n1y * n2y * n2z * p1z
- n1y * n2y * n2z * p2z
- n1y * n2z ** 2 * p1y
+ n1y * n2z ** 2 * p2y
- n1z * n2x ** 2 * p1z
+ n1z * n2x ** 2 * p2z
+ n1z * n2x * n2z * p1x
- n1z * n2x * n2z * p2x
- n1z * n2y ** 2 * p1z
+ n1z * n2y ** 2 * p2z
+ n1z * n2y * n2z * p1y
- n1z * n2y * n2z * p2y) / d;
if (!isFinite(t1)) {
parallel = true;
t1 = 0;
}
let o1x = p1x + n1x * t1;
let o1y = p1y + n1y * t1;
let o1z = p1z + n1z * t1;
if (out1) {
out1[0] = o1x;
out1[1] = o1y;
out1[2] = o1z;
}
if (out2) {
let t3 = (
-n1x * n2y * p1z
+ n1x * n2y * p2z
+ n1x * n2z * p1y
- n1x * n2z * p2y
+ n1y * n2x * p1z
- n1y * n2x * p2z
- n1y * n2z * p1x
+ n1y * n2z * p2x
- n1z * n2x * p1y
+ n1z * n2x * p2y
+ n1z * n2y * p1x
- n1z * n2y * p2x) / d;
if (isFinite(t3)) {
let n3x = n1y * n2z - n1z * n2y;
let n3y = -n1x * n2z + n1z * n2x;
let n3z = n1x * n2y - n1y * n2x;
out2[0] = o1x + n3x * t3;
out2[1] = o1y + n3y * t3;
out2[2] = o1z + n3z * t3;
} else {
parallel = true;
let n3x = n1y * (p1z - p2z) - n1z * (p1y - p2y);
let n3y = -n1x * (p1z - p2z) + n1z * (p1x - p2x);
let n3z = n1x * (p1y - p2y) - n1y * (p1x - p2x);
out2[0] = o1x + n1y * n3z - n1z * n3y;
out2[1] = o1y + -n1x * n3z + n1z * n3x;
out2[2] = o1z + n1x * n3y - n1y * n3x;
}
}
return parallel;
} |