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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
52d6fc301866fccc3a2004222d9a88498840f05e | 6,289 | ts | TypeScript | UID_Test/ClientApp/src/client/createRouters.ts | leeichang/UID_Test | e0542a2ce5fd8c1693864db0db5edf71dad2919b | [
"MIT"
] | 1 | 2022-03-22T14:02:13.000Z | 2022-03-22T14:02:13.000Z | UID_Test/ClientApp/src/client/createRouters.ts | leeichang/UID_Test | e0542a2ce5fd8c1693864db0db5edf71dad2919b | [
"MIT"
] | null | null | null | UID_Test/ClientApp/src/client/createRouters.ts | leeichang/UID_Test | e0542a2ce5fd8c1693864db0db5edf71dad2919b | [
"MIT"
] | null | null | null |
interface Config {
rc: any
redirect?: string
rootFile?: string
/** 过滤文件 */
filter?: (file: any) => boolean
/** 定义组件返回 */
component: (file: any) => any
}
/**
* https://github.com/MrHzq/vue-router-auto
* rc:require.context 传入的文件
* redirect:需要将根路由(/)重定向到的路由
* rootFile:页面级别的.vue存放的文件名称
* filter:过滤文件
* component:定义组件返回
*/
export function createRouters(config: Config) {
// 所生成的所有路由数组
const Routers: any = []
const defaultConfig: Config = {
rc: null,
redirect: '',
rootFile: 'pages',
filter: () => true,
component: () => ({})
}
const { rc, redirect, filter, rootFile, component } = (<any>Object).assign(
{},
defaultConfig,
config
)
if (rc === null) return Routers
// allRouters[object]:存储所有路由的变量:先将所有的路由生成,然后放在该变量里面
const allRouters: any = {
len1: []
}
// 通过循环RC(传入的文件)
const routerFileAndLen = rc
.keys()
.filter(filter)
.map((fileName: any) => {
// 因为得到的filename格式是: './baseButton.vue', 所以这里我们去掉头和尾,只保留真正的文件名
const realFileName = fileName
.replace(/^\.\//, '')
.replace(/\.\w+$/, '')
return {
file: fileName,
fileName: realFileName,
// routerName(路由名称):将 / 转为 - 并去掉 _
routerName: realFileName.replace(/\//g, '-').replace(/_/g, '').replace(/-index/g, ''),
// routerComponent(路由异步component的文件路径):将 ./baseButton.vue 从 . 之后截取
routerComponent: fileName.substr(1),
// fileLen(文件的层级深度):通过 / 的数量来判断当前文件的深度
fileLen: fileName.match(/\//g).length
}
})
.sort((i: any, j: any) => i.fileLen - j.fileLen) // 通过文件深度 升序排序
// 传入文件中最大深度
let maxLen = 0
routerFileAndLen.map((r: any) => {
const name = r.routerName
// 生成一块路由对象,包含:name、fileName(用于后续处理真正path的依据)、path、needDelectName(用于后续处理,判断是否删除name的依据)、component
const obj = {
name,
exact: true,
fileName: r.fileName,
// path:只是以name命名的path,还不是真正的路由path
path: '/' + (name === 'index' ? '' : name),
// needDelectName: name === 'index',
needDelectName: false,
component: component(rc(r.file))//() => import(`~/${rootFile}${r.routerComponent}`)
}
maxLen = r.fileLen
// allRouters的key:以 'len'加当前的文件深度 作为key
const key = 'len' + maxLen
if (Array.isArray(allRouters[key])) allRouters[key].push(obj)
else allRouters[key] = [obj]
})
// 将根目录层的路由放入Routers中
// @ts-ignore
Routers.push(...allRouters.len1)
// 截取名称方法:从开始到最后一个'-'之间的字符串
const substrName = (name: any) => name.substr(0, name.lastIndexOf('-'))
/**
* 正式生成路由:1、将相应的路由放在对应的路由下,形成子路由;2、生成同级路由
* index:当前文件深度,为maxlen的倒序循环
* nofindnum:未找到路由的次数
* newcurr:当前新的深度下的路由数据
*/
const ceateRouter = (index: any, nofindnum = 0, newcurr = null) => {
// 当前深度下的路由数据:优先使用传入的newcurr,其次获取当前深度对应的路由数据
const curr = newcurr || allRouters['len' + index]
// 当前深度上一层的路由数据
const pre = allRouters['len' + (index - 1)]
// 若 没有上一层的数据了
if (!pre) {
// 则表明是属于顶层的路由
curr.map((c: any) => {
let path = '/' + c.fileName.replace('/index', '')
// if (path.match('_')) path = path.replace('/_', '/:')
// 将真正的路由path赋值给当前路由
c.path = path
// 将当前路由放到Routers里面
Routers.push(c)
})
return
}
// 在上一层中 未找到的 当前深度路由数据
let noFind: any = []
// 循环当前深度路由数据
curr?.map((c: any) => {
// 在 上一层深度 的路由数据里面查找
const fobj = pre.find((p: any) => {
// 生成 当前深度 当前项 路由的name
let name = substrName(c.name)
// 循环nofindnum,当nofindnum>0,则表示已经出现:在上一层中未找到对应的父路由,则需要将 当前深度 当前项 路由的name 再次生成
for (let i = 0; i < nofindnum; i++) {
name = substrName(name)
}
return name === p.name
})
// 如果 找到了 对应的 父路由数据(fobj)
if (fobj) {
// 生成 当前路由的path:1、去掉当前路由中与父路由重复的;2、去掉/;3、将 _ 转为 :;
let path = c.fileName
.replace(fobj.fileName, '')
.substr(1)
.replace('_', ':')
if (path.match('/') && !path.match('/:')) {
path = path.replace('/index', '')
}
if (path === undefined) {
throw new Error(
`找到了对应的父路由,但是生成子路由的path为【undefined】了`
)
}
// 将真正的路由path赋值给当前路由
c.path = path
// 若:当前路由为 index
if (path === 'index') {
// 1、转为 '' path,'':表明是默认子路由,那父路由就不能存在name属性
c.path = ''
// 2、将父路由的needDelectName标记为true,表明需要删除它的name
fobj.needDelectName = fobj.needDelectName || true
}
// 将当前路由放到父路由的children里面
if (Array.isArray(fobj.children)) fobj.children.push(c)
else fobj.children = [c]
} else noFind.push(c) // 表明未找到父路由,则先将当前路由的数据放入noFind中存储起来
})
// 若存在:未找到的路由数据,则再次向上一个层级寻找
if (noFind.length) ceateRouter(index - 1, ++nofindnum, noFind)
}
// 倒序循环 最大深度,然后调用生成路由方法
for (let i = maxLen; i > 1; i--) ceateRouter(i)
// 路由生成完毕了,应该删除 有默认子路由的父路由的name属性
const deleteNameFun = (arr: any) => {
arr.map((r: any) => {
// 删除多余的fileName属性
delete r.fileName
// 判断是否需要删除name属性
if (r.needDelectName) delete r.name
// 判断完毕了,则要删除needDelectName属性
delete r.needDelectName
// 若 存在子路由 则继续调用deleteNameFun,删除name
if (Array.isArray(r.children)) deleteNameFun(r.children)
})
}
// 调用deleteNameFun,先删除Routers的一级路由的name
deleteNameFun(Routers)
// 若存在重定向的路由,则加入重定向
if (redirect) Routers.unshift({ path: '/', redirect })
// 返回正儿八经的的路由数据
return Routers
} | 32.755208 | 105 | 0.503101 | 116 | 13 | 0 | 14 | 22 | 5 | 3 | 19 | 3 | 1 | 0 | 17.076923 | 2,007 | 0.013453 | 0.010962 | 0.002491 | 0.000498 | 0 | 0.351852 | 0.055556 | 0.233272 |
interface Config {
rc
redirect?
rootFile?
/** 过滤文件 */
filter?
/** 定义组件返回 */
component
}
/**
* https://github.com/MrHzq/vue-router-auto
* rc:require.context 传入的文件
* redirect:需要将根路由(/)重定向到的路由
* rootFile:页面级别的.vue存放的文件名称
* filter:过滤文件
* component:定义组件返回
*/
export function createRouters(config) {
// 所生成的所有路由数组
const Routers = []
const defaultConfig = {
rc: null,
redirect: '',
rootFile: 'pages',
filter: () => true,
component: () => ({})
}
const { rc, redirect, filter, rootFile, component } = (<any>Object).assign(
{},
defaultConfig,
config
)
if (rc === null) return Routers
// allRouters[object]:存储所有路由的变量:先将所有的路由生成,然后放在该变量里面
const allRouters = {
len1: []
}
// 通过循环RC(传入的文件)
const routerFileAndLen = rc
.keys()
.filter(filter)
.map((fileName) => {
// 因为得到的filename格式是: './baseButton.vue', 所以这里我们去掉头和尾,只保留真正的文件名
const realFileName = fileName
.replace(/^\.\//, '')
.replace(/\.\w+$/, '')
return {
file: fileName,
fileName: realFileName,
// routerName(路由名称):将 / 转为 - 并去掉 _
routerName: realFileName.replace(/\//g, '-').replace(/_/g, '').replace(/-index/g, ''),
// routerComponent(路由异步component的文件路径):将 ./baseButton.vue 从 . 之后截取
routerComponent: fileName.substr(1),
// fileLen(文件的层级深度):通过 / 的数量来判断当前文件的深度
fileLen: fileName.match(/\//g).length
}
})
.sort((i, j) => i.fileLen - j.fileLen) // 通过文件深度 升序排序
// 传入文件中最大深度
let maxLen = 0
routerFileAndLen.map((r) => {
const name = r.routerName
// 生成一块路由对象,包含:name、fileName(用于后续处理真正path的依据)、path、needDelectName(用于后续处理,判断是否删除name的依据)、component
const obj = {
name,
exact: true,
fileName: r.fileName,
// path:只是以name命名的path,还不是真正的路由path
path: '/' + (name === 'index' ? '' : name),
// needDelectName: name === 'index',
needDelectName: false,
component: component(rc(r.file))//() => import(`~/${rootFile}${r.routerComponent}`)
}
maxLen = r.fileLen
// allRouters的key:以 'len'加当前的文件深度 作为key
const key = 'len' + maxLen
if (Array.isArray(allRouters[key])) allRouters[key].push(obj)
else allRouters[key] = [obj]
})
// 将根目录层的路由放入Routers中
// @ts-ignore
Routers.push(...allRouters.len1)
// 截取名称方法:从开始到最后一个'-'之间的字符串
/* Example usages of 'substrName' are shown below:
substrName(c.name);
name = substrName(name);
*/
const substrName = (name) => name.substr(0, name.lastIndexOf('-'))
/**
* 正式生成路由:1、将相应的路由放在对应的路由下,形成子路由;2、生成同级路由
* index:当前文件深度,为maxlen的倒序循环
* nofindnum:未找到路由的次数
* newcurr:当前新的深度下的路由数据
*/
/* Example usages of 'ceateRouter' are shown below:
ceateRouter(index - 1, ++nofindnum, noFind);
ceateRouter(i);
*/
const ceateRouter = (index, nofindnum = 0, newcurr = null) => {
// 当前深度下的路由数据:优先使用传入的newcurr,其次获取当前深度对应的路由数据
const curr = newcurr || allRouters['len' + index]
// 当前深度上一层的路由数据
const pre = allRouters['len' + (index - 1)]
// 若 没有上一层的数据了
if (!pre) {
// 则表明是属于顶层的路由
curr.map((c) => {
let path = '/' + c.fileName.replace('/index', '')
// if (path.match('_')) path = path.replace('/_', '/:')
// 将真正的路由path赋值给当前路由
c.path = path
// 将当前路由放到Routers里面
Routers.push(c)
})
return
}
// 在上一层中 未找到的 当前深度路由数据
let noFind = []
// 循环当前深度路由数据
curr?.map((c) => {
// 在 上一层深度 的路由数据里面查找
const fobj = pre.find((p) => {
// 生成 当前深度 当前项 路由的name
let name = substrName(c.name)
// 循环nofindnum,当nofindnum>0,则表示已经出现:在上一层中未找到对应的父路由,则需要将 当前深度 当前项 路由的name 再次生成
for (let i = 0; i < nofindnum; i++) {
name = substrName(name)
}
return name === p.name
})
// 如果 找到了 对应的 父路由数据(fobj)
if (fobj) {
// 生成 当前路由的path:1、去掉当前路由中与父路由重复的;2、去掉/;3、将 _ 转为 :;
let path = c.fileName
.replace(fobj.fileName, '')
.substr(1)
.replace('_', ':')
if (path.match('/') && !path.match('/:')) {
path = path.replace('/index', '')
}
if (path === undefined) {
throw new Error(
`找到了对应的父路由,但是生成子路由的path为【undefined】了`
)
}
// 将真正的路由path赋值给当前路由
c.path = path
// 若:当前路由为 index
if (path === 'index') {
// 1、转为 '' path,'':表明是默认子路由,那父路由就不能存在name属性
c.path = ''
// 2、将父路由的needDelectName标记为true,表明需要删除它的name
fobj.needDelectName = fobj.needDelectName || true
}
// 将当前路由放到父路由的children里面
if (Array.isArray(fobj.children)) fobj.children.push(c)
else fobj.children = [c]
} else noFind.push(c) // 表明未找到父路由,则先将当前路由的数据放入noFind中存储起来
})
// 若存在:未找到的路由数据,则再次向上一个层级寻找
if (noFind.length) ceateRouter(index - 1, ++nofindnum, noFind)
}
// 倒序循环 最大深度,然后调用生成路由方法
for (let i = maxLen; i > 1; i--) ceateRouter(i)
// 路由生成完毕了,应该删除 有默认子路由的父路由的name属性
/* Example usages of 'deleteNameFun' are shown below:
deleteNameFun(r.children);
// 调用deleteNameFun,先删除Routers的一级路由的name
deleteNameFun(Routers);
*/
const deleteNameFun = (arr) => {
arr.map((r) => {
// 删除多余的fileName属性
delete r.fileName
// 判断是否需要删除name属性
if (r.needDelectName) delete r.name
// 判断完毕了,则要删除needDelectName属性
delete r.needDelectName
// 若 存在子路由 则继续调用deleteNameFun,删除name
if (Array.isArray(r.children)) deleteNameFun(r.children)
})
}
// 调用deleteNameFun,先删除Routers的一级路由的name
deleteNameFun(Routers)
// 若存在重定向的路由,则加入重定向
if (redirect) Routers.unshift({ path: '/', redirect })
// 返回正儿八经的的路由数据
return Routers
} |
52e10f052dbde116c2dcbfb430911014f48e2abb | 1,359 | ts | TypeScript | Controller.v2/src/utils/utc-helper.ts | JonathanHartmann/fbcontrolv4 | 52656b744fdcccf8c6c80cec02e17084251fb340 | [
"MIT"
] | 1 | 2022-01-27T17:38:29.000Z | 2022-01-27T17:38:29.000Z | Website.v2/src/utils/utc-helper.ts | JonathanHartmann/fbcontrolv4 | 52656b744fdcccf8c6c80cec02e17084251fb340 | [
"MIT"
] | null | null | null | Website.v2/src/utils/utc-helper.ts | JonathanHartmann/fbcontrolv4 | 52656b744fdcccf8c6c80cec02e17084251fb340 | [
"MIT"
] | null | null | null |
export const getTime = (date: Date): string => {
if (date) {
const hours = date.getUTCHours().toString();
const min = date.getUTCMinutes().toString();
return formatTime(hours, min);
} else {
return '';
}
}
export const getTimezoneTime = (date: Date): string => {
if (date) {
const hours = date.getHours().toString();
const min = date.getMinutes().toString();
return formatTime(hours, min);
} else {
return '';
}
}
const formatTime = (h: string, m: string): string => {
if (h.length === 1) {
h = '0' + h;
}
if (m.length === 1) {
m = '0' + m;
}
return `${h}:${m}`;
}
export const getDate = (date: Date): string => {
return dateToString(date, false);
}
export const getDisplayDate = (date: Date): string => {
return dateToString(date, true);
}
const dateToString = (date: Date, display: boolean): string => {
if (date) {
const year = date.getUTCFullYear();
let month = (date.getUTCMonth() + (display? 1 : 0)).toString();
let day = date.getUTCDate().toString();
if (month.length === 1) {
month = '0' + month;
}
if (day.length === 1) {
day = '0' + day;
}
return `${year}-${month}-${day}`;
} else {
return '';
}
}
export const toDateTime = (secs: number): Date => {
const t = new Date(secs * 1000); // Epoch
return t;
} | 21.571429 | 67 | 0.557027 | 53 | 7 | 0 | 9 | 15 | 0 | 2 | 0 | 10 | 0 | 0 | 5.571429 | 417 | 0.038369 | 0.035971 | 0 | 0 | 0 | 0 | 0.322581 | 0.377472 |
export const getTime = (date) => {
if (date) {
const hours = date.getUTCHours().toString();
const min = date.getUTCMinutes().toString();
return formatTime(hours, min);
} else {
return '';
}
}
export const getTimezoneTime = (date) => {
if (date) {
const hours = date.getHours().toString();
const min = date.getMinutes().toString();
return formatTime(hours, min);
} else {
return '';
}
}
/* Example usages of 'formatTime' are shown below:
formatTime(hours, min);
*/
const formatTime = (h, m) => {
if (h.length === 1) {
h = '0' + h;
}
if (m.length === 1) {
m = '0' + m;
}
return `${h}:${m}`;
}
export const getDate = (date) => {
return dateToString(date, false);
}
export const getDisplayDate = (date) => {
return dateToString(date, true);
}
/* Example usages of 'dateToString' are shown below:
dateToString(date, false);
dateToString(date, true);
*/
const dateToString = (date, display) => {
if (date) {
const year = date.getUTCFullYear();
let month = (date.getUTCMonth() + (display? 1 : 0)).toString();
let day = date.getUTCDate().toString();
if (month.length === 1) {
month = '0' + month;
}
if (day.length === 1) {
day = '0' + day;
}
return `${year}-${month}-${day}`;
} else {
return '';
}
}
export const toDateTime = (secs) => {
const t = new Date(secs * 1000); // Epoch
return t;
} |
52e46bb83d7cb7c606df933aa7135dee70d9bb3e | 2,842 | ts | TypeScript | server/node_modules/apollo-server-core/src/plugin/usageReporting/durationHistogram.ts | kelseykodes/book-worm | 60447b38d6576a078dd02e4979c398996207c3d9 | [
"MIT"
] | 2 | 2022-01-23T01:41:05.000Z | 2022-01-25T06:54:23.000Z | server/node_modules/apollo-server-core/src/plugin/usageReporting/durationHistogram.ts | kelseykodes/book-worm | 60447b38d6576a078dd02e4979c398996207c3d9 | [
"MIT"
] | 3 | 2022-03-16T15:57:02.000Z | 2022-03-25T16:18:29.000Z | server/node_modules/apollo-server-core/src/plugin/usageReporting/durationHistogram.ts | kelseykodes/book-worm | 60447b38d6576a078dd02e4979c398996207c3d9 | [
"MIT"
] | 1 | 2022-02-23T19:21:28.000Z | 2022-02-23T19:21:28.000Z | export interface DurationHistogramOptions {
initSize?: number;
buckets?: number[];
}
export class DurationHistogram {
// Note that it's legal for the values in "buckets" to be non-integers; they
// will be floored by toArray (which is called by the protobuf encoder).
// (We take advantage of this for field latencies specifically, because
// the ability to return a non-1 weight from fieldLevelInstrumentation
// means we want to build up our histograms as floating-point rather than
// rounding after every operation.)
private readonly buckets: number[];
static readonly BUCKET_COUNT = 384;
static readonly EXPONENT_LOG = Math.log(1.1);
toArray(): number[] {
let bufferedZeroes = 0;
const outputArray: number[] = [];
for (const value of this.buckets) {
if (value === 0) {
bufferedZeroes++;
} else {
if (bufferedZeroes === 1) {
outputArray.push(0);
} else if (bufferedZeroes !== 0) {
outputArray.push(-bufferedZeroes);
}
outputArray.push(Math.floor(value));
bufferedZeroes = 0;
}
}
return outputArray;
}
static durationToBucket(durationNs: number): number {
const log = Math.log(durationNs / 1000.0);
const unboundedBucket = Math.ceil(log / DurationHistogram.EXPONENT_LOG);
// Compare <= 0 to catch -0 and -infinity
return unboundedBucket <= 0 || Number.isNaN(unboundedBucket)
? 0
: unboundedBucket >= DurationHistogram.BUCKET_COUNT
? DurationHistogram.BUCKET_COUNT - 1
: unboundedBucket;
}
incrementDuration(durationNs: number, value = 1): DurationHistogram {
this.incrementBucket(DurationHistogram.durationToBucket(durationNs), value);
return this;
}
incrementBucket(bucket: number, value = 1) {
if (bucket >= DurationHistogram.BUCKET_COUNT) {
// Since we don't have fixed size arrays I'd rather throw the error manually
throw Error('Bucket is out of bounds of the buckets array');
}
// Extend the array if we haven't gotten it long enough to handle the new bucket
if (bucket >= this.buckets.length) {
const oldLength = this.buckets.length;
this.buckets.length = bucket + 1;
this.buckets.fill(0, oldLength);
}
this.buckets[bucket] += value;
}
combine(otherHistogram: DurationHistogram) {
for (let i = 0; i < otherHistogram.buckets.length; i++) {
this.incrementBucket(i, otherHistogram.buckets[i]);
}
}
constructor(options?: DurationHistogramOptions) {
const initSize = options?.initSize || 74;
const buckets = options?.buckets;
const arrayInitSize = Math.max(buckets?.length || 0, initSize);
this.buckets = Array<number>(arrayInitSize).fill(0);
if (buckets) {
buckets.forEach((val, index) => (this.buckets[index] = val));
}
}
}
| 32.295455 | 84 | 0.666432 | 65 | 7 | 0 | 9 | 9 | 5 | 2 | 0 | 10 | 2 | 0 | 6.428571 | 731 | 0.021888 | 0.012312 | 0.00684 | 0.002736 | 0 | 0 | 0.333333 | 0.265976 | export interface DurationHistogramOptions {
initSize?;
buckets?;
}
export class DurationHistogram {
// Note that it's legal for the values in "buckets" to be non-integers; they
// will be floored by toArray (which is called by the protobuf encoder).
// (We take advantage of this for field latencies specifically, because
// the ability to return a non-1 weight from fieldLevelInstrumentation
// means we want to build up our histograms as floating-point rather than
// rounding after every operation.)
private readonly buckets;
static readonly BUCKET_COUNT = 384;
static readonly EXPONENT_LOG = Math.log(1.1);
toArray() {
let bufferedZeroes = 0;
const outputArray = [];
for (const value of this.buckets) {
if (value === 0) {
bufferedZeroes++;
} else {
if (bufferedZeroes === 1) {
outputArray.push(0);
} else if (bufferedZeroes !== 0) {
outputArray.push(-bufferedZeroes);
}
outputArray.push(Math.floor(value));
bufferedZeroes = 0;
}
}
return outputArray;
}
static durationToBucket(durationNs) {
const log = Math.log(durationNs / 1000.0);
const unboundedBucket = Math.ceil(log / DurationHistogram.EXPONENT_LOG);
// Compare <= 0 to catch -0 and -infinity
return unboundedBucket <= 0 || Number.isNaN(unboundedBucket)
? 0
: unboundedBucket >= DurationHistogram.BUCKET_COUNT
? DurationHistogram.BUCKET_COUNT - 1
: unboundedBucket;
}
incrementDuration(durationNs, value = 1) {
this.incrementBucket(DurationHistogram.durationToBucket(durationNs), value);
return this;
}
incrementBucket(bucket, value = 1) {
if (bucket >= DurationHistogram.BUCKET_COUNT) {
// Since we don't have fixed size arrays I'd rather throw the error manually
throw Error('Bucket is out of bounds of the buckets array');
}
// Extend the array if we haven't gotten it long enough to handle the new bucket
if (bucket >= this.buckets.length) {
const oldLength = this.buckets.length;
this.buckets.length = bucket + 1;
this.buckets.fill(0, oldLength);
}
this.buckets[bucket] += value;
}
combine(otherHistogram) {
for (let i = 0; i < otherHistogram.buckets.length; i++) {
this.incrementBucket(i, otherHistogram.buckets[i]);
}
}
constructor(options?) {
const initSize = options?.initSize || 74;
const buckets = options?.buckets;
const arrayInitSize = Math.max(buckets?.length || 0, initSize);
this.buckets = Array<number>(arrayInitSize).fill(0);
if (buckets) {
buckets.forEach((val, index) => (this.buckets[index] = val));
}
}
}
|
061ff6d38d7937dfc5d58418015175ee872e76fe | 2,507 | ts | TypeScript | server/src/apiModules/user/user.parameters.ts | saqwxz/raspberry-iot-rola-dht22 | b35980067ccdb91b59cd6319d8441ac8cbb0f817 | [
"MIT"
] | 1 | 2022-02-24T07:35:21.000Z | 2022-02-24T07:35:21.000Z | server/src/apiModules/user/user.parameters.ts | saqwxz/raspberry-iot-rola-dht22 | b35980067ccdb91b59cd6319d8441ac8cbb0f817 | [
"MIT"
] | null | null | null | server/src/apiModules/user/user.parameters.ts | saqwxz/raspberry-iot-rola-dht22 | b35980067ccdb91b59cd6319d8441ac8cbb0f817 | [
"MIT"
] | null | null | null |
export type CreateOneUserRequest = {
bodyAuthLevel: number,
bodyEmail: string,
bodyPassword: string,
bodyPhone: string,
bodyUserStatus: number,
bodyUsername: string,
}
export const CreateOneUserRequestConvert = (
body: any,
query: any,
path: any,
) => {
return {
bodyAuthLevel: parseInt(body.authLevel),
bodyEmail: body.email,
bodyPassword: body.password,
bodyPhone: body.phone,
bodyUserStatus: parseInt(body.userStatus),
bodyUsername: body.username,
};
};
export type LoginUserRequest = {
bodyEmail: string,
bodyPassword: string,
}
export const LoginUserRequestConvert = (
body: any,
query: any,
path: any,
) => {
return {
bodyEmail: body.email,
bodyPassword: body.password,
};
};
export type LogoutUserRequest = {
}
export const LogoutUserRequestConvert = (
body: any,
query: any,
path: any,
) => {
return {
};
};
export type DeleteOneUserRequest = {
pathId: number
}
export const DeleteOneUserRequestConvert = (
body: any,
query: any,
path: any,
) => {
return {
pathId: parseInt(path.id),
};
};
export type ReadOneUserRequest = {
pathId: number
}
export const ReadOneUserRequestConvert = (
body: any,
query: any,
path: any,
) => {
return {
pathId: parseInt(path.id),
};
};
export type UpdateOneUserRequest = {
pathId: number
bodyAuthLevel: number,
bodyEmail: string,
bodyPassword: string,
bodyPhone: string,
bodyUserStatus: number,
bodyUsername: string,
}
export const UpdateOneUserRequestConvert = (
body: any,
query: any,
path: any,
) => {
return {
pathId: parseInt(path.id),
bodyAuthLevel: parseInt(body.authLevel),
bodyEmail: body.email,
bodyPassword: body.password,
bodyPhone: body.phone,
bodyUserStatus: parseInt(body.userStatus),
bodyUsername: body.username,
};
};
export type CreateManyUsersRequest = {
bodyAuthLevel: number,
bodyEmail: string,
bodyPassword: string,
bodyPhone: string,
bodyUserStatus: number,
bodyUsername: string,
}
export const CreateManyUsersRequestConvert = (
body: any,
query: any,
path: any,
) => {
const arrayBody = body.map((e: any) => {
return {
bodyAuthLevel: parseInt(e.authLevel),
bodyEmail: e.email,
bodyPassword: e.password,
bodyPhone: e.phone,
bodyUserStatus: parseInt(e.userStatus),
bodyUsername: e.username,
};
});
return arrayBody;
};
| 19.585938 | 46 | 0.649382 | 119 | 8 | 0 | 22 | 8 | 23 | 0 | 22 | 23 | 7 | 0 | 6 | 692 | 0.043353 | 0.011561 | 0.033237 | 0.010116 | 0 | 0.360656 | 0.377049 | 0.319375 |
export type CreateOneUserRequest = {
bodyAuthLevel,
bodyEmail,
bodyPassword,
bodyPhone,
bodyUserStatus,
bodyUsername,
}
export const CreateOneUserRequestConvert = (
body,
query,
path,
) => {
return {
bodyAuthLevel: parseInt(body.authLevel),
bodyEmail: body.email,
bodyPassword: body.password,
bodyPhone: body.phone,
bodyUserStatus: parseInt(body.userStatus),
bodyUsername: body.username,
};
};
export type LoginUserRequest = {
bodyEmail,
bodyPassword,
}
export const LoginUserRequestConvert = (
body,
query,
path,
) => {
return {
bodyEmail: body.email,
bodyPassword: body.password,
};
};
export type LogoutUserRequest = {
}
export const LogoutUserRequestConvert = (
body,
query,
path,
) => {
return {
};
};
export type DeleteOneUserRequest = {
pathId
}
export const DeleteOneUserRequestConvert = (
body,
query,
path,
) => {
return {
pathId: parseInt(path.id),
};
};
export type ReadOneUserRequest = {
pathId
}
export const ReadOneUserRequestConvert = (
body,
query,
path,
) => {
return {
pathId: parseInt(path.id),
};
};
export type UpdateOneUserRequest = {
pathId
bodyAuthLevel,
bodyEmail,
bodyPassword,
bodyPhone,
bodyUserStatus,
bodyUsername,
}
export const UpdateOneUserRequestConvert = (
body,
query,
path,
) => {
return {
pathId: parseInt(path.id),
bodyAuthLevel: parseInt(body.authLevel),
bodyEmail: body.email,
bodyPassword: body.password,
bodyPhone: body.phone,
bodyUserStatus: parseInt(body.userStatus),
bodyUsername: body.username,
};
};
export type CreateManyUsersRequest = {
bodyAuthLevel,
bodyEmail,
bodyPassword,
bodyPhone,
bodyUserStatus,
bodyUsername,
}
export const CreateManyUsersRequestConvert = (
body,
query,
path,
) => {
const arrayBody = body.map((e) => {
return {
bodyAuthLevel: parseInt(e.authLevel),
bodyEmail: e.email,
bodyPassword: e.password,
bodyPhone: e.phone,
bodyUserStatus: parseInt(e.userStatus),
bodyUsername: e.username,
};
});
return arrayBody;
};
|
063387b59b79d31d7cceded5326507068d4f2305 | 3,344 | ts | TypeScript | src/runtime.ts | state-less/react-server | 964d2f9d164fa5e75de2a7e77f2823c05dfb0da1 | [
"MIT",
"Unlicense"
] | null | null | null | src/runtime.ts | state-less/react-server | 964d2f9d164fa5e75de2a7e77f2823c05dfb0da1 | [
"MIT",
"Unlicense"
] | 11 | 2022-01-29T14:12:34.000Z | 2022-03-19T02:54:43.000Z | src/runtime.ts | state-less/react-server | 964d2f9d164fa5e75de2a7e77f2823c05dfb0da1 | [
"MIT",
"Unlicense"
] | null | null | null | const filterComponents = (child) =>
child && child.server && "function" == typeof child;
const filterRenderer = (child) =>
child && child.server && child.handler && "function" == typeof child.handler;
const reduceComponents = (lkp, cmp) => {
lkp[cmp.key] = cmp;
return lkp;
};
/**
* Contains the rendered tree.
*/
export const tree = {};
export const parentMap = {};
const isElement = (object: any) => {
if (!object) return false;
return typeof object.type === "function" && object.props;
};
export const render = async (
component,
props,
connectionInfo,
parent = null
) => {
/** The current component that gets rendered */
let current = component,
root;
/** Maintains a stack of components to be rendered */
let stack = [];
do {
if (isElement(current)) {
/** A normal component is similar to JSX.Element */
current = await current.type(props, connectionInfo, parent);
} else if (typeof current === "function") {
/** Components can return Components which will be rendered in a second pass; usually upon a client request */
current = await current(props, connectionInfo);
} else if (typeof current === "object") {
/** Usually components are already transformed to objects and no further processing needs to be done */
current = await current;
} else if (current === null || typeof current === "undefined") {
current = null;
} else {
throw new Error("Component not valid");
}
/** If a component renders another component we need to store the tree to be able to look up providers */
if (isElement(current) && component.key !== current.key) {
/** We skip arrays, as they are keyless childs. */
if (Array.isArray(component) && parent) {
parentMap[current.key] = parent;
} else {
parentMap[current.key] = component;
}
}
root = current;
/** We need to traverse the tree as some component down the tree might have rendered components */
let children = current?.props?.children;
if (children) {
children = await Promise.all([current?.props?.children].flat());
current.props.children = children;
}
if (current && children) {
for (var i = 0; i < children.length; i++) {
const child = await children[i];
if (Array.isArray(child)) {
for (var j = 0; j < child.length; j++) {
children[i][j] = await render(
child[j],
props,
connectionInfo,
current
);
if (children[i][j]?.key) parentMap[children[i][j].key] = current;
}
} else {
if (child?.key) parentMap[child.key] = current;
}
// if (child && typeof child !== 'function')
// continue;
children[i] = await render(child, props, connectionInfo, current);
}
}
if (current && current.component) {
// if (cmp.component === 'ClientComponent') continue;
// throw new Error("client")
}
if (Array.isArray(current)) {
stack.push(...current);
}
/** If the component rendered a functin we need to render it again */
if (typeof current !== "function") current = stack.shift();
} while (current);
Object.assign(tree, root);
/** The resolved tree */
return root;
};
| 31.252336 | 116 | 0.595993 | 77 | 5 | 0 | 9 | 14 | 0 | 2 | 1 | 0 | 0 | 7 | 12.4 | 819 | 0.017094 | 0.017094 | 0 | 0 | 0.008547 | 0.035714 | 0 | 0.264565 | const filterComponents = (child) =>
child && child.server && "function" == typeof child;
const filterRenderer = (child) =>
child && child.server && child.handler && "function" == typeof child.handler;
const reduceComponents = (lkp, cmp) => {
lkp[cmp.key] = cmp;
return lkp;
};
/**
* Contains the rendered tree.
*/
export const tree = {};
export const parentMap = {};
/* Example usages of 'isElement' are shown below:
isElement(current);
isElement(current) && component.key !== current.key;
*/
const isElement = (object) => {
if (!object) return false;
return typeof object.type === "function" && object.props;
};
export /* Example usages of 'render' are shown below:
render(child[j], props, connectionInfo, current);
render(child, props, connectionInfo, current);
*/
const render = async (
component,
props,
connectionInfo,
parent = null
) => {
/** The current component that gets rendered */
let current = component,
root;
/** Maintains a stack of components to be rendered */
let stack = [];
do {
if (isElement(current)) {
/** A normal component is similar to JSX.Element */
current = await current.type(props, connectionInfo, parent);
} else if (typeof current === "function") {
/** Components can return Components which will be rendered in a second pass; usually upon a client request */
current = await current(props, connectionInfo);
} else if (typeof current === "object") {
/** Usually components are already transformed to objects and no further processing needs to be done */
current = await current;
} else if (current === null || typeof current === "undefined") {
current = null;
} else {
throw new Error("Component not valid");
}
/** If a component renders another component we need to store the tree to be able to look up providers */
if (isElement(current) && component.key !== current.key) {
/** We skip arrays, as they are keyless childs. */
if (Array.isArray(component) && parent) {
parentMap[current.key] = parent;
} else {
parentMap[current.key] = component;
}
}
root = current;
/** We need to traverse the tree as some component down the tree might have rendered components */
let children = current?.props?.children;
if (children) {
children = await Promise.all([current?.props?.children].flat());
current.props.children = children;
}
if (current && children) {
for (var i = 0; i < children.length; i++) {
const child = await children[i];
if (Array.isArray(child)) {
for (var j = 0; j < child.length; j++) {
children[i][j] = await render(
child[j],
props,
connectionInfo,
current
);
if (children[i][j]?.key) parentMap[children[i][j].key] = current;
}
} else {
if (child?.key) parentMap[child.key] = current;
}
// if (child && typeof child !== 'function')
// continue;
children[i] = await render(child, props, connectionInfo, current);
}
}
if (current && current.component) {
// if (cmp.component === 'ClientComponent') continue;
// throw new Error("client")
}
if (Array.isArray(current)) {
stack.push(...current);
}
/** If the component rendered a functin we need to render it again */
if (typeof current !== "function") current = stack.shift();
} while (current);
Object.assign(tree, root);
/** The resolved tree */
return root;
};
|
f4123dfcc3de7156f63e6996f27badaae74e59bc | 1,927 | ts | TypeScript | lib/process-services-cloud/src/lib/task-cloud/models/filter-cloud.model.ts | stevetweeddale/alfresco-ng2-components | 5fc03cf26b919e770745a3fb78eb05709b23f835 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | lib/process-services-cloud/src/lib/task-cloud/models/filter-cloud.model.ts | stevetweeddale/alfresco-ng2-components | 5fc03cf26b919e770745a3fb78eb05709b23f835 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2022-02-27T23:58:39.000Z | 2022-03-02T12:50:14.000Z | lib/process-services-cloud/src/lib/task-cloud/models/filter-cloud.model.ts | stevetweeddale/alfresco-ng2-components | 5fc03cf26b919e770745a3fb78eb05709b23f835 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*!
* @license
* Copyright 2016 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export class QueryModel {
processDefinitionId: string;
appName: string;
state: string;
sort: string;
assignment: string;
order: string;
constructor(obj?: any) {
if (obj) {
this.appName = obj.appName || null;
this.processDefinitionId = obj.processDefinitionId || null;
this.state = obj.state || null;
this.sort = obj.sort || null;
this.assignment = obj.assignment || null;
this.order = obj.order || null;
}
}
}
export class TaskFilterCloudRepresentationModel {
id: string;
name: string;
key: string;
icon: string;
query: QueryModel;
constructor(obj?: any) {
if (obj) {
this.id = obj.id;
this.name = obj.name;
this.key = obj.key;
this.icon = obj.icon;
this.query = new QueryModel(obj.query);
}
}
hasFilter() {
return !!this.query;
}
}
export class FilterParamsModel {
id?: string;
name?: string;
key?: string;
index?: number;
constructor(obj?: any) {
if (obj) {
this.id = obj.id || null;
this.name = obj.name || null;
this.key = obj.key || null;
this.index = obj.index;
}
}
}
| 26.763889 | 75 | 0.587961 | 51 | 4 | 0 | 3 | 0 | 15 | 0 | 3 | 14 | 3 | 0 | 5.5 | 488 | 0.014344 | 0 | 0.030738 | 0.006148 | 0 | 0.136364 | 0.636364 | 0.210513 | /*!
* @license
* Copyright 2016 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export class QueryModel {
processDefinitionId;
appName;
state;
sort;
assignment;
order;
constructor(obj?) {
if (obj) {
this.appName = obj.appName || null;
this.processDefinitionId = obj.processDefinitionId || null;
this.state = obj.state || null;
this.sort = obj.sort || null;
this.assignment = obj.assignment || null;
this.order = obj.order || null;
}
}
}
export class TaskFilterCloudRepresentationModel {
id;
name;
key;
icon;
query;
constructor(obj?) {
if (obj) {
this.id = obj.id;
this.name = obj.name;
this.key = obj.key;
this.icon = obj.icon;
this.query = new QueryModel(obj.query);
}
}
hasFilter() {
return !!this.query;
}
}
export class FilterParamsModel {
id?;
name?;
key?;
index?;
constructor(obj?) {
if (obj) {
this.id = obj.id || null;
this.name = obj.name || null;
this.key = obj.key || null;
this.index = obj.index;
}
}
}
|
f49da3344f8374115865cb50cd0ff119cbf7301c | 12,877 | ts | TypeScript | src/trivia-state-machine.ts | willheslam/typescript-analyze-trace | 2c9a33ecfd2e31f81f3f9ab6c015405492dba12c | [
"MIT"
] | 138 | 2022-01-15T01:24:17.000Z | 2022-03-30T13:26:55.000Z | src/trivia-state-machine.ts | willheslam/typescript-analyze-trace | 2c9a33ecfd2e31f81f3f9ab6c015405492dba12c | [
"MIT"
] | 16 | 2022-01-14T22:28:03.000Z | 2022-03-12T01:26:10.000Z | src/trivia-state-machine.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.
const code_CarriageReturn = "\r".charCodeAt(0);
const code_NewLine = "\n".charCodeAt(0);
const code_Space = " ".charCodeAt(0);
const code_Tab = "\t".charCodeAt(0);
const code_Slash = "/".charCodeAt(0);
const code_Backslash = "\\".charCodeAt(0);
const code_Star = "*".charCodeAt(0);
const code_Hash = "#".charCodeAt(0);
const code_Bang = "!".charCodeAt(0);
const code_SingleQuote = "'".charCodeAt(0);
const code_DoubleQuote = "\"".charCodeAt(0);
const code_OpenBrace = "{".charCodeAt(0);
const code_CloseBrace = "}".charCodeAt(0);
const code_OpenBracket = "[".charCodeAt(0);
const code_CloseBracket = "]".charCodeAt(0);
const code_Backtick = "`".charCodeAt(0);
const code_Dollar = "$".charCodeAt(0);
const enum State {
Uninitialized,
Default,
StartSingleLineComment,
SingleLineComment,
StartMultiLineComment,
MultiLineComment,
EndMultiLineComment,
StartShebangComment,
ShebangComment,
SingleQuoteString,
SingleQuoteStringEscapeBackslash,
SingleQuoteStringEscapeQuote,
DoubleQuoteString,
DoubleQuoteStringEscapeBackslash,
DoubleQuoteStringEscapeQuote,
TemplateString,
TemplateStringEscapeBackslash,
TemplateStringEscapeQuote,
StartExpressionHole,
Regex,
RegexEscapeBackslash,
RegexEscapeSlash,
RegexEscapeOpenBracket,
CharClass,
CharClassEscapeBackslash,
CharClassEscapeCloseBracket,
}
export type CharKind =
| "whitespace"
| "comment"
| "string"
| "regex"
| "code"
;
interface StepResult {
charKind: CharKind;
wrapLine: boolean;
}
export interface StateMachine {
step(ch: number, nextCh: number): StepResult;
}
export function create(): StateMachine {
let state = State.Default;
let braceDepth = 0;
let templateStringBraceDepthStack: number[] = [];
let isBOF = true;
function step(ch: number, nextCh: number): StepResult {
let nextStateId = State.Uninitialized;;
let wrapLine = false;
switch (ch) {
case code_CarriageReturn:
if (nextCh === code_NewLine) {
if (state === State.ShebangComment ||
state === State.SingleLineComment ||
// Cases below are for error recovery
state === State.SingleQuoteString ||
state === State.DoubleQuoteString ||
state === State.Regex ||
state === State.CharClass) {
state = State.Default;
}
break;
}
// Fall through
case code_NewLine:
wrapLine = true;
if (state === State.ShebangComment ||
state === State.SingleLineComment) {
state = State.Default;
}
else if (state === State.SingleQuoteString || // Error recovery
state === State.DoubleQuoteString) { // Error recovery
state = State.Default;
}
break;
case code_Slash:
if (state === State.Default) {
if (nextCh === code_Slash) {
state = State.StartSingleLineComment;
}
else if (nextCh === code_Star) {
// It seems like there might technically be a corner case where this is the beginning of an invalid regex
state = State.StartMultiLineComment;
}
else {
// TODO (https://github.com/microsoft/typescript-analyze-trace/issues/14): this is too aggressive - it will catch division
state = State.Regex;
}
}
else if (state === State.StartSingleLineComment) {
state = State.SingleLineComment;
}
else if (state === State.EndMultiLineComment) {
nextStateId = State.Default;
}
else if (state === State.Regex) {
nextStateId = State.Default;
}
else if (state === State.RegexEscapeSlash) {
nextStateId = State.Regex;
}
break;
case code_Star:
if (state === State.StartMultiLineComment) {
state = State.MultiLineComment;
}
else if (state === State.MultiLineComment) {
if (nextCh === code_Slash) {
state = State.EndMultiLineComment;
}
}
break;
case code_Hash:
if (isBOF && state === State.Default && nextCh === code_Bang) {
state = State.StartShebangComment;
}
break;
case code_Bang:
if (state === State.StartShebangComment) {
state = State.ShebangComment;
}
break;
case code_SingleQuote:
if (state === State.Default) {
state = State.SingleQuoteString;
}
else if (state === State.SingleQuoteStringEscapeQuote) {
nextStateId = State.SingleQuoteString;
}
else if (state === State.SingleQuoteString) {
nextStateId = State.Default;
}
break;
case code_DoubleQuote:
if (state === State.Default) {
state = State.DoubleQuoteString;
}
else if (state === State.DoubleQuoteStringEscapeQuote) {
nextStateId = State.DoubleQuoteString;
}
else if (state === State.DoubleQuoteString) {
nextStateId = State.Default;
}
break;
case code_Backtick:
if (state === State.Default) {
state = State.TemplateString;
}
else if (state === State.TemplateStringEscapeQuote) {
nextStateId = State.TemplateString;
}
else if (state === State.TemplateString) {
nextStateId = State.Default;
}
break;
case code_Backslash:
if (state === State.SingleQuoteString) {
if (nextCh === code_SingleQuote) {
state = State.SingleQuoteStringEscapeQuote;
}
else if (nextCh === code_Backslash) {
state = State.SingleQuoteStringEscapeBackslash;
}
}
else if (state === State.DoubleQuoteString) {
if (nextCh === code_DoubleQuote) {
state = State.DoubleQuoteStringEscapeQuote;
}
else if (nextCh === code_Backslash) {
state = State.DoubleQuoteStringEscapeBackslash;
}
}
else if (state === State.TemplateString) {
if (nextCh === code_Backtick) {
state = State.TemplateStringEscapeQuote;
}
else if (nextCh === code_Backslash) {
state = State.TemplateStringEscapeBackslash;
}
}
else if (state === State.Regex) {
if (nextCh === code_OpenBracket) {
state = State.RegexEscapeOpenBracket;
}
else if (nextCh === code_Slash) {
state = State.RegexEscapeSlash;
}
else if (nextCh === code_Backslash) {
state = State.RegexEscapeBackslash;
}
}
else if (state === State.CharClass) {
if (nextCh === code_CloseBracket) {
state = State.CharClassEscapeCloseBracket;
}
else if (nextCh === code_Backslash) {
state = State.CharClassEscapeBackslash;
}
}
else if (state === State.SingleQuoteStringEscapeBackslash) {
nextStateId = State.SingleQuoteString;
}
else if (state === State.DoubleQuoteStringEscapeBackslash) {
nextStateId = State.DoubleQuoteString;
}
else if (state === State.TemplateStringEscapeBackslash) {
nextStateId = State.TemplateString;
}
else if (state === State.RegexEscapeBackslash) {
nextStateId = State.Regex;
}
else if (state === State.CharClassEscapeBackslash) {
nextStateId = State.CharClass;
}
break;
case code_Dollar:
if (state === State.TemplateString && nextCh === code_OpenBrace) {
state = State.StartExpressionHole;
}
break;
case code_OpenBrace:
if (state === State.Default) {
braceDepth++;
}
else if (state === State.StartExpressionHole) {
templateStringBraceDepthStack.push(braceDepth);
nextStateId = State.Default;
}
break;
case code_CloseBrace:
if (templateStringBraceDepthStack.length && braceDepth === templateStringBraceDepthStack[templateStringBraceDepthStack.length - 1]) {
templateStringBraceDepthStack.pop();
state = State.TemplateString;
}
else if (state === State.Default && braceDepth > 0) { // Error recovery
braceDepth--;
}
break;
case code_OpenBracket:
if (state === State.RegexEscapeOpenBracket) {
nextStateId = State.Regex;
}
else if (state === State.Regex) {
state = State.CharClass;
}
break;
case code_CloseBracket:
if (state === State.CharClassEscapeCloseBracket) {
nextStateId = State.CharClass;
}
else if (state === State.CharClass) {
nextStateId = State.Regex;
}
break;
}
let charKind: CharKind;
switch (state) {
case State.StartSingleLineComment:
case State.SingleLineComment:
case State.StartMultiLineComment:
case State.MultiLineComment:
case State.EndMultiLineComment:
case State.StartShebangComment:
case State.ShebangComment:
charKind = "comment";
break;
case State.SingleQuoteString:
case State.SingleQuoteStringEscapeBackslash:
case State.SingleQuoteStringEscapeQuote:
case State.DoubleQuoteString:
case State.DoubleQuoteStringEscapeBackslash:
case State.DoubleQuoteStringEscapeQuote:
case State.TemplateString:
case State.TemplateStringEscapeBackslash:
case State.TemplateStringEscapeQuote:
case State.StartExpressionHole:
charKind = "string";
break;
case State.Regex:
case State.RegexEscapeBackslash:
case State.RegexEscapeSlash:
case State.RegexEscapeOpenBracket:
case State.CharClass:
case State.CharClassEscapeBackslash:
case State.CharClassEscapeCloseBracket:
charKind = "regex";
break;
default:
const isWhitespace =
ch === code_Space ||
ch === code_Tab ||
ch === code_NewLine ||
ch === code_CarriageReturn ||
/^\s$/.test(String.fromCharCode(ch));
charKind = isWhitespace ? "whitespace" : "code";
break;
}
if (nextStateId !== State.Uninitialized) {
state = nextStateId;
}
isBOF = false;
return { charKind, wrapLine };
}
return { step };
} | 36.68661 | 149 | 0.492118 | 319 | 2 | 1 | 4 | 25 | 2 | 0 | 0 | 6 | 3 | 0 | 254.5 | 2,518 | 0.002383 | 0.009929 | 0.000794 | 0.001191 | 0 | 0 | 0.176471 | 0.210893 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
const code_CarriageReturn = "\r".charCodeAt(0);
const code_NewLine = "\n".charCodeAt(0);
const code_Space = " ".charCodeAt(0);
const code_Tab = "\t".charCodeAt(0);
const code_Slash = "/".charCodeAt(0);
const code_Backslash = "\\".charCodeAt(0);
const code_Star = "*".charCodeAt(0);
const code_Hash = "#".charCodeAt(0);
const code_Bang = "!".charCodeAt(0);
const code_SingleQuote = "'".charCodeAt(0);
const code_DoubleQuote = "\"".charCodeAt(0);
const code_OpenBrace = "{".charCodeAt(0);
const code_CloseBrace = "}".charCodeAt(0);
const code_OpenBracket = "[".charCodeAt(0);
const code_CloseBracket = "]".charCodeAt(0);
const code_Backtick = "`".charCodeAt(0);
const code_Dollar = "$".charCodeAt(0);
const enum State {
Uninitialized,
Default,
StartSingleLineComment,
SingleLineComment,
StartMultiLineComment,
MultiLineComment,
EndMultiLineComment,
StartShebangComment,
ShebangComment,
SingleQuoteString,
SingleQuoteStringEscapeBackslash,
SingleQuoteStringEscapeQuote,
DoubleQuoteString,
DoubleQuoteStringEscapeBackslash,
DoubleQuoteStringEscapeQuote,
TemplateString,
TemplateStringEscapeBackslash,
TemplateStringEscapeQuote,
StartExpressionHole,
Regex,
RegexEscapeBackslash,
RegexEscapeSlash,
RegexEscapeOpenBracket,
CharClass,
CharClassEscapeBackslash,
CharClassEscapeCloseBracket,
}
export type CharKind =
| "whitespace"
| "comment"
| "string"
| "regex"
| "code"
;
interface StepResult {
charKind;
wrapLine;
}
export interface StateMachine {
step(ch, nextCh);
}
export function create() {
let state = State.Default;
let braceDepth = 0;
let templateStringBraceDepthStack = [];
let isBOF = true;
/* Example usages of 'step' are shown below:
;
*/
function step(ch, nextCh) {
let nextStateId = State.Uninitialized;;
let wrapLine = false;
switch (ch) {
case code_CarriageReturn:
if (nextCh === code_NewLine) {
if (state === State.ShebangComment ||
state === State.SingleLineComment ||
// Cases below are for error recovery
state === State.SingleQuoteString ||
state === State.DoubleQuoteString ||
state === State.Regex ||
state === State.CharClass) {
state = State.Default;
}
break;
}
// Fall through
case code_NewLine:
wrapLine = true;
if (state === State.ShebangComment ||
state === State.SingleLineComment) {
state = State.Default;
}
else if (state === State.SingleQuoteString || // Error recovery
state === State.DoubleQuoteString) { // Error recovery
state = State.Default;
}
break;
case code_Slash:
if (state === State.Default) {
if (nextCh === code_Slash) {
state = State.StartSingleLineComment;
}
else if (nextCh === code_Star) {
// It seems like there might technically be a corner case where this is the beginning of an invalid regex
state = State.StartMultiLineComment;
}
else {
// TODO (https://github.com/microsoft/typescript-analyze-trace/issues/14): this is too aggressive - it will catch division
state = State.Regex;
}
}
else if (state === State.StartSingleLineComment) {
state = State.SingleLineComment;
}
else if (state === State.EndMultiLineComment) {
nextStateId = State.Default;
}
else if (state === State.Regex) {
nextStateId = State.Default;
}
else if (state === State.RegexEscapeSlash) {
nextStateId = State.Regex;
}
break;
case code_Star:
if (state === State.StartMultiLineComment) {
state = State.MultiLineComment;
}
else if (state === State.MultiLineComment) {
if (nextCh === code_Slash) {
state = State.EndMultiLineComment;
}
}
break;
case code_Hash:
if (isBOF && state === State.Default && nextCh === code_Bang) {
state = State.StartShebangComment;
}
break;
case code_Bang:
if (state === State.StartShebangComment) {
state = State.ShebangComment;
}
break;
case code_SingleQuote:
if (state === State.Default) {
state = State.SingleQuoteString;
}
else if (state === State.SingleQuoteStringEscapeQuote) {
nextStateId = State.SingleQuoteString;
}
else if (state === State.SingleQuoteString) {
nextStateId = State.Default;
}
break;
case code_DoubleQuote:
if (state === State.Default) {
state = State.DoubleQuoteString;
}
else if (state === State.DoubleQuoteStringEscapeQuote) {
nextStateId = State.DoubleQuoteString;
}
else if (state === State.DoubleQuoteString) {
nextStateId = State.Default;
}
break;
case code_Backtick:
if (state === State.Default) {
state = State.TemplateString;
}
else if (state === State.TemplateStringEscapeQuote) {
nextStateId = State.TemplateString;
}
else if (state === State.TemplateString) {
nextStateId = State.Default;
}
break;
case code_Backslash:
if (state === State.SingleQuoteString) {
if (nextCh === code_SingleQuote) {
state = State.SingleQuoteStringEscapeQuote;
}
else if (nextCh === code_Backslash) {
state = State.SingleQuoteStringEscapeBackslash;
}
}
else if (state === State.DoubleQuoteString) {
if (nextCh === code_DoubleQuote) {
state = State.DoubleQuoteStringEscapeQuote;
}
else if (nextCh === code_Backslash) {
state = State.DoubleQuoteStringEscapeBackslash;
}
}
else if (state === State.TemplateString) {
if (nextCh === code_Backtick) {
state = State.TemplateStringEscapeQuote;
}
else if (nextCh === code_Backslash) {
state = State.TemplateStringEscapeBackslash;
}
}
else if (state === State.Regex) {
if (nextCh === code_OpenBracket) {
state = State.RegexEscapeOpenBracket;
}
else if (nextCh === code_Slash) {
state = State.RegexEscapeSlash;
}
else if (nextCh === code_Backslash) {
state = State.RegexEscapeBackslash;
}
}
else if (state === State.CharClass) {
if (nextCh === code_CloseBracket) {
state = State.CharClassEscapeCloseBracket;
}
else if (nextCh === code_Backslash) {
state = State.CharClassEscapeBackslash;
}
}
else if (state === State.SingleQuoteStringEscapeBackslash) {
nextStateId = State.SingleQuoteString;
}
else if (state === State.DoubleQuoteStringEscapeBackslash) {
nextStateId = State.DoubleQuoteString;
}
else if (state === State.TemplateStringEscapeBackslash) {
nextStateId = State.TemplateString;
}
else if (state === State.RegexEscapeBackslash) {
nextStateId = State.Regex;
}
else if (state === State.CharClassEscapeBackslash) {
nextStateId = State.CharClass;
}
break;
case code_Dollar:
if (state === State.TemplateString && nextCh === code_OpenBrace) {
state = State.StartExpressionHole;
}
break;
case code_OpenBrace:
if (state === State.Default) {
braceDepth++;
}
else if (state === State.StartExpressionHole) {
templateStringBraceDepthStack.push(braceDepth);
nextStateId = State.Default;
}
break;
case code_CloseBrace:
if (templateStringBraceDepthStack.length && braceDepth === templateStringBraceDepthStack[templateStringBraceDepthStack.length - 1]) {
templateStringBraceDepthStack.pop();
state = State.TemplateString;
}
else if (state === State.Default && braceDepth > 0) { // Error recovery
braceDepth--;
}
break;
case code_OpenBracket:
if (state === State.RegexEscapeOpenBracket) {
nextStateId = State.Regex;
}
else if (state === State.Regex) {
state = State.CharClass;
}
break;
case code_CloseBracket:
if (state === State.CharClassEscapeCloseBracket) {
nextStateId = State.CharClass;
}
else if (state === State.CharClass) {
nextStateId = State.Regex;
}
break;
}
let charKind;
switch (state) {
case State.StartSingleLineComment:
case State.SingleLineComment:
case State.StartMultiLineComment:
case State.MultiLineComment:
case State.EndMultiLineComment:
case State.StartShebangComment:
case State.ShebangComment:
charKind = "comment";
break;
case State.SingleQuoteString:
case State.SingleQuoteStringEscapeBackslash:
case State.SingleQuoteStringEscapeQuote:
case State.DoubleQuoteString:
case State.DoubleQuoteStringEscapeBackslash:
case State.DoubleQuoteStringEscapeQuote:
case State.TemplateString:
case State.TemplateStringEscapeBackslash:
case State.TemplateStringEscapeQuote:
case State.StartExpressionHole:
charKind = "string";
break;
case State.Regex:
case State.RegexEscapeBackslash:
case State.RegexEscapeSlash:
case State.RegexEscapeOpenBracket:
case State.CharClass:
case State.CharClassEscapeBackslash:
case State.CharClassEscapeCloseBracket:
charKind = "regex";
break;
default:
const isWhitespace =
ch === code_Space ||
ch === code_Tab ||
ch === code_NewLine ||
ch === code_CarriageReturn ||
/^\s$/.test(String.fromCharCode(ch));
charKind = isWhitespace ? "whitespace" : "code";
break;
}
if (nextStateId !== State.Uninitialized) {
state = nextStateId;
}
isBOF = false;
return { charKind, wrapLine };
}
return { step };
} |
a7acf302c8c51ed44ae06e1538762319051b2eb2 | 3,730 | ts | TypeScript | source/common/annotations/create.ts | lindylearn/annotations | e771a4736b7434ff1392f8ad89fecb12ee6b11ea | [
"MIT"
] | 61 | 2022-03-17T17:44:44.000Z | 2022-03-31T11:40:45.000Z | source/common/annotations/create.ts | lindylearn/annotations | e771a4736b7434ff1392f8ad89fecb12ee6b11ea | [
"MIT"
] | 12 | 2022-03-18T16:11:16.000Z | 2022-03-31T14:19:54.000Z | source/common/annotations/create.ts | lindylearn/annotations | e771a4736b7434ff1392f8ad89fecb12ee6b11ea | [
"MIT"
] | 2 | 2022-03-18T11:27:25.000Z | 2022-03-27T20:50:38.000Z | export function createDraftAnnotation(
url: string,
selector: object,
reply_to: string = null
): LindyAnnotation {
return createAnnotation(url, selector, {
id: null,
localId: generateId(),
reply_to,
});
}
function createAnnotation(
url: string,
selector: object,
partial: Partial<LindyAnnotation> = {}
): LindyAnnotation {
return {
id: partial.id,
localId: partial.localId || partial.id,
url,
quote_text: selector?.[2]?.exact || "_",
text: partial.text || "",
author: partial.author || "",
quote_html_selector: selector,
platform: partial.platform || "ll",
link: partial.id,
reply_count: partial.reply_count || 0,
isMyAnnotation: true,
isPublic: false,
upvote_count: 0,
tags: partial.tags || [],
created_at: partial.created_at || new Date().toISOString(),
replies: [],
user_upvoted: false,
reply_to: partial.reply_to || null,
};
}
function generateId(): string {
return Math.random().toString(36).slice(-10);
}
export interface LindyAnnotation {
id: string;
author: 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;
reply_to?: string;
// local state
localId?: string; // immutable local annotation id (stays the same through remote synchronization)
url: string;
isMyAnnotation?: boolean;
displayOffset?: number;
displayOffsetEnd?: number;
hidden?: boolean;
focused?: boolean; // should only be set for one annotation
}
export function hypothesisToLindyFormat(
annotation: any,
currentUsername: string
): LindyAnnotation {
const author: string = annotation.user.match(/([^:]+)@/)[1];
return {
id: annotation.id,
url: annotation.uri,
localId: annotation.id, // base comparisons on immutable localId
author,
isMyAnnotation: author === currentUsername,
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] === "group:__world__",
reply_to: annotation.references?.[annotation.references.length - 1],
};
}
export interface PickledAnnotation {
url: string;
id: string;
created_at: string;
quote_text: string;
text: string;
tags: string[];
quote_html_selector: object;
}
// strip locally saved annotation from unneccessary state, to reduce used storage
export function pickleLocalAnnotation(
annotation: LindyAnnotation
): PickledAnnotation {
return {
url: annotation.url,
id: annotation.id,
created_at: annotation.created_at,
quote_text: annotation.quote_text,
text: annotation.text,
tags: annotation.tags,
quote_html_selector: annotation.quote_html_selector,
};
}
export function unpickleLocalAnnotation(
annotation: PickledAnnotation
): LindyAnnotation {
return createAnnotation(
annotation.url,
annotation.quote_html_selector,
annotation
);
}
| 27.62963 | 102 | 0.632708 | 123 | 7 | 0 | 11 | 1 | 29 | 2 | 1 | 35 | 2 | 0 | 9.142857 | 950 | 0.018947 | 0.001053 | 0.030526 | 0.002105 | 0 | 0.020833 | 0.729167 | 0.220452 | export function createDraftAnnotation(
url,
selector,
reply_to = null
) {
return createAnnotation(url, selector, {
id: null,
localId: generateId(),
reply_to,
});
}
/* Example usages of 'createAnnotation' are shown below:
createAnnotation(url, selector, {
id: null,
localId: generateId(),
reply_to,
});
createAnnotation(annotation.url, annotation.quote_html_selector, annotation);
*/
function createAnnotation(
url,
selector,
partial = {}
) {
return {
id: partial.id,
localId: partial.localId || partial.id,
url,
quote_text: selector?.[2]?.exact || "_",
text: partial.text || "",
author: partial.author || "",
quote_html_selector: selector,
platform: partial.platform || "ll",
link: partial.id,
reply_count: partial.reply_count || 0,
isMyAnnotation: true,
isPublic: false,
upvote_count: 0,
tags: partial.tags || [],
created_at: partial.created_at || new Date().toISOString(),
replies: [],
user_upvoted: false,
reply_to: partial.reply_to || null,
};
}
/* Example usages of 'generateId' are shown below:
generateId();
*/
function generateId() {
return Math.random().toString(36).slice(-10);
}
export interface LindyAnnotation {
id;
author;
platform;
link;
created_at;
reply_count;
quote_text;
text;
replies;
upvote_count;
tags;
quote_html_selector;
user_upvoted;
isPublic;
reply_to?;
// local state
localId?; // immutable local annotation id (stays the same through remote synchronization)
url;
isMyAnnotation?;
displayOffset?;
displayOffsetEnd?;
hidden?;
focused?; // should only be set for one annotation
}
export function hypothesisToLindyFormat(
annotation,
currentUsername
) {
const author = annotation.user.match(/([^:]+)@/)[1];
return {
id: annotation.id,
url: annotation.uri,
localId: annotation.id, // base comparisons on immutable localId
author,
isMyAnnotation: author === currentUsername,
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] === "group:__world__",
reply_to: annotation.references?.[annotation.references.length - 1],
};
}
export interface PickledAnnotation {
url;
id;
created_at;
quote_text;
text;
tags;
quote_html_selector;
}
// strip locally saved annotation from unneccessary state, to reduce used storage
export function pickleLocalAnnotation(
annotation
) {
return {
url: annotation.url,
id: annotation.id,
created_at: annotation.created_at,
quote_text: annotation.quote_text,
text: annotation.text,
tags: annotation.tags,
quote_html_selector: annotation.quote_html_selector,
};
}
export function unpickleLocalAnnotation(
annotation
) {
return createAnnotation(
annotation.url,
annotation.quote_html_selector,
annotation
);
}
|
a7af438782d65ffe7be7dcc76b971fb844c396c2 | 1,794 | ts | TypeScript | src/helper/base64-arraybuffer.conversion.ts | lovetodream/mapkit-api | fd6261042b81c29c379e4dbc5aef9f457a1e9dce | [
"MIT"
] | null | null | null | src/helper/base64-arraybuffer.conversion.ts | lovetodream/mapkit-api | fd6261042b81c29c379e4dbc5aef9f457a1e9dce | [
"MIT"
] | 2 | 2022-02-23T20:55:50.000Z | 2022-02-24T22:29:31.000Z | src/helper/base64-arraybuffer.conversion.ts | lovetodream/mapkit-api | fd6261042b81c29c379e4dbc5aef9f457a1e9dce | [
"MIT"
] | null | null | null | const chars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// Use a lookup table to find the index.
const lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
for (let i = 0; i < chars.length; i++) {
lookup[chars.charCodeAt(i)] = i;
}
export const encode = (arraybuffer: ArrayBuffer): string => {
const bytes = new Uint8Array(arraybuffer);
const len = bytes.length;
let base64 = '';
for (let i = 0; i < len; i += 3) {
base64 += chars[bytes[i] >> 2];
base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64 += chars[bytes[i + 2] & 63];
}
if (len % 3 === 2) {
base64 = base64.substring(0, base64.length - 1) + '=';
} else if (len % 3 === 1) {
base64 = base64.substring(0, base64.length - 2) + '==';
}
return base64;
};
export const decode = (base64: string): ArrayBuffer => {
let bufferLength = base64.length * 0.75;
const len = base64.length;
let p = 0;
let encoded1: number;
let encoded2: number;
let encoded3: number;
let encoded4: number;
if (base64[base64.length - 1] === '=') {
bufferLength--;
if (base64[base64.length - 2] === '=') {
bufferLength--;
}
}
const arraybuffer = new ArrayBuffer(bufferLength),
bytes = new Uint8Array(arraybuffer);
for (let i = 0; i < len; i += 4) {
encoded1 = lookup[base64.charCodeAt(i)];
encoded2 = lookup[base64.charCodeAt(i + 1)];
encoded3 = lookup[base64.charCodeAt(i + 2)];
encoded4 = lookup[base64.charCodeAt(i + 3)];
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return arraybuffer;
};
| 28.47619 | 76 | 0.583055 | 50 | 2 | 0 | 2 | 19 | 0 | 0 | 0 | 6 | 0 | 1 | 20 | 659 | 0.00607 | 0.028832 | 0 | 0 | 0.001517 | 0 | 0.26087 | 0.277934 | const chars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// Use a lookup table to find the index.
const lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
for (let i = 0; i < chars.length; i++) {
lookup[chars.charCodeAt(i)] = i;
}
export const encode = (arraybuffer) => {
const bytes = new Uint8Array(arraybuffer);
const len = bytes.length;
let base64 = '';
for (let i = 0; i < len; i += 3) {
base64 += chars[bytes[i] >> 2];
base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64 += chars[bytes[i + 2] & 63];
}
if (len % 3 === 2) {
base64 = base64.substring(0, base64.length - 1) + '=';
} else if (len % 3 === 1) {
base64 = base64.substring(0, base64.length - 2) + '==';
}
return base64;
};
export const decode = (base64) => {
let bufferLength = base64.length * 0.75;
const len = base64.length;
let p = 0;
let encoded1;
let encoded2;
let encoded3;
let encoded4;
if (base64[base64.length - 1] === '=') {
bufferLength--;
if (base64[base64.length - 2] === '=') {
bufferLength--;
}
}
const arraybuffer = new ArrayBuffer(bufferLength),
bytes = new Uint8Array(arraybuffer);
for (let i = 0; i < len; i += 4) {
encoded1 = lookup[base64.charCodeAt(i)];
encoded2 = lookup[base64.charCodeAt(i + 1)];
encoded3 = lookup[base64.charCodeAt(i + 2)];
encoded4 = lookup[base64.charCodeAt(i + 3)];
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return arraybuffer;
};
|
a7d2370ab8654f6a4ae33e2acb3c198102b400d1 | 2,057 | ts | TypeScript | src/utils/verification.ts | codeluosiyu/toa-utils | 4a88a32b9a5a642ec402f7540941da39661bc604 | [
"MIT"
] | 35 | 2022-03-12T16:28:38.000Z | 2022-03-24T12:02:50.000Z | src/utils/verification.ts | codeluosiyu/toa-tools | d09a0db2a34fc9352251cdac768d89980541695b | [
"MIT"
] | null | null | null | src/utils/verification.ts | codeluosiyu/toa-tools | d09a0db2a34fc9352251cdac768d89980541695b | [
"MIT"
] | null | null | null | /**
* 过滤表情
* @param name
* @returns
*/
export const filterEmoji = (name) => {
const str = name.replace(
/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi,
""
);
return str;
};
/**
* 过滤税号
* @param num
* @returns
*/
export const isNumber = (num: string) =>
/^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/.test(num);
/**
* 验证手机号
* @param phone
* @returns
*/
export const isPhone = (phone: any) => /^[1][0-9]{10}$/.test(phone);
/**
* 验证邮箱
* @param email
* @returns
*/
export const isEmail = (email: string) =>
/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(
email
);
/**
* 验证是否存在特殊符号或者表情
* @param value
* @param tips
* @returns
*/
export const hasEmoji = function (value: string, tips = "") {
let char =
/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi;
if (char.test(value)) {
return true;
}
return false;
};
/**
* 获取数组索引值
* @param param0
* @returns
*/
export const getIndexArr = function ({
id = "",
productTree = [],
idKey = "id",
childrenKey = "child",
}: {
id: string;
productTree?: Array<any>;
idKey?: string;
childrenKey?: string;
}) {
let indexArr: number[] = [];
let fn: (arr: Array<any>) => boolean = (arr) =>
arr.some((elem: any, index) => {
if (elem[idKey] == id) {
indexArr.push(index);
return true;
} else if (
elem[childrenKey] &&
elem[childrenKey] instanceof Array &&
elem[childrenKey].length
) {
return fn(elem[childrenKey]) && indexArr.push(index);
}
return false;
});
fn(productTree);
indexArr.reverse();
return indexArr;
};
| 23.11236 | 241 | 0.561983 | 52 | 8 | 0 | 10 | 10 | 0 | 1 | 4 | 8 | 0 | 1 | 7.25 | 933 | 0.019293 | 0.010718 | 0 | 0 | 0.001072 | 0.142857 | 0.285714 | 0.247651 | /**
* 过滤表情
* @param name
* @returns
*/
export const filterEmoji = (name) => {
const str = name.replace(
/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi,
""
);
return str;
};
/**
* 过滤税号
* @param num
* @returns
*/
export const isNumber = (num) =>
/^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/.test(num);
/**
* 验证手机号
* @param phone
* @returns
*/
export const isPhone = (phone) => /^[1][0-9]{10}$/.test(phone);
/**
* 验证邮箱
* @param email
* @returns
*/
export const isEmail = (email) =>
/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(
email
);
/**
* 验证是否存在特殊符号或者表情
* @param value
* @param tips
* @returns
*/
export const hasEmoji = function (value, tips = "") {
let char =
/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/gi;
if (char.test(value)) {
return true;
}
return false;
};
/**
* 获取数组索引值
* @param param0
* @returns
*/
export const getIndexArr = function ({
id = "",
productTree = [],
idKey = "id",
childrenKey = "child",
}) {
let indexArr = [];
/* Example usages of 'fn' are shown below:
fn(elem[childrenKey]) && indexArr.push(index);
fn(productTree);
*/
let fn = (arr) =>
arr.some((elem, index) => {
if (elem[idKey] == id) {
indexArr.push(index);
return true;
} else if (
elem[childrenKey] &&
elem[childrenKey] instanceof Array &&
elem[childrenKey].length
) {
return fn(elem[childrenKey]) && indexArr.push(index);
}
return false;
});
fn(productTree);
indexArr.reverse();
return indexArr;
};
|
a7f6bdfb0812b0fd5630ebe7aa78ac3103b96c5b | 1,201 | ts | TypeScript | combinations/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | 1 | 2022-03-30T11:10:14.000Z | 2022-03-30T11:10:14.000Z | combinations/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | null | null | null | combinations/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | null | null | null | function combine(n: number, k: number): number[][] {
if (k > n) {
return [];
}
if (k === n) {
return [
Array(n)
.fill(0)
.map((_v, i) => i + 1),
];
}
if (n === 4 && k === 2) {
return [
[1, 2],
[1, 3],
[1, 4],
[2, 3],
[2, 4],
[3, 4],
];
}
if (n === 1 && k === 1) {
return [[1]];
}
const nums = Array(n)
.fill(0)
.map((_v, i) => i + 1);
const ans: number[][] = [];
dfs(0, n - 1, k, [], (indexs: number[]) => {
ans.push(indexs.map((v) => nums[v]));
});
return ans;
}
const dfs = (
cur: number,
n: number,
k: number,
temp: number[],
output: (nums: number[]) => void,
) => {
if (temp.length > k) {
return;
}
if (cur > n + 1) {
return;
}
// 记录合法的答案
if (temp.length == k) {
output(temp);
return;
}
// 考虑不选择当前位置
dfs(cur + 1, n, k, temp, output);
// 考虑选择当前位置
if (temp.length + 1 <= k) {
dfs(cur + 1, n, k, [...temp, cur], output);
}
};
export default combine;
| 19.370968 | 52 | 0.353039 | 56 | 6 | 0 | 13 | 3 | 0 | 1 | 0 | 11 | 0 | 0 | 8.166667 | 412 | 0.046117 | 0.007282 | 0 | 0 | 0 | 0 | 0.5 | 0.301377 | /* Example usages of 'combine' are shown below:
;
*/
function combine(n, k) {
if (k > n) {
return [];
}
if (k === n) {
return [
Array(n)
.fill(0)
.map((_v, i) => i + 1),
];
}
if (n === 4 && k === 2) {
return [
[1, 2],
[1, 3],
[1, 4],
[2, 3],
[2, 4],
[3, 4],
];
}
if (n === 1 && k === 1) {
return [[1]];
}
const nums = Array(n)
.fill(0)
.map((_v, i) => i + 1);
const ans = [];
dfs(0, n - 1, k, [], (indexs) => {
ans.push(indexs.map((v) => nums[v]));
});
return ans;
}
/* Example usages of 'dfs' are shown below:
dfs(0, n - 1, k, [], (indexs) => {
ans.push(indexs.map((v) => nums[v]));
});
// 考虑不选择当前位置
dfs(cur + 1, n, k, temp, output);
dfs(cur + 1, n, k, [...temp, cur], output);
*/
const dfs = (
cur,
n,
k,
temp,
output,
) => {
if (temp.length > k) {
return;
}
if (cur > n + 1) {
return;
}
// 记录合法的答案
if (temp.length == k) {
output(temp);
return;
}
// 考虑不选择当前位置
dfs(cur + 1, n, k, temp, output);
// 考虑选择当前位置
if (temp.length + 1 <= k) {
dfs(cur + 1, n, k, [...temp, cur], output);
}
};
export default combine;
|
49e1039c39ffc02e4d364e89e535ef87b31206f2 | 2,114 | ts | TypeScript | template/src/utils/Type/TypeUtils.ts | yigityuce/cra-template-react-spa-quick-start | 6b131fe288a502c1ff7b01daedb772093526d9da | [
"MIT"
] | 1 | 2022-03-24T13:56:00.000Z | 2022-03-24T13:56:00.000Z | template/src/utils/Type/TypeUtils.ts | yigityuce/cra-template-react-spa-quick-start | 6b131fe288a502c1ff7b01daedb772093526d9da | [
"MIT"
] | null | null | null | template/src/utils/Type/TypeUtils.ts | yigityuce/cra-template-react-spa-quick-start | 6b131fe288a502c1ff7b01daedb772093526d9da | [
"MIT"
] | null | null | null | export class TypeUtils {
public static isDefined(input: unknown): boolean {
return input !== undefined && input !== null;
}
public static hasValue(input: unknown): boolean {
if (!TypeUtils.isDefined(input)) {
return false;
}
if (Array.isArray(input)) {
return input.length !== 0;
}
if (typeof input === 'object') {
return !!input && Object.keys(input).length > 0;
}
if (typeof input === 'string') {
return !!input.trim();
}
return true;
}
public static isString(input: unknown): boolean {
return TypeUtils.isDefined(input) && typeof input === 'string';
}
public static isPositiveFloat(input: unknown): boolean {
return (
(TypeUtils.isDefined(input) && typeof input === 'number' && !isNaN(input) && input >= 0) ||
(TypeUtils.isDefined(input) &&
typeof input === 'string' &&
!isNaN(parseFloat(input)) &&
parseFloat(input) >= 0 &&
/[0-9]*\.?[0-9]+/.test(input))
);
}
public static isFloat(input: unknown): boolean {
return (
(TypeUtils.isDefined(input) && typeof input === 'number' && !isNaN(input)) ||
(TypeUtils.isDefined(input) &&
typeof input === 'string' &&
!isNaN(parseFloat(input)) &&
parseFloat(input) >= 0 &&
/[0-9]*\.?[0-9]+/.test(input))
);
}
public static isPositiveNumber(input: unknown): boolean {
return (
(TypeUtils.isDefined(input) && typeof input === 'number' && !isNaN(input) && input >= 0) ||
(TypeUtils.isDefined(input) &&
typeof input === 'string' &&
!isNaN(parseInt(input, 10)) &&
parseInt(input, 10) >= 0 &&
/[0-9]+$/.test(input))
);
}
public static isNumber(input: unknown): boolean {
return (
(TypeUtils.isDefined(input) && typeof input === 'number' && !isNaN(input)) ||
(TypeUtils.isDefined(input) && typeof input === 'string' && !isNaN(parseInt(input, 10)) && /[0-9]+$/.test(input))
);
}
public static isDate(input: unknown): boolean {
return TypeUtils.isDefined(input) && Object.prototype.toString.call(input) === '[object Date]' && !isNaN((input as Date).getTime());
}
}
| 30.2 | 135 | 0.593661 | 62 | 8 | 0 | 8 | 0 | 0 | 1 | 0 | 16 | 1 | 12 | 5.5 | 646 | 0.024768 | 0 | 0 | 0.001548 | 0.018576 | 0 | 1 | 0.226648 | export class TypeUtils {
public static isDefined(input) {
return input !== undefined && input !== null;
}
public static hasValue(input) {
if (!TypeUtils.isDefined(input)) {
return false;
}
if (Array.isArray(input)) {
return input.length !== 0;
}
if (typeof input === 'object') {
return !!input && Object.keys(input).length > 0;
}
if (typeof input === 'string') {
return !!input.trim();
}
return true;
}
public static isString(input) {
return TypeUtils.isDefined(input) && typeof input === 'string';
}
public static isPositiveFloat(input) {
return (
(TypeUtils.isDefined(input) && typeof input === 'number' && !isNaN(input) && input >= 0) ||
(TypeUtils.isDefined(input) &&
typeof input === 'string' &&
!isNaN(parseFloat(input)) &&
parseFloat(input) >= 0 &&
/[0-9]*\.?[0-9]+/.test(input))
);
}
public static isFloat(input) {
return (
(TypeUtils.isDefined(input) && typeof input === 'number' && !isNaN(input)) ||
(TypeUtils.isDefined(input) &&
typeof input === 'string' &&
!isNaN(parseFloat(input)) &&
parseFloat(input) >= 0 &&
/[0-9]*\.?[0-9]+/.test(input))
);
}
public static isPositiveNumber(input) {
return (
(TypeUtils.isDefined(input) && typeof input === 'number' && !isNaN(input) && input >= 0) ||
(TypeUtils.isDefined(input) &&
typeof input === 'string' &&
!isNaN(parseInt(input, 10)) &&
parseInt(input, 10) >= 0 &&
/[0-9]+$/.test(input))
);
}
public static isNumber(input) {
return (
(TypeUtils.isDefined(input) && typeof input === 'number' && !isNaN(input)) ||
(TypeUtils.isDefined(input) && typeof input === 'string' && !isNaN(parseInt(input, 10)) && /[0-9]+$/.test(input))
);
}
public static isDate(input) {
return TypeUtils.isDefined(input) && Object.prototype.toString.call(input) === '[object Date]' && !isNaN((input as Date).getTime());
}
}
|
49e304be6fed5652977970ac39a5e313fbbb21b3 | 1,845 | ts | TypeScript | src/tools/interpolate.ts | PixiColorEffects/pixi-color-effects | 2b26149b870fa826d6358b899b49be0f8d04d90a | [
"MIT"
] | 84 | 2022-03-03T05:42:35.000Z | 2022-03-21T12:36:25.000Z | src/tools/interpolate.ts | PixiColorEffects/pixi-color-effects | 2b26149b870fa826d6358b899b49be0f8d04d90a | [
"MIT"
] | 1 | 2022-03-01T09:22:58.000Z | 2022-03-02T13:32:54.000Z | src/tools/interpolate.ts | PixiColorEffects/pixi-color-effects | 2b26149b870fa826d6358b899b49be0f8d04d90a | [
"MIT"
] | 7 | 2022-03-04T07:04:42.000Z | 2022-03-22T03:57:22.000Z | // @ts-nocheck
export class interpolate {
constructor(e, t) {
var s, i, n, a, r, o, h, c, l, d, u, p, g;
if (null != e && null != t) {
for (
c = e.length - 1,
a = [],
u = [],
h = [],
d = [],
p = [],
i = [],
s = [],
n = [],
o = [],
l = [],
r = 0;
0 <= c ? r < c : r > c;
0 <= c ? (r += 1) : (r -= 1)
)
(a[r] = e[r + 1] - e[r]),
(o[r] = t[r + 1] - t[r]),
(l[r] = o[r] / a[r]);
for (r = 1; 1 <= c ? r < c : r > c; 1 <= c ? (r += 1) : (r -= 1))
u[r] =
(3 / a[r]) * (t[r + 1] - t[r]) - (3 / a[r - 1]) * (t[r] - t[r - 1]);
for (
h[0] = 1, d[0] = 0, p[0] = 0, r = 1;
1 <= c ? r < c : r > c;
1 <= c ? (r += 1) : (r -= 1)
)
(h[r] = 2 * (e[r + 1] - e[r - 1]) - a[r - 1] * d[r - 1]),
(d[r] = a[r] / h[r]),
(p[r] = (u[r] - a[r - 1] * p[r - 1]) / h[r]);
for (
h[c] = 1, p[c] = 0, i[c] = 0, r = g = c - 1;
g <= 0 ? r <= 0 : r >= 0;
g <= 0 ? (r += 1) : (r -= 1)
)
(i[r] = p[r] - d[r] * i[r + 1]),
(s[r] =
(t[r + 1] - t[r]) / a[r] - (a[r] * (i[r + 1] + 2 * i[r])) / 3),
(n[r] = (i[r + 1] - i[r]) / (3 * a[r]));
(this.x = e.slice(0, c + 1)),
(this.a = t.slice(0, c)),
(this.b = s),
(this.c = i.slice(0, c)),
(this.d = n);
}
}
interpolate(e) {
var t, s, i;
for (
s = i = this.x.length - 1;
(i <= 0 ? s <= 0 : s >= 0) && !(this.x[s] <= e);
i <= 0 ? (s += 1) : (s -= 1)
);
return (
(t = e - this.x[s]),
this.a[s] +
this.b[s] * t +
this.c[s] * Math.pow(t, 2) +
this.d[s] * Math.pow(t, 3)
);
}
}
| 27.132353 | 78 | 0.244444 | 66 | 2 | 0 | 3 | 16 | 0 | 0 | 0 | 0 | 1 | 0 | 30 | 854 | 0.005855 | 0.018735 | 0 | 0.001171 | 0 | 0 | 0 | 0.246936 | // @ts-nocheck
export class interpolate {
constructor(e, t) {
var s, i, n, a, r, o, h, c, l, d, u, p, g;
if (null != e && null != t) {
for (
c = e.length - 1,
a = [],
u = [],
h = [],
d = [],
p = [],
i = [],
s = [],
n = [],
o = [],
l = [],
r = 0;
0 <= c ? r < c : r > c;
0 <= c ? (r += 1) : (r -= 1)
)
(a[r] = e[r + 1] - e[r]),
(o[r] = t[r + 1] - t[r]),
(l[r] = o[r] / a[r]);
for (r = 1; 1 <= c ? r < c : r > c; 1 <= c ? (r += 1) : (r -= 1))
u[r] =
(3 / a[r]) * (t[r + 1] - t[r]) - (3 / a[r - 1]) * (t[r] - t[r - 1]);
for (
h[0] = 1, d[0] = 0, p[0] = 0, r = 1;
1 <= c ? r < c : r > c;
1 <= c ? (r += 1) : (r -= 1)
)
(h[r] = 2 * (e[r + 1] - e[r - 1]) - a[r - 1] * d[r - 1]),
(d[r] = a[r] / h[r]),
(p[r] = (u[r] - a[r - 1] * p[r - 1]) / h[r]);
for (
h[c] = 1, p[c] = 0, i[c] = 0, r = g = c - 1;
g <= 0 ? r <= 0 : r >= 0;
g <= 0 ? (r += 1) : (r -= 1)
)
(i[r] = p[r] - d[r] * i[r + 1]),
(s[r] =
(t[r + 1] - t[r]) / a[r] - (a[r] * (i[r + 1] + 2 * i[r])) / 3),
(n[r] = (i[r + 1] - i[r]) / (3 * a[r]));
(this.x = e.slice(0, c + 1)),
(this.a = t.slice(0, c)),
(this.b = s),
(this.c = i.slice(0, c)),
(this.d = n);
}
}
interpolate(e) {
var t, s, i;
for (
s = i = this.x.length - 1;
(i <= 0 ? s <= 0 : s >= 0) && !(this.x[s] <= e);
i <= 0 ? (s += 1) : (s -= 1)
);
return (
(t = e - this.x[s]),
this.a[s] +
this.b[s] * t +
this.c[s] * Math.pow(t, 2) +
this.d[s] * Math.pow(t, 3)
);
}
}
|
b2ef27341c97dd1594cccdc87c0678eb366f1464 | 2,897 | ts | TypeScript | src/Queue.ts | duan602728596/Q | 4bfa42c5f759dc3a8ebce287fd9467d5bb30880b | [
"MIT"
] | null | null | null | src/Queue.ts | duan602728596/Q | 4bfa42c5f759dc3a8ebce287fd9467d5bb30880b | [
"MIT"
] | null | null | null | src/Queue.ts | duan602728596/Q | 4bfa42c5f759dc3a8ebce287fd9467d5bb30880b | [
"MIT"
] | 1 | 2022-02-08T09:29:49.000Z | 2022-02-08T09:29:49.000Z | /**
* Queue is a queue function, it can limit the number of simultaneous execution methods.
* For example, when uploading multiple files at the same time,
* using the queue function can limit uploading up to 3 files each time,
* When one file is uploaded, upload the next file.
*
* Queue是一个队列函数,它可以限制同时执行方法的数量。
* 比如同时上传多个文件,使用队列函数可以限制每次最多上传3个文件,
* 当一个文件上传完毕后,接着上传下一个文件。
*/
/**
* example:
*
* function task() { / * do something * / }
*
* const queue = new Queue({ workerLen: 3 });
*
* queue.use(
* [task, undefined, 1],
* [task, undefined, 2],
* [task, undefined, 3],
* // ...
* );
* queue.run();
*
* queue.use([task, undefined, 4]);
* queue.use([task, undefined, 5]);
* queue.run();
*/
interface QueueConfig {
workerLen?: number;
}
interface TaskFunc {
(...args: any[]): any;
}
type Task = [taskFunc: TaskFunc, self?: any, ...args: any[]];
class Queue {
public workerLen: number; // Number of tasks executed simultaneously 同时执行的任务数量
public waitingTasks: Array<Task>; // Queue of tasks waiting to be executed 等待执行的任务队列
public workerTasks: Array<Generator | undefined>; // Task in progress 正在执行的任务
constructor(config?: QueueConfig) {
this.workerLen = config?.workerLen ?? 3;
this.waitingTasks = [];
this.workerTasks = new Array<Generator | undefined>(this.workerLen);
}
/**
* Add to the queue of tasks waiting to be executed
* 添加到等待执行的任务队列
* @param { Array<Task> } tasks
*/
use(...tasks: Array<Task>): void {
for (const task of tasks) {
this.waitingTasks.unshift(task);
}
}
/**
* Perform a task
* 执行一个任务
* @param { number } index
* @param { Task } task
*/
*executionTask(index: number, task: Task): Generator {
const [taskFunc, self, ...args]: Task = task;
yield ((): any => {
const callback: Function = (): void => {
this.workerTasks[index] = undefined;
this.run();
};
let callFunc: any;
try {
callFunc = taskFunc.call(self, ...args);
} finally {
// After the task is executed, assign the task again and execute the task
// 任务执行完毕后,再次分配任务并执行任务
if (typeof callFunc?.finally === 'function') {
callFunc.finally(callback);
} else {
callback();
}
}
})();
}
/**
* Assign and execute tasks
* 分配并执行任务
*/
run(): void {
const runIndex: Array<number> = [];
for (let i: number = 0; i < this.workerLen; i++) {
const len: number = this.waitingTasks.length;
if (!this.workerTasks[i] && len > 0) {
this.workerTasks[i] = this.executionTask(i, this.waitingTasks[len - 1]);
runIndex.push(i);
this.waitingTasks.pop(); // Delete tasks from the task queue 从任务队列内删除任务
}
}
for (const index of runIndex) {
this.workerTasks[index]?.next?.();
}
}
}
export default Queue; | 24.550847 | 88 | 0.599241 | 56 | 6 | 0 | 4 | 6 | 4 | 3 | 7 | 9 | 4 | 1 | 8.5 | 868 | 0.011521 | 0.006912 | 0.004608 | 0.004608 | 0.001152 | 0.35 | 0.45 | 0.221459 | /**
* Queue is a queue function, it can limit the number of simultaneous execution methods.
* For example, when uploading multiple files at the same time,
* using the queue function can limit uploading up to 3 files each time,
* When one file is uploaded, upload the next file.
*
* Queue是一个队列函数,它可以限制同时执行方法的数量。
* 比如同时上传多个文件,使用队列函数可以限制每次最多上传3个文件,
* 当一个文件上传完毕后,接着上传下一个文件。
*/
/**
* example:
*
* function task() { / * do something * / }
*
* const queue = new Queue({ workerLen: 3 });
*
* queue.use(
* [task, undefined, 1],
* [task, undefined, 2],
* [task, undefined, 3],
* // ...
* );
* queue.run();
*
* queue.use([task, undefined, 4]);
* queue.use([task, undefined, 5]);
* queue.run();
*/
interface QueueConfig {
workerLen?;
}
interface TaskFunc {
(...args);
}
type Task = [taskFunc, self?, ...args];
class Queue {
public workerLen; // Number of tasks executed simultaneously 同时执行的任务数量
public waitingTasks; // Queue of tasks waiting to be executed 等待执行的任务队列
public workerTasks; // Task in progress 正在执行的任务
constructor(config?) {
this.workerLen = config?.workerLen ?? 3;
this.waitingTasks = [];
this.workerTasks = new Array<Generator | undefined>(this.workerLen);
}
/**
* Add to the queue of tasks waiting to be executed
* 添加到等待执行的任务队列
* @param { Array<Task> } tasks
*/
use(...tasks) {
for (const task of tasks) {
this.waitingTasks.unshift(task);
}
}
/**
* Perform a task
* 执行一个任务
* @param { number } index
* @param { Task } task
*/
*executionTask(index, task) {
const [taskFunc, self, ...args] = task;
yield (() => {
/* Example usages of 'callback' are shown below:
callFunc.finally(callback);
callback();
*/
const callback = () => {
this.workerTasks[index] = undefined;
this.run();
};
let callFunc;
try {
callFunc = taskFunc.call(self, ...args);
} finally {
// After the task is executed, assign the task again and execute the task
// 任务执行完毕后,再次分配任务并执行任务
if (typeof callFunc?.finally === 'function') {
callFunc.finally(callback);
} else {
callback();
}
}
})();
}
/**
* Assign and execute tasks
* 分配并执行任务
*/
run() {
const runIndex = [];
for (let i = 0; i < this.workerLen; i++) {
const len = this.waitingTasks.length;
if (!this.workerTasks[i] && len > 0) {
this.workerTasks[i] = this.executionTask(i, this.waitingTasks[len - 1]);
runIndex.push(i);
this.waitingTasks.pop(); // Delete tasks from the task queue 从任务队列内删除任务
}
}
for (const index of runIndex) {
this.workerTasks[index]?.next?.();
}
}
}
export default Queue; |
4044219caba3537d2ee9d01ed96ab520accebf35 | 2,215 | tsx | TypeScript | src/Utils.tsx | hkgnp/logseq-chartrender-plugin | 9d98621905d21a8fb70f3fde1793eb70f89dbf2d | [
"MIT"
] | 18 | 2022-01-03T03:17:12.000Z | 2022-03-15T13:57:01.000Z | src/Utils.tsx | hkgnp/logseq-chartrender-plugin | 9d98621905d21a8fb70f3fde1793eb70f89dbf2d | [
"MIT"
] | 4 | 2022-01-06T04:27:59.000Z | 2022-03-03T03:57:25.000Z | src/Utils.tsx | hkgnp/logseq-chartrender-plugin | 9d98621905d21a8fb70f3fde1793eb70f89dbf2d | [
"MIT"
] | 2 | 2022-01-06T06:06:00.000Z | 2022-01-14T13:57:43.000Z | export const createChart = (chartData: any[], chartOptions: string) => {
let [chartType, colour, height] = chartOptions.split(' ');
const chartHeight = parseFloat(height);
const chartWidth = chartHeight * 1.78;
const xAxisLabel = chartData[0].content;
const yAxisLabel = chartData[1].content;
let chartObj: any;
if (chartType === 'percentbar') {
chartObj = chartData[0].children.map(
(val1: { content: string }, index: number) => ({
name: val1.content,
valueZero: (
(parseFloat(chartData[1].children[index].content.split(',')[0]) /
parseFloat(chartData[1].children[index].content.split(',')[1])) *
100
).toFixed(2),
valueOne: (
100 -
(parseFloat(chartData[1].children[index].content.split(',')[0]) /
parseFloat(chartData[1].children[index].content.split(',')[1])) *
100
).toFixed(2),
})
);
} else if (
chartType === 'line' ||
chartType === 'bar' ||
chartType === 'stackedbar'
) {
let mostValuesInSeries = 0;
chartObj = chartData[0].children.map(
(val1: { content: string }, index: number) => {
const values: string[] =
chartData[1].children[index].content.split(',');
if (values.length > mostValuesInSeries) {
mostValuesInSeries = values.length;
}
let returnObj = {
name: val1.content,
};
for (let i = 0; i < values.length; i++) {
returnObj[`value${i}`] = parseFloat(values[i]);
}
return returnObj;
}
);
chartObj['mostValuesInSeries'] = mostValuesInSeries;
} else {
chartObj = chartData[0].children.map(
(val1: { content: string }, index: number) => ({
name: val1.content,
value: parseFloat(chartData[1].children[index].content),
})
);
}
return {
chartObj,
chartType,
colour,
chartHeight,
chartWidth,
xAxisLabel,
yAxisLabel,
};
};
export const randomColours = () => {
const letters = '0123456789ABCDEF';
let colour = '#';
for (let i = 0; i < 6; i++) {
colour += letters[Math.floor(Math.random() * 16)];
}
return colour;
};
| 27.012195 | 77 | 0.561174 | 73 | 5 | 0 | 8 | 15 | 0 | 0 | 2 | 8 | 0 | 0 | 19.8 | 622 | 0.0209 | 0.024116 | 0 | 0 | 0 | 0.071429 | 0.285714 | 0.2963 | export const createChart = (chartData, chartOptions) => {
let [chartType, colour, height] = chartOptions.split(' ');
const chartHeight = parseFloat(height);
const chartWidth = chartHeight * 1.78;
const xAxisLabel = chartData[0].content;
const yAxisLabel = chartData[1].content;
let chartObj;
if (chartType === 'percentbar') {
chartObj = chartData[0].children.map(
(val1, index) => ({
name: val1.content,
valueZero: (
(parseFloat(chartData[1].children[index].content.split(',')[0]) /
parseFloat(chartData[1].children[index].content.split(',')[1])) *
100
).toFixed(2),
valueOne: (
100 -
(parseFloat(chartData[1].children[index].content.split(',')[0]) /
parseFloat(chartData[1].children[index].content.split(',')[1])) *
100
).toFixed(2),
})
);
} else if (
chartType === 'line' ||
chartType === 'bar' ||
chartType === 'stackedbar'
) {
let mostValuesInSeries = 0;
chartObj = chartData[0].children.map(
(val1, index) => {
const values =
chartData[1].children[index].content.split(',');
if (values.length > mostValuesInSeries) {
mostValuesInSeries = values.length;
}
let returnObj = {
name: val1.content,
};
for (let i = 0; i < values.length; i++) {
returnObj[`value${i}`] = parseFloat(values[i]);
}
return returnObj;
}
);
chartObj['mostValuesInSeries'] = mostValuesInSeries;
} else {
chartObj = chartData[0].children.map(
(val1, index) => ({
name: val1.content,
value: parseFloat(chartData[1].children[index].content),
})
);
}
return {
chartObj,
chartType,
colour,
chartHeight,
chartWidth,
xAxisLabel,
yAxisLabel,
};
};
export const randomColours = () => {
const letters = '0123456789ABCDEF';
let colour = '#';
for (let i = 0; i < 6; i++) {
colour += letters[Math.floor(Math.random() * 16)];
}
return colour;
};
|
4069776bff590a946938caa5450c5db571dbd32e | 2,852 | ts | TypeScript | src/component/file-tree/lib/file-type-icons.ts | mvhenten/ace-edit | 961472e71218740f4974c0297ce31ed8cc2b00ee | [
"MIT"
] | 1 | 2022-02-09T09:47:41.000Z | 2022-02-09T09:47:41.000Z | src/component/file-tree/lib/file-type-icons.ts | mvhenten/ace-edit | 961472e71218740f4974c0297ce31ed8cc2b00ee | [
"MIT"
] | 10 | 2022-02-10T10:53:58.000Z | 2022-02-15T11:30:38.000Z | src/component/file-tree/lib/file-type-icons.ts | mvhenten/ace-edit | 961472e71218740f4974c0297ce31ed8cc2b00ee | [
"MIT"
] | null | null | null | export const getIconUrl = (path: string, isDir: boolean) => {
return `https://raw.githubusercontent.com/vscode-icons/vscode-icons/master/icons/${getIconName(
path,
isDir
)}.svg`;
};
function getIconName(path: string, isDir: boolean) {
if (!path) return "default_file";
if (isDir) return "default_folder";
const filename = path.substring(path.lastIndexOf("/") + 1);
const ext = filename.split(".").pop() || "";
return (
getIconNameFromExtension(ext) ||
getIconNameFromFileName(filename) ||
"default_file"
);
}
function getIconNameFromExtension(ext: string) {
switch (ext.toLowerCase()) {
case "js":
return "file_type_js";
case "ts":
return "file_type_typescript";
case "html":
return "file_type_html";
case "css":
return "file_type_css";
case "less":
return "file_type_less";
case "sass":
return "file_type_sass";
case "scss":
return "file_type_scss";
case "json":
return "file_type_json";
case "py":
return "file_type_python";
case "rb":
return "file_type_ruby";
case "go":
return "file_type_go";
case "rust":
return "file_type_rust";
case "java":
return "file_type_java";
case "scala":
return "file_type_scala";
case "swift":
return "file_type_swift";
case "sh":
return "file_type_shell";
case "makefile":
return "file_type_shell";
case "bat":
return "file_type_shell";
case "bash":
return "file_type_shell";
case "cs":
return "file_type_csharp";
case "yml":
return "file_type_yaml";
case "yaml":
return "file_type_yaml";
case "xml":
return "file_type_xml";
case "md":
return "file_type_markdown";
case "sql":
return "file_type_sql";
case "jpg":
return "file_type_image";
case "svg":
return "file_type_image";
case "jpeg":
return "file_type_image";
case "png":
return "file_type_image";
case "gif":
return "file_type_image";
case "bmp":
return "file_type_image";
default:
return null;
}
}
function getIconNameFromFileName(filename: string) {
switch (filename.toLowerCase()) {
case "dockerfile":
return "file_type_docker";
case ".gitignore":
return "file_type_git2";
case ".gitattributes":
return "file_type_git2";
default:
return null;
}
}
| 28.237624 | 99 | 0.5277 | 97 | 4 | 0 | 6 | 3 | 0 | 3 | 0 | 6 | 0 | 0 | 22.25 | 704 | 0.014205 | 0.004261 | 0 | 0 | 0 | 0 | 0.461538 | 0.21743 | export const getIconUrl = (path, isDir) => {
return `https://raw.githubusercontent.com/vscode-icons/vscode-icons/master/icons/${getIconName(
path,
isDir
)}.svg`;
};
/* Example usages of 'getIconName' are shown below:
getIconName(path, isDir);
*/
function getIconName(path, isDir) {
if (!path) return "default_file";
if (isDir) return "default_folder";
const filename = path.substring(path.lastIndexOf("/") + 1);
const ext = filename.split(".").pop() || "";
return (
getIconNameFromExtension(ext) ||
getIconNameFromFileName(filename) ||
"default_file"
);
}
/* Example usages of 'getIconNameFromExtension' are shown below:
getIconNameFromExtension(ext) ||
getIconNameFromFileName(filename) ||
"default_file";
*/
function getIconNameFromExtension(ext) {
switch (ext.toLowerCase()) {
case "js":
return "file_type_js";
case "ts":
return "file_type_typescript";
case "html":
return "file_type_html";
case "css":
return "file_type_css";
case "less":
return "file_type_less";
case "sass":
return "file_type_sass";
case "scss":
return "file_type_scss";
case "json":
return "file_type_json";
case "py":
return "file_type_python";
case "rb":
return "file_type_ruby";
case "go":
return "file_type_go";
case "rust":
return "file_type_rust";
case "java":
return "file_type_java";
case "scala":
return "file_type_scala";
case "swift":
return "file_type_swift";
case "sh":
return "file_type_shell";
case "makefile":
return "file_type_shell";
case "bat":
return "file_type_shell";
case "bash":
return "file_type_shell";
case "cs":
return "file_type_csharp";
case "yml":
return "file_type_yaml";
case "yaml":
return "file_type_yaml";
case "xml":
return "file_type_xml";
case "md":
return "file_type_markdown";
case "sql":
return "file_type_sql";
case "jpg":
return "file_type_image";
case "svg":
return "file_type_image";
case "jpeg":
return "file_type_image";
case "png":
return "file_type_image";
case "gif":
return "file_type_image";
case "bmp":
return "file_type_image";
default:
return null;
}
}
/* Example usages of 'getIconNameFromFileName' are shown below:
getIconNameFromExtension(ext) ||
getIconNameFromFileName(filename) ||
"default_file";
*/
function getIconNameFromFileName(filename) {
switch (filename.toLowerCase()) {
case "dockerfile":
return "file_type_docker";
case ".gitignore":
return "file_type_git2";
case ".gitattributes":
return "file_type_git2";
default:
return null;
}
}
|
40bf514dc401b58ab0df1663702f4c0aec1a112b | 1,898 | ts | TypeScript | problemset/count-of-range-sum/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/count-of-range-sum/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/count-of-range-sum/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 暴力解法
* @desc 时间复杂度 O(NlogN) 空间复杂度 O(N)
* @param nums
* @param lower
* @param upper
* @returns
*/
export function countRangeSum(nums: number[], lower: number, upper: number): number {
const len = nums.length
let res = 0
for (let i = 0; i < len; i++) {
let sum = 0
for (let j = i; j < len; j++) {
sum += nums[j]
if (sum >= lower && sum <= upper) res++
}
}
return res
}
/**
* 归并排序
* @desc 时间复杂度 O(N²) 空间复杂度 O(1)
* @param nums
* @param lower
* @param upper
* @returns
*/
export function countRangeSum2(nums: number[], lower: number, upper: number): number {
let s = 0
const sum = [0]
for (const val of nums)
sum.push(s += val)
return countRangeSumRecursive(sum, lower, upper, 0, sum.length - 1)
function countRangeSumRecursive(
sum: number[],
lower: number,
upper: number,
left: number,
right: number,
): number {
if (left === right) return 0
const mid = (left + right) >> 1
const n1 = countRangeSumRecursive(sum, lower, upper, left, mid)
const n2 = countRangeSumRecursive(sum, lower, upper, mid + 1, right)
let res = n1 + n2
// 统计下标对的数量
let i = left
let l = mid + 1
let r = mid + 1
while (i <= mid) {
while (l <= right && sum[l] - sum[i] < lower) l++
while (r <= right && sum[r] - sum[i] <= upper) r++
res += (r - l)
i++
}
// 合并两个排序数组
const sorted: number[] = []
let p1 = left
let p2 = mid + 1
let p = 0
while (p1 <= mid || p2 <= right) {
if (p1 > mid) {
sorted[p++] = sum[p2++]
}
else if (p2 > right) {
sorted[p++] = sum[p1++]
}
else {
if (sum[p1] < sum[p2])
sorted[p++] = sum[p1++]
else
sorted[p++] = sum[p2++]
}
}
for (let i = 0; i < sorted.length; i++)
sum[left + i] = sorted[i]
return res
}
}
| 20.630435 | 86 | 0.512118 | 62 | 3 | 0 | 11 | 19 | 0 | 1 | 0 | 15 | 0 | 0 | 31 | 666 | 0.021021 | 0.028529 | 0 | 0 | 0 | 0 | 0.454545 | 0.312232 | /**
* 暴力解法
* @desc 时间复杂度 O(NlogN) 空间复杂度 O(N)
* @param nums
* @param lower
* @param upper
* @returns
*/
export function countRangeSum(nums, lower, upper) {
const len = nums.length
let res = 0
for (let i = 0; i < len; i++) {
let sum = 0
for (let j = i; j < len; j++) {
sum += nums[j]
if (sum >= lower && sum <= upper) res++
}
}
return res
}
/**
* 归并排序
* @desc 时间复杂度 O(N²) 空间复杂度 O(1)
* @param nums
* @param lower
* @param upper
* @returns
*/
export function countRangeSum2(nums, lower, upper) {
let s = 0
const sum = [0]
for (const val of nums)
sum.push(s += val)
return countRangeSumRecursive(sum, lower, upper, 0, sum.length - 1)
/* Example usages of 'countRangeSumRecursive' are shown below:
countRangeSumRecursive(sum, lower, upper, 0, sum.length - 1);
countRangeSumRecursive(sum, lower, upper, left, mid);
countRangeSumRecursive(sum, lower, upper, mid + 1, right);
*/
function countRangeSumRecursive(
sum,
lower,
upper,
left,
right,
) {
if (left === right) return 0
const mid = (left + right) >> 1
const n1 = countRangeSumRecursive(sum, lower, upper, left, mid)
const n2 = countRangeSumRecursive(sum, lower, upper, mid + 1, right)
let res = n1 + n2
// 统计下标对的数量
let i = left
let l = mid + 1
let r = mid + 1
while (i <= mid) {
while (l <= right && sum[l] - sum[i] < lower) l++
while (r <= right && sum[r] - sum[i] <= upper) r++
res += (r - l)
i++
}
// 合并两个排序数组
const sorted = []
let p1 = left
let p2 = mid + 1
let p = 0
while (p1 <= mid || p2 <= right) {
if (p1 > mid) {
sorted[p++] = sum[p2++]
}
else if (p2 > right) {
sorted[p++] = sum[p1++]
}
else {
if (sum[p1] < sum[p2])
sorted[p++] = sum[p1++]
else
sorted[p++] = sum[p2++]
}
}
for (let i = 0; i < sorted.length; i++)
sum[left + i] = sorted[i]
return res
}
}
|
1e77790db7b2fb2bc54e0cf7b258c00999f031a1 | 3,166 | ts | TypeScript | src/bezier.ts | SansDeus/useful | 8b218d2bef4b854d37d4861340495621e2dfdeb6 | [
"MIT"
] | 1 | 2022-02-08T03:31:32.000Z | 2022-02-08T03:31:32.000Z | src/bezier.ts | SansDeus/useful | 8b218d2bef4b854d37d4861340495621e2dfdeb6 | [
"MIT"
] | null | null | null | src/bezier.ts | SansDeus/useful | 8b218d2bef4b854d37d4861340495621e2dfdeb6 | [
"MIT"
] | null | null | null | /**
* https://github.com/gre/bezier-easing
* BezierEasing - use bezier curve for transition easing function
* by Gaëtan Renaudeau 2014 - 2015 – MIT License
*/
export const Bezier = (values: number[]) => {
if(values.length === 0) return (v: number) => 0;
const newtonIterations = 4;
const newtonMinSlope = 0.001;
const subdivisionPrecision = 0.0000001;
const subdivisionMaxIterations = 10;
const kSplineTableSize = 11;
const kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
const A = (aA1: number, aA2: number) => 1.0 - 3.0 * aA2 + 3.0 * aA1;
const B = (aA1: number, aA2: number) => 3.0 * aA2 - 6.0 * aA1;
const C = (aA1: number) => 3.0 * aA1;
const float32ArraySupported = () => typeof Float32Array === "function";
const calcBezier = (aT: number, aA1: number, aA2: number) => ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
const getSlope = (aT: number, aA1: number, aA2: number) => 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
const binarySubdivide = (aX: number, aA: number, aB: number, mX1: number, mX2: number) => {
let currentX: number;
let currentT: number;
let i = 0;
do {
currentT = aA + (aB - aA) / 2.0;
currentX = calcBezier(currentT, mX1, mX2) - aX;
if (currentX > 0.0) {
aB = currentT;
} else {
aA = currentT;
}
} while (Math.abs(currentX) > subdivisionPrecision && ++i < subdivisionMaxIterations);
return currentT;
}
const newtonRaphsonIterate = (aX: number, aGuessT: number, mX1: number, mX2: number) => {
for (let i = 0; i < newtonIterations; ++i) {
const currentSlope = getSlope(aGuessT, mX1, mX2);
if (currentSlope === 0.0) {
return aGuessT;
}
const currentX = calcBezier(aGuessT, mX1, mX2) - aX;
aGuessT -= currentX / currentSlope;
}
return aGuessT;
}
const create = (coords: number[]): ((t: number) => number) => {
const [mX1, mY1, mX2, mY2] = coords;
const sampleValues = float32ArraySupported()
? new Float32Array(kSplineTableSize)
: new Array(kSplineTableSize);
if (mX1 !== mY1 || mX2 !== mY2) {
for (let i = 0; i < kSplineTableSize; ++i) {
sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
}
}
const getTForX = (aX: number) => {
let intervalStart = 0.0;
let currentSample = 1;
const lastSample = kSplineTableSize - 1;
for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) {
intervalStart += kSampleStepSize;
}
--currentSample;
const dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
const guessForT = intervalStart + dist * kSampleStepSize;
const initialSlope = getSlope(guessForT, mX1, mX2);
if (initialSlope >= newtonMinSlope) {
return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
} else if (initialSlope === 0.0) {
return guessForT;
} else {
return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
}
};
return (x: number) => {
if (mX1 === mY1 && mX2 === mY2) return x;
if (x === 0) return 0;
if (x === 1) return 1;
return calcBezier(getTForX(x), mY1, mY2);
}
}
return create(values);
}
| 35.177778 | 122 | 0.636134 | 78 | 13 | 0 | 25 | 32 | 0 | 10 | 0 | 29 | 0 | 1 | 12.307692 | 1,280 | 0.029688 | 0.025 | 0 | 0 | 0.000781 | 0 | 0.414286 | 0.323137 | /**
* https://github.com/gre/bezier-easing
* BezierEasing - use bezier curve for transition easing function
* by Gaëtan Renaudeau 2014 - 2015 – MIT License
*/
export const Bezier = (values) => {
if(values.length === 0) return (v) => 0;
const newtonIterations = 4;
const newtonMinSlope = 0.001;
const subdivisionPrecision = 0.0000001;
const subdivisionMaxIterations = 10;
const kSplineTableSize = 11;
const kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
/* Example usages of 'A' are shown below:
A(aA1, aA2) * aT + B(aA1, aA2);
3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
*/
const A = (aA1, aA2) => 1.0 - 3.0 * aA2 + 3.0 * aA1;
/* Example usages of 'B' are shown below:
A(aA1, aA2) * aT + B(aA1, aA2);
3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
*/
const B = (aA1, aA2) => 3.0 * aA2 - 6.0 * aA1;
/* Example usages of 'C' are shown below:
(A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1);
3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
*/
const C = (aA1) => 3.0 * aA1;
/* Example usages of 'float32ArraySupported' are shown below:
float32ArraySupported()
? new Float32Array(kSplineTableSize)
: new Array(kSplineTableSize);
*/
const float32ArraySupported = () => typeof Float32Array === "function";
/* Example usages of 'calcBezier' are shown below:
currentX = calcBezier(currentT, mX1, mX2) - aX;
calcBezier(aGuessT, mX1, mX2) - aX;
sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
calcBezier(getTForX(x), mY1, mY2);
*/
const calcBezier = (aT, aA1, aA2) => ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
/* Example usages of 'getSlope' are shown below:
getSlope(aGuessT, mX1, mX2);
getSlope(guessForT, mX1, mX2);
*/
const getSlope = (aT, aA1, aA2) => 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
/* Example usages of 'binarySubdivide' are shown below:
binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
*/
const binarySubdivide = (aX, aA, aB, mX1, mX2) => {
let currentX;
let currentT;
let i = 0;
do {
currentT = aA + (aB - aA) / 2.0;
currentX = calcBezier(currentT, mX1, mX2) - aX;
if (currentX > 0.0) {
aB = currentT;
} else {
aA = currentT;
}
} while (Math.abs(currentX) > subdivisionPrecision && ++i < subdivisionMaxIterations);
return currentT;
}
/* Example usages of 'newtonRaphsonIterate' are shown below:
newtonRaphsonIterate(aX, guessForT, mX1, mX2);
*/
const newtonRaphsonIterate = (aX, aGuessT, mX1, mX2) => {
for (let i = 0; i < newtonIterations; ++i) {
const currentSlope = getSlope(aGuessT, mX1, mX2);
if (currentSlope === 0.0) {
return aGuessT;
}
const currentX = calcBezier(aGuessT, mX1, mX2) - aX;
aGuessT -= currentX / currentSlope;
}
return aGuessT;
}
/* Example usages of 'create' are shown below:
create(values);
*/
const create = (coords) => {
const [mX1, mY1, mX2, mY2] = coords;
const sampleValues = float32ArraySupported()
? new Float32Array(kSplineTableSize)
: new Array(kSplineTableSize);
if (mX1 !== mY1 || mX2 !== mY2) {
for (let i = 0; i < kSplineTableSize; ++i) {
sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
}
}
/* Example usages of 'getTForX' are shown below:
calcBezier(getTForX(x), mY1, mY2);
*/
const getTForX = (aX) => {
let intervalStart = 0.0;
let currentSample = 1;
const lastSample = kSplineTableSize - 1;
for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) {
intervalStart += kSampleStepSize;
}
--currentSample;
const dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
const guessForT = intervalStart + dist * kSampleStepSize;
const initialSlope = getSlope(guessForT, mX1, mX2);
if (initialSlope >= newtonMinSlope) {
return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
} else if (initialSlope === 0.0) {
return guessForT;
} else {
return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
}
};
return (x) => {
if (mX1 === mY1 && mX2 === mY2) return x;
if (x === 0) return 0;
if (x === 1) return 1;
return calcBezier(getTForX(x), mY1, mY2);
}
}
return create(values);
}
|
dee4a34c955fd13da1de7ae43821257c0b36e782 | 1,766 | ts | TypeScript | problemset/letter-combinations-of-a-phone-number/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/letter-combinations-of-a-phone-number/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/letter-combinations-of-a-phone-number/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 暴力解法
* @desc 时间复杂度 O(3^m*4^n) 空间复杂度 O(m+n)
* @param digits
* @return {string[]}
*/
export function letterCombinations(digits: string): string[] {
if (digits === '') return []
const keyMap: Map<string, string[]> = new Map([
['2', ['a', 'b', 'c']],
['3', ['d', 'e', 'f']],
['4', ['g', 'h', 'i']],
['5', ['j', 'k', 'l']],
['6', ['m', 'n', 'o']],
['7', ['p', 'q', 'r', 's']],
['8', ['t', 'u', 'v']],
['9', ['w', 'x', 'y', 'z']],
])
let ans: string[] = []
for (let i = 0; i < digits.length; i++) {
const map: string[] = keyMap.get(digits[i]) || []
if (!ans.length) {
ans.push(...map)
}
else {
const newAns: string[] = []
ans.forEach((str) => {
map.forEach((letter) => {
newAns.push(str + letter)
})
})
ans = newAns
}
}
return ans
}
/**
* 回溯
* @desc 时间复杂度 O(3^m*4^n) 空间复杂度 O(m+n)
* @param digits
* @return {string[]}
*/
export function letterCombinations2(digits: string): string[] {
if (!digits) return []
const keyMap: Map<string, string> = new Map([
['2', 'abc'],
['3', 'def'],
['4', 'ghi'],
['5', 'jkl'],
['6', 'mno'],
['7', 'pqrs'],
['8', 'tuv'],
['9', 'wxyz'],
])
const ans: string[] = []
backtrack('', digits)
return ans
function backtrack(str: string, digits: string) {
if (!digits.length) {
ans.push(str) // 如果字符串为空了,将拼接好的字符加入数组
}
else {
// 拿到字符串第一个字符其对应的数字
const letters: string = keyMap.get(digits[0]) || ''
// 对可能性进行组合
for (let i = 0; i < letters.length; i++) {
str += letters[i]
// 递归组好的 str和下一段字符串
backtrack(str, digits.slice(1))
// 回溯
str = str.slice(0, -1)
}
}
}
}
| 20.776471 | 63 | 0.451869 | 59 | 5 | 0 | 6 | 9 | 0 | 1 | 0 | 15 | 0 | 0 | 14 | 659 | 0.016692 | 0.013657 | 0 | 0 | 0 | 0 | 0.75 | 0.253038 | /**
* 暴力解法
* @desc 时间复杂度 O(3^m*4^n) 空间复杂度 O(m+n)
* @param digits
* @return {string[]}
*/
export function letterCombinations(digits) {
if (digits === '') return []
const keyMap = new Map([
['2', ['a', 'b', 'c']],
['3', ['d', 'e', 'f']],
['4', ['g', 'h', 'i']],
['5', ['j', 'k', 'l']],
['6', ['m', 'n', 'o']],
['7', ['p', 'q', 'r', 's']],
['8', ['t', 'u', 'v']],
['9', ['w', 'x', 'y', 'z']],
])
let ans = []
for (let i = 0; i < digits.length; i++) {
const map = keyMap.get(digits[i]) || []
if (!ans.length) {
ans.push(...map)
}
else {
const newAns = []
ans.forEach((str) => {
map.forEach((letter) => {
newAns.push(str + letter)
})
})
ans = newAns
}
}
return ans
}
/**
* 回溯
* @desc 时间复杂度 O(3^m*4^n) 空间复杂度 O(m+n)
* @param digits
* @return {string[]}
*/
export function letterCombinations2(digits) {
if (!digits) return []
const keyMap = new Map([
['2', 'abc'],
['3', 'def'],
['4', 'ghi'],
['5', 'jkl'],
['6', 'mno'],
['7', 'pqrs'],
['8', 'tuv'],
['9', 'wxyz'],
])
const ans = []
backtrack('', digits)
return ans
/* Example usages of 'backtrack' are shown below:
backtrack('', digits);
// 递归组好的 str和下一段字符串
backtrack(str, digits.slice(1));
*/
function backtrack(str, digits) {
if (!digits.length) {
ans.push(str) // 如果字符串为空了,将拼接好的字符加入数组
}
else {
// 拿到字符串第一个字符其对应的数字
const letters = keyMap.get(digits[0]) || ''
// 对可能性进行组合
for (let i = 0; i < letters.length; i++) {
str += letters[i]
// 递归组好的 str和下一段字符串
backtrack(str, digits.slice(1))
// 回溯
str = str.slice(0, -1)
}
}
}
}
|
4435a98275bc2c5632caaf5b25b234898288022d | 4,198 | ts | TypeScript | src/components/canvasIcons.ts | spking11/EldenRingOnlineMap | 7f63421edf692fbd3c50fa2e24f0663f3579050a | [
"MIT"
] | 131 | 2022-03-01T03:02:13.000Z | 2022-03-31T18:06:08.000Z | src/components/canvasIcons.ts | Garfield247/EldenRingOnlineMap | 8c8f4f16dee20a71be2b9ee886a74cf9d772cd24 | [
"MIT"
] | 25 | 2022-03-09T02:15:57.000Z | 2022-03-31T08:00:00.000Z | src/components/canvasIcons.ts | Garfield247/EldenRingOnlineMap | 8c8f4f16dee20a71be2b9ee886a74cf9d772cd24 | [
"MIT"
] | 16 | 2022-03-08T19:27:29.000Z | 2022-03-31T05:28:21.000Z | /**
* 自定义地图图标
* @description 导出的是生成图标数据的函数,用法:`L.divIcon(iconname(size, fontcolor)(title))`
*/
export const MapCanvasIcon = {
default:
(size: number = 10, fontcolor: string = 'white') =>
(title?: string, fontSize: string = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
cifu:
(size: number = 20, fontcolor: string = 'white') =>
(title?: string, fontSize: string = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
boss:
(size: number = 30, fontcolor: string = 'yellow') =>
(title?: string, fontSize: string = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
littleboss:
(size: number = 28, fontcolor: string = 'yellow') =>
(title?: string, fontSize: string = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
portal:
(size: number = 24, fontcolor: string = 'white') =>
(title?: string, fontSize: string = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
message:
(size: number = 20, fontcolor: string = 'white') =>
(title?: string, fontSize: string = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
warning:
(size: number = 15, fontcolor: string = 'white') =>
(title?: string, fontSize: string = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
question:
(size: number = 15, fontcolor: string = 'white') =>
(title?: string, fontSize: string = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
collect:
(size: number = 20, fontcolor: string = 'white') =>
(title?: string, fontSize: string = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
white:
(size: number = 10, fontcolor: string = 'white') =>
(title?: string, fontSize: string = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
yellow:
(size: number = 10, fontcolor: string = 'white') =>
(title?: string, fontSize: string = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
green:
(size: number = 10, fontcolor: string = 'white') =>
(title?: string, fontSize: string = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
blue:
(size: number = 10, fontcolor: string = 'white') =>
(title?: string, fontSize: string = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
red:
(size: number = 10, fontcolor: string = 'white') =>
(title?: string, fontSize: string = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
purple:
(size: number = 10, fontcolor: string = 'white') =>
(title?: string, fontSize: string = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
};
| 29.56338 | 78 | 0.507861 | 137 | 30 | 0 | 60 | 1 | 0 | 0 | 0 | 60 | 0 | 0 | 5.5 | 1,319 | 0.068234 | 0.000758 | 0 | 0 | 0 | 0 | 0.659341 | 0.331361 | /**
* 自定义地图图标
* @description 导出的是生成图标数据的函数,用法:`L.divIcon(iconname(size, fontcolor)(title))`
*/
export const MapCanvasIcon = {
default:
(size = 10, fontcolor = 'white') =>
(title?, fontSize = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
cifu:
(size = 20, fontcolor = 'white') =>
(title?, fontSize = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
boss:
(size = 30, fontcolor = 'yellow') =>
(title?, fontSize = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
littleboss:
(size = 28, fontcolor = 'yellow') =>
(title?, fontSize = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
portal:
(size = 24, fontcolor = 'white') =>
(title?, fontSize = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
message:
(size = 20, fontcolor = 'white') =>
(title?, fontSize = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
warning:
(size = 15, fontcolor = 'white') =>
(title?, fontSize = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
question:
(size = 15, fontcolor = 'white') =>
(title?, fontSize = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
collect:
(size = 20, fontcolor = 'white') =>
(title?, fontSize = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
white:
(size = 10, fontcolor = 'white') =>
(title?, fontSize = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
yellow:
(size = 10, fontcolor = 'white') =>
(title?, fontSize = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
green:
(size = 10, fontcolor = 'white') =>
(title?, fontSize = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
blue:
(size = 10, fontcolor = 'white') =>
(title?, fontSize = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
red:
(size = 10, fontcolor = 'white') =>
(title?, fontSize = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
purple:
(size = 10, fontcolor = 'white') =>
(title?, fontSize = '0.8em') => {
return {
iconUrl: './resource/icons/boss.png',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
};
},
};
|
44481f570658425682f18a6a5dc25f8f8fe067af | 1,067 | ts | TypeScript | src/Hooks/Client/userDataHandler.ts | callmenikk/JetChat | 6f5ba02f6d112ed11e48f08c1a30a1a40a42cf6d | [
"CC0-1.0"
] | 7 | 2022-02-22T06:58:56.000Z | 2022-03-14T11:40:10.000Z | src/Hooks/Client/userDataHandler.ts | callmenikk/JetChat | 6f5ba02f6d112ed11e48f08c1a30a1a40a42cf6d | [
"CC0-1.0"
] | null | null | null | src/Hooks/Client/userDataHandler.ts | callmenikk/JetChat | 6f5ba02f6d112ed11e48f08c1a30a1a40a42cf6d | [
"CC0-1.0"
] | null | null | null | export type State = {
username: string,
client_id: string,
createdAt: string,
profile_src: string,
isLogined: boolean
}
type Action = {
type: "FILL_USER" | "CLEAR_ALL_THE_DATA" | "SPECIFIC_KEY_UPDATE",
payload: {
username: string,
client_id: string,
createdAt: string,
profile_src: string,
isLogined: boolean,
key?: string ,
value?: string
}
}
const defaultState: State = {
username: '',
client_id: '',
createdAt: '',
profile_src: '',
isLogined: false
}
export const userDataHandler = (state: State = defaultState, action: Action): State => {
switch(action.type){
case "FILL_USER": {
const {username, client_id, createdAt, profile_src, isLogined} = action.payload
return {
username: username,
client_id: client_id,
createdAt: createdAt,
profile_src: profile_src,
isLogined: isLogined
}
}case "CLEAR_ALL_THE_DATA": {
return defaultState
}
case "SPECIFIC_KEY_UPDATE": {
const {key, value} = action.payload
return {
...state,
[key!]: value
}
}
default: return state
}
} | 19.053571 | 88 | 0.666354 | 50 | 1 | 0 | 2 | 4 | 7 | 0 | 0 | 12 | 2 | 0 | 22 | 361 | 0.00831 | 0.01108 | 0.019391 | 0.00554 | 0 | 0 | 0.857143 | 0.233582 | export type State = {
username,
client_id,
createdAt,
profile_src,
isLogined
}
type Action = {
type,
payload
}
const defaultState = {
username: '',
client_id: '',
createdAt: '',
profile_src: '',
isLogined: false
}
export const userDataHandler = (state = defaultState, action) => {
switch(action.type){
case "FILL_USER": {
const {username, client_id, createdAt, profile_src, isLogined} = action.payload
return {
username: username,
client_id: client_id,
createdAt: createdAt,
profile_src: profile_src,
isLogined: isLogined
}
}case "CLEAR_ALL_THE_DATA": {
return defaultState
}
case "SPECIFIC_KEY_UPDATE": {
const {key, value} = action.payload
return {
...state,
[key!]: value
}
}
default: return state
}
} |
447d49816b0bfc51e151a39117989ca37c72fc22 | 1,205 | ts | TypeScript | src/useCases/calculator.ts | Iray68/react-simple-picker | c9f454b019d325f31619844e71bd71b28bc775d1 | [
"MIT"
] | null | null | null | src/useCases/calculator.ts | Iray68/react-simple-picker | c9f454b019d325f31619844e71bd71b28bc775d1 | [
"MIT"
] | 1 | 2022-02-18T08:19:29.000Z | 2022-02-18T08:19:29.000Z | src/useCases/calculator.ts | Iray68/react-simple-picker | c9f454b019d325f31619844e71bd71b28bc775d1 | [
"MIT"
] | null | null | null | export interface Operator<T, R> {
(raw: T, count: T): R;
}
export type NumberOperator = Operator<number, number | null>;
export function addGenerator(
maxCount: number,
displayLoop: boolean,
minCount: number
): NumberOperator {
const add: NumberOperator = (current, diff = 1) => {
const total = current + diff;
if (total > maxCount) {
if (!displayLoop) {
return null;
}
return total - maxCount - 1 + minCount;
}
return total;
};
return add;
}
export function minusGenerator(
minCount: number,
displayLoop: boolean,
maxCount: number
): NumberOperator {
const minus: NumberOperator = (current, diff = 1) => {
const total = current + diff * -1;
if (total < minCount) {
if (!displayLoop) {
return null;
}
return maxCount + 1 + total - minCount;
}
return total;
};
return minus;
}
export function buildPositionCalculator(
add: NumberOperator,
minus: NumberOperator
): NumberOperator {
const calculate = (current: number, diff: number) => {
if (diff === 0) {
return current;
}
return diff > 0 ? add(current, diff) : minus(current, diff * -1);
};
return calculate;
}
| 20.775862 | 69 | 0.619087 | 50 | 6 | 0 | 14 | 5 | 0 | 2 | 0 | 10 | 2 | 0 | 8.166667 | 331 | 0.060423 | 0.015106 | 0 | 0.006042 | 0 | 0 | 0.4 | 0.370575 | export interface Operator<T, R> {
(raw, count);
}
export type NumberOperator = Operator<number, number | null>;
export function addGenerator(
maxCount,
displayLoop,
minCount
) {
/* Example usages of 'add' are shown below:
return add;
;
diff > 0 ? add(current, diff) : minus(current, diff * -1);
*/
const add = (current, diff = 1) => {
const total = current + diff;
if (total > maxCount) {
if (!displayLoop) {
return null;
}
return total - maxCount - 1 + minCount;
}
return total;
};
return add;
}
export function minusGenerator(
minCount,
displayLoop,
maxCount
) {
/* Example usages of 'minus' are shown below:
return minus;
;
diff > 0 ? add(current, diff) : minus(current, diff * -1);
*/
const minus = (current, diff = 1) => {
const total = current + diff * -1;
if (total < minCount) {
if (!displayLoop) {
return null;
}
return maxCount + 1 + total - minCount;
}
return total;
};
return minus;
}
export function buildPositionCalculator(
add,
minus
) {
/* Example usages of 'calculate' are shown below:
return calculate;
*/
const calculate = (current, diff) => {
if (diff === 0) {
return current;
}
return diff > 0 ? add(current, diff) : minus(current, diff * -1);
};
return calculate;
}
|
4496a54dc085a3025bf352793a78be8095f7dbf4 | 1,808 | ts | TypeScript | behavior_packs/mcwl BP/scripts/ts/Utils/data/PlayerData.ts | picobyte86/mcwl | e391e4f3d4ca2d55cf6295dcaf0974d78a920f5f | [
"MIT"
] | 2 | 2022-02-14T20:48:45.000Z | 2022-02-26T05:25:06.000Z | behavior_packs/mcwl BP/scripts/ts/Utils/data/PlayerData.ts | picobyte86/mcwl | e391e4f3d4ca2d55cf6295dcaf0974d78a920f5f | [
"MIT"
] | null | null | null | behavior_packs/mcwl BP/scripts/ts/Utils/data/PlayerData.ts | picobyte86/mcwl | e391e4f3d4ca2d55cf6295dcaf0974d78a920f5f | [
"MIT"
] | null | null | null | export class PlayerData {
data: any
dataType: string
name: string
format: string
constructor(data: any, dataType: string, name: string) {
this.dataType = dataType;
this.name = name;
this.format = "v1.0"
switch (dataType) {
case "string":
this.data = (data as string)
break;
case "number":
this.data = (data as number)
break;
case "boolean":
this.data = (data as boolean)
break;
case "object":
this.data = (data as object)
break;
default:
}
}
toJSON(): PlayerJSONData {
if (this.dataType == "object") {
return Object.assign({}, this, {
data: JSON.stringify(this.data)
});
} else {
return Object.assign({}, this, {
data: this.data.toString()
});
}
}
static fromJSON(json: PlayerJSONData | string): PlayerData {
if (typeof json === 'string') {
return JSON.parse(json, PlayerData.reviver);
} else {
let user = Object.create(PlayerData.prototype);
if (json.dataType == "object") {
return Object.assign(user, json, {
data: JSON.parse(json.data)
});
} else {
return Object.assign(user, json, {
data: json.data.toString()
});
}
}
}
static reviver(key: string, value: any): any {
return key === "" ? PlayerData.fromJSON(value) : value;
}
}
interface PlayerJSONData {
data: any;
dataType: string;
name: string
format: string
} | 29.16129 | 64 | 0.466814 | 62 | 4 | 0 | 6 | 1 | 8 | 1 | 5 | 14 | 2 | 5 | 10.5 | 400 | 0.025 | 0.0025 | 0.02 | 0.005 | 0.0125 | 0.263158 | 0.736842 | 0.238026 | export class PlayerData {
data
dataType
name
format
constructor(data, dataType, name) {
this.dataType = dataType;
this.name = name;
this.format = "v1.0"
switch (dataType) {
case "string":
this.data = (data as string)
break;
case "number":
this.data = (data as number)
break;
case "boolean":
this.data = (data as boolean)
break;
case "object":
this.data = (data as object)
break;
default:
}
}
toJSON() {
if (this.dataType == "object") {
return Object.assign({}, this, {
data: JSON.stringify(this.data)
});
} else {
return Object.assign({}, this, {
data: this.data.toString()
});
}
}
static fromJSON(json) {
if (typeof json === 'string') {
return JSON.parse(json, PlayerData.reviver);
} else {
let user = Object.create(PlayerData.prototype);
if (json.dataType == "object") {
return Object.assign(user, json, {
data: JSON.parse(json.data)
});
} else {
return Object.assign(user, json, {
data: json.data.toString()
});
}
}
}
static reviver(key, value) {
return key === "" ? PlayerData.fromJSON(value) : value;
}
}
interface PlayerJSONData {
data;
dataType;
name
format
} |
44a520e620f5168e4463fcd975d71bdcee8e3767 | 3,288 | ts | TypeScript | src/utils/parseKindleHighlights.ts | theBenForce/logseq-plugin-my-highlights | 66500ad9e52f8d5a7d48ab161f34cf2c21283189 | [
"MIT"
] | 4 | 2022-03-03T14:14:43.000Z | 2022-03-31T12:26:22.000Z | src/utils/parseKindleHighlights.ts | theBenForce/logseq-plugin-my-highlights | 66500ad9e52f8d5a7d48ab161f34cf2c21283189 | [
"MIT"
] | 6 | 2022-03-03T12:22:49.000Z | 2022-03-03T21:53:52.000Z | src/utils/parseKindleHighlights.ts | theBenForce/logseq-plugin-my-highlights | 66500ad9e52f8d5a7d48ab161f34cf2c21283189 | [
"MIT"
] | 1 | 2022-03-06T14:11:50.000Z | 2022-03-06T14:11:50.000Z |
export type AnnotationType = 'Highlight' | 'Note' | 'Bookmark';
export interface KindleAnnotation {
timestamp: Date;
type: AnnotationType;
content?: string;
page?: number;
location: {
start: number;
end?: number;
}
}
export interface KindleBook extends BookMetadata {
lastAnnotation: Date;
annotations: Array<KindleAnnotation>;
}
interface BookMetadata {
title: string;
author?: string;
}
export const parseTitleLine = (titleLine: string) => {
const title = titleLine.replace(/\([^)]+\)$/g, '').trim();
const authorMatches = /\((?<author>[^)]+)\)$/g.exec(titleLine);
const author = authorMatches?.groups?.["author"]?.trim();
return { title, author };
}
export const parseMetaLine = (metaLine: string): KindleAnnotation => {
const typeRx = /^- Your\s(?<type>Note|Highlight|Bookmark)/;
const pageRx = /page\s+(?<page>\d+)/;
const locationRx = /Location\s+(?<start>\d+)(-(?<end>\d+))?/;
const timestampRx = /Added on\s+(?<timestamp>.*)$/;
const type = typeRx.exec(metaLine)?.groups?.['type'];
const pageVal = pageRx.exec(metaLine)?.groups?.['page'];
let page: number | undefined;
if (pageVal) {
page = parseInt(pageVal);
}
const locationVal = locationRx.exec(metaLine)?.groups;
if (!locationVal) {
throw new Error(`Could not find location: ${metaLine}`);
}
let start: number | undefined;
let end: number | undefined;
if (locationVal['start']) {
start = parseInt(locationVal['start']);
}
if (locationVal['end']) {
end = parseInt(locationVal['end']);
}
let timestamp = new Date();
const timestampVal = timestampRx.exec(metaLine)?.groups?.['timestamp'];
if (timestampVal) {
timestamp = new Date(Date.parse(timestampVal));
}
return {
type,
page,
timestamp,
location: {
start,
end
}
} as KindleAnnotation;
}
export const parseClipping = (clipping: string): KindleAnnotation & BookMetadata => {
const lines = clipping.trim().split(/\n/);
if (lines.length < 2) {
throw new Error(`Could not parse clipping, not enough lines: ${clipping}`);
}
const title = parseTitleLine(lines.shift()!.trim());
const metadata = parseMetaLine(lines.shift()!.trim());
const content = lines.join('\n').trim();
return {
...title,
...metadata,
content
};
}
export const parseKindleHighlights = (content: string): Array<KindleBook> => {
const clippings = content.split(/^==========$/gm).filter(line => Boolean(line.trim())).map(parseClipping);
return clippings.reduce((result, clipping) => {
let book = result.find((b) => b.title === clipping.title && b.author === clipping.author);
if (!book) {
book = {
title: clipping.title,
author: clipping.author,
annotations: [],
lastAnnotation: clipping.timestamp
};
result.push(book);
}
if (book.lastAnnotation < clipping.timestamp) {
book.lastAnnotation = clipping.timestamp;
}
book.annotations.push({
content: clipping.content,
location: clipping.location,
timestamp: clipping.timestamp,
type: clipping.type,
page: clipping.page
});
return result;
}, [] as Array<KindleBook>)
// @ts-ignore
.sort((a, b) => b.lastAnnotation - a.lastAnnotation);
} | 24.355556 | 108 | 0.63017 | 104 | 8 | 0 | 10 | 25 | 9 | 2 | 0 | 13 | 4 | 2 | 12.625 | 898 | 0.020045 | 0.02784 | 0.010022 | 0.004454 | 0.002227 | 0 | 0.25 | 0.31498 |
export type AnnotationType = 'Highlight' | 'Note' | 'Bookmark';
export interface KindleAnnotation {
timestamp;
type;
content?;
page?;
location
}
export interface KindleBook extends BookMetadata {
lastAnnotation;
annotations;
}
interface BookMetadata {
title;
author?;
}
export /* Example usages of 'parseTitleLine' are shown below:
parseTitleLine(lines.shift()!.trim());
*/
const parseTitleLine = (titleLine) => {
const title = titleLine.replace(/\([^)]+\)$/g, '').trim();
const authorMatches = /\((?<author>[^)]+)\)$/g.exec(titleLine);
const author = authorMatches?.groups?.["author"]?.trim();
return { title, author };
}
export /* Example usages of 'parseMetaLine' are shown below:
parseMetaLine(lines.shift()!.trim());
*/
const parseMetaLine = (metaLine) => {
const typeRx = /^- Your\s(?<type>Note|Highlight|Bookmark)/;
const pageRx = /page\s+(?<page>\d+)/;
const locationRx = /Location\s+(?<start>\d+)(-(?<end>\d+))?/;
const timestampRx = /Added on\s+(?<timestamp>.*)$/;
const type = typeRx.exec(metaLine)?.groups?.['type'];
const pageVal = pageRx.exec(metaLine)?.groups?.['page'];
let page;
if (pageVal) {
page = parseInt(pageVal);
}
const locationVal = locationRx.exec(metaLine)?.groups;
if (!locationVal) {
throw new Error(`Could not find location: ${metaLine}`);
}
let start;
let end;
if (locationVal['start']) {
start = parseInt(locationVal['start']);
}
if (locationVal['end']) {
end = parseInt(locationVal['end']);
}
let timestamp = new Date();
const timestampVal = timestampRx.exec(metaLine)?.groups?.['timestamp'];
if (timestampVal) {
timestamp = new Date(Date.parse(timestampVal));
}
return {
type,
page,
timestamp,
location: {
start,
end
}
} as KindleAnnotation;
}
export /* Example usages of 'parseClipping' are shown below:
content.split(/^==========$/gm).filter(line => Boolean(line.trim())).map(parseClipping);
*/
const parseClipping = (clipping) => {
const lines = clipping.trim().split(/\n/);
if (lines.length < 2) {
throw new Error(`Could not parse clipping, not enough lines: ${clipping}`);
}
const title = parseTitleLine(lines.shift()!.trim());
const metadata = parseMetaLine(lines.shift()!.trim());
const content = lines.join('\n').trim();
return {
...title,
...metadata,
content
};
}
export const parseKindleHighlights = (content) => {
const clippings = content.split(/^==========$/gm).filter(line => Boolean(line.trim())).map(parseClipping);
return clippings.reduce((result, clipping) => {
let book = result.find((b) => b.title === clipping.title && b.author === clipping.author);
if (!book) {
book = {
title: clipping.title,
author: clipping.author,
annotations: [],
lastAnnotation: clipping.timestamp
};
result.push(book);
}
if (book.lastAnnotation < clipping.timestamp) {
book.lastAnnotation = clipping.timestamp;
}
book.annotations.push({
content: clipping.content,
location: clipping.location,
timestamp: clipping.timestamp,
type: clipping.type,
page: clipping.page
});
return result;
}, [] as Array<KindleBook>)
// @ts-ignore
.sort((a, b) => b.lastAnnotation - a.lastAnnotation);
} |
44d761c6307094a13d3114c50abbe905f6737601 | 1,629 | ts | TypeScript | src/features/core/helper/timeSelectUnit.ts | open-inc/opendash-core | bf9998cce3a480ad43323d0d94d70d03805d0279 | [
"MIT"
] | null | null | null | src/features/core/helper/timeSelectUnit.ts | open-inc/opendash-core | bf9998cce3a480ad43323d0d94d70d03805d0279 | [
"MIT"
] | 1 | 2022-01-18T13:44:15.000Z | 2022-01-18T13:44:15.000Z | src/features/core/helper/timeSelectUnit.ts | open-inc/opendash-core | bf9998cce3a480ad43323d0d94d70d03805d0279 | [
"MIT"
] | null | null | null | // selectUnit is from: https://github.com/formatjs/formatjs/blob/master/packages/intl-utils/src/diff.ts
type Unit =
| "second"
| "minute"
| "hour"
| "day"
| "week"
| "month"
| "quarter"
| "year";
const MS_PER_SECOND = 1000;
const SECS_PER_MIN = 60;
const SECS_PER_HOUR = SECS_PER_MIN * 60;
const SECS_PER_DAY = SECS_PER_HOUR * 24;
const SECS_PER_WEEK = SECS_PER_DAY * 7;
const THRESHOLDS = {
second: 60, // seconds to minute
minute: 60, // minutes to hour
hour: 24, // hour to day
day: 7, // day to week
};
export function timeSelectUnit(
from: Date | number,
to: Date | number = Date.now()
): [number, Unit] {
const secs = (from.valueOf() - to.valueOf()) / MS_PER_SECOND;
if (Math.abs(secs) < THRESHOLDS.second) {
return [Math.round(secs), "second"];
}
const mins = secs / SECS_PER_MIN;
if (Math.abs(mins) < THRESHOLDS.minute) {
return [Math.round(mins), "minute"];
}
const hours = secs / SECS_PER_HOUR;
if (Math.abs(hours) < THRESHOLDS.hour) {
return [Math.round(hours), "hour"];
}
const days = secs / SECS_PER_DAY;
if (Math.abs(days) < THRESHOLDS.day) {
return [Math.round(days), "day"];
}
const fromDate = new Date(from);
const toDate = new Date(to);
const years = fromDate.getFullYear() - toDate.getFullYear();
if (Math.round(Math.abs(years)) > 0) {
return [Math.round(years), "year"];
}
const months = years * 12 + fromDate.getMonth() - toDate.getMonth();
if (Math.round(Math.abs(months)) > 0) {
return [Math.round(months), "month"];
}
const weeks = secs / SECS_PER_WEEK;
return [Math.round(weeks), "week"];
}
| 22.625 | 103 | 0.637201 | 53 | 1 | 0 | 2 | 15 | 0 | 0 | 0 | 3 | 1 | 0 | 28 | 583 | 0.005146 | 0.025729 | 0 | 0.001715 | 0 | 0 | 0.166667 | 0.268787 | // selectUnit is from: https://github.com/formatjs/formatjs/blob/master/packages/intl-utils/src/diff.ts
type Unit =
| "second"
| "minute"
| "hour"
| "day"
| "week"
| "month"
| "quarter"
| "year";
const MS_PER_SECOND = 1000;
const SECS_PER_MIN = 60;
const SECS_PER_HOUR = SECS_PER_MIN * 60;
const SECS_PER_DAY = SECS_PER_HOUR * 24;
const SECS_PER_WEEK = SECS_PER_DAY * 7;
const THRESHOLDS = {
second: 60, // seconds to minute
minute: 60, // minutes to hour
hour: 24, // hour to day
day: 7, // day to week
};
export function timeSelectUnit(
from,
to = Date.now()
) {
const secs = (from.valueOf() - to.valueOf()) / MS_PER_SECOND;
if (Math.abs(secs) < THRESHOLDS.second) {
return [Math.round(secs), "second"];
}
const mins = secs / SECS_PER_MIN;
if (Math.abs(mins) < THRESHOLDS.minute) {
return [Math.round(mins), "minute"];
}
const hours = secs / SECS_PER_HOUR;
if (Math.abs(hours) < THRESHOLDS.hour) {
return [Math.round(hours), "hour"];
}
const days = secs / SECS_PER_DAY;
if (Math.abs(days) < THRESHOLDS.day) {
return [Math.round(days), "day"];
}
const fromDate = new Date(from);
const toDate = new Date(to);
const years = fromDate.getFullYear() - toDate.getFullYear();
if (Math.round(Math.abs(years)) > 0) {
return [Math.round(years), "year"];
}
const months = years * 12 + fromDate.getMonth() - toDate.getMonth();
if (Math.round(Math.abs(months)) > 0) {
return [Math.round(months), "month"];
}
const weeks = secs / SECS_PER_WEEK;
return [Math.round(weeks), "week"];
}
|
4f8e0469dd6fc21465c78955afb969ede13063de | 2,229 | ts | TypeScript | js-code/src/01-algorithm/continuous-char.ts | PeiyunBai/new-fe-interview-100 | a8ff266d20b781f82de59756a0b35726e5962169 | [
"MIT"
] | null | null | null | js-code/src/01-algorithm/continuous-char.ts | PeiyunBai/new-fe-interview-100 | a8ff266d20b781f82de59756a0b35726e5962169 | [
"MIT"
] | null | null | null | js-code/src/01-algorithm/continuous-char.ts | PeiyunBai/new-fe-interview-100 | a8ff266d20b781f82de59756a0b35726e5962169 | [
"MIT"
] | 2 | 2022-03-16T08:18:47.000Z | 2022-03-17T06:03:04.000Z | /**
* @description 连续字符
* @author 双越老师
*/
interface IRes {
char: string
length: number
}
/**
* 求连续最多的字符和次数(嵌套循环)
* @param str str
*/
export function findContinuousChar1(str: string): IRes {
const res: IRes = {
char: '',
length: 0
}
const length = str.length
if (length === 0) return res
let tempLength = 0 // 临时记录当前连续字符的长度
// O(n)
for (let i = 0; i < length; i++) {
tempLength = 0 // 重置
for (let j = i; j < length; j++) {
if (str[i] === str[j]) {
tempLength++
}
if (str[i] !== str[j] || j === length - 1) {
// 不相等,或者已经到了最后一个元素。要去判断最大值
if (tempLength > res.length) {
res.char = str[i]
res.length = tempLength
}
if (i < length - 1) {
i = j - 1 // 跳步
}
break
}
}
}
return res
}
/**
* 求连续最多的字符和次数(双指针)
* @param str str
*/
export function findContinuousChar2(str: string): IRes {
const res: IRes = {
char: '',
length: 0
}
const length = str.length
if (length === 0) return res
let tempLength = 0 // 临时记录当前连续字符的长度
let i = 0
let j = 0
// O(n)
for (; i < length; i++) {
if (str[i] === str[j]) {
tempLength++
}
if (str[i] !== str[j] || i === length - 1) {
// 不相等,或者 i 到了字符串的末尾
if (tempLength > res.length) {
res.char = str[j]
res.length = tempLength
}
tempLength = 0 // reset
if (i < length - 1) {
j = i // 让 j “追上” i
i-- // 细节
}
}
}
return res
}
// // 功能测试
// const str = 'aabbcccddeeee11223'
// console.info(findContinuousChar2(str))
// let str = ''
// for (let i = 0; i < 100 * 10000; i++) {
// str += i.toString()
// }
// console.time('findContinuousChar1')
// findContinuousChar1(str)
// console.timeEnd('findContinuousChar1') // 219ms
// console.time('findContinuousChar2')
// findContinuousChar2(str)
// console.timeEnd('findContinuousChar2') // 228ms
| 20.081081 | 56 | 0.45581 | 60 | 2 | 0 | 2 | 10 | 2 | 0 | 0 | 4 | 1 | 0 | 26 | 734 | 0.00545 | 0.013624 | 0.002725 | 0.001362 | 0 | 0 | 0.25 | 0.229253 | /**
* @description 连续字符
* @author 双越老师
*/
interface IRes {
char
length
}
/**
* 求连续最多的字符和次数(嵌套循环)
* @param str str
*/
export function findContinuousChar1(str) {
const res = {
char: '',
length: 0
}
const length = str.length
if (length === 0) return res
let tempLength = 0 // 临时记录当前连续字符的长度
// O(n)
for (let i = 0; i < length; i++) {
tempLength = 0 // 重置
for (let j = i; j < length; j++) {
if (str[i] === str[j]) {
tempLength++
}
if (str[i] !== str[j] || j === length - 1) {
// 不相等,或者已经到了最后一个元素。要去判断最大值
if (tempLength > res.length) {
res.char = str[i]
res.length = tempLength
}
if (i < length - 1) {
i = j - 1 // 跳步
}
break
}
}
}
return res
}
/**
* 求连续最多的字符和次数(双指针)
* @param str str
*/
export function findContinuousChar2(str) {
const res = {
char: '',
length: 0
}
const length = str.length
if (length === 0) return res
let tempLength = 0 // 临时记录当前连续字符的长度
let i = 0
let j = 0
// O(n)
for (; i < length; i++) {
if (str[i] === str[j]) {
tempLength++
}
if (str[i] !== str[j] || i === length - 1) {
// 不相等,或者 i 到了字符串的末尾
if (tempLength > res.length) {
res.char = str[j]
res.length = tempLength
}
tempLength = 0 // reset
if (i < length - 1) {
j = i // 让 j “追上” i
i-- // 细节
}
}
}
return res
}
// // 功能测试
// const str = 'aabbcccddeeee11223'
// console.info(findContinuousChar2(str))
// let str = ''
// for (let i = 0; i < 100 * 10000; i++) {
// str += i.toString()
// }
// console.time('findContinuousChar1')
// findContinuousChar1(str)
// console.timeEnd('findContinuousChar1') // 219ms
// console.time('findContinuousChar2')
// findContinuousChar2(str)
// console.timeEnd('findContinuousChar2') // 228ms
|
4ff4531a2948e347c16c60172974ed796b744007 | 4,898 | ts | TypeScript | src/vortex/UtilArray.ts | Synerty/vortexjs | 0d4e56f6d8d1b5938d4399abc7f0a1fa81accef6 | [
"MIT"
] | null | null | null | src/vortex/UtilArray.ts | Synerty/vortexjs | 0d4e56f6d8d1b5938d4399abc7f0a1fa81accef6 | [
"MIT"
] | 3 | 2022-02-13T20:45:55.000Z | 2022-02-27T10:34:30.000Z | src/vortex/UtilArray.ts | Synerty/vortexjs | 0d4e56f6d8d1b5938d4399abc7f0a1fa81accef6 | [
"MIT"
] | null | null | null | // Declare the TypeScript for Declaration Merging
// https://www.typescriptlang.org/docs/handbook/declaration-merging.html
interface Array<T> {
diff(a: Array<T>): Array<T>;
intersect(a: Array<T>): Array<T>;
remove(a: Array<T> | T): Array<T>;
add(a: Array<T> | T): Array<T>;
equals(array: Array<T> | null): boolean;
bubbleSort(compFunc: (
left: T,
right: T
) => number): Array<T>;
indexOf(item: T): number;
}
// Start the javascript type patching
if (Array.prototype.diff == null) {
Array.prototype.diff = function (a: Array<any>): Array<any> {
return this.filter(function (i: any) {
return !(a.indexOf(i) > -1)
})
}
}
if (Array.prototype.intersect == null) {
Array.prototype.intersect = function (a: Array<any>): Array<any> {
return this.filter(function (i) {
return (a.indexOf(i) > -1)
})
}
}
if (Array.prototype.remove == null) {
Array.prototype.remove = function (objectOrArray: Array<any> | any): Array<any> {
if (objectOrArray == null)
return this
if (objectOrArray instanceof Array) {
return this.diff(objectOrArray)
}
else {
let index = this.indexOf(objectOrArray)
if (index !== -1)
this.splice(index, 1)
return this
}
}
}
if (Array.prototype.add == null) {
Array.prototype.add = function (objectOrArray: Array<any> | any): Array<any> {
if (objectOrArray == null)
return this
// If for some reasons they are trying to add us to our self, throw an exception.
if (objectOrArray === this)
throw new Error("Array.add, I was passed myself, i can't add my self to myself.")
if (objectOrArray instanceof Array) {
for (let i = 0; i < objectOrArray.length; ++i)
this.push(objectOrArray[i])
return this
}
this.push(objectOrArray)
return this
}
}
if (Array.prototype.equals == null) {
Array.prototype.equals = function (array: Array<any> | null): boolean {
// if the other array is a false value, return
if (array == null)
return false
// compare object instances
if (this === array)
return true
// compare lengths - can save a lot of time
if (this.length !== array.length)
return false
for (let i = 0; i < this.length; i++) {
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].compare(array[i]))
return false
}
else if (this[i] !== array[i]) {
// Warning - two different object instances will never be equal: {x:20} !=
// {x:20}
return false
}
}
return true
}
}
if (Array.prototype.bubbleSort == null) {
Array.prototype.bubbleSort = function (compFunc: (
left: any,
right: any
) => number): Array<any> {
let self = this
function merge(
left,
right
) {
let result = []
while (left.length && right.length) {
if (compFunc(left[0], right[0]) <= 0) {
result.push(left.shift())
}
else {
result.push(right.shift())
}
}
while (left.length)
result.push(left.shift())
while (right.length)
result.push(right.shift())
return result
}
if (self.length < 2)
return self.slice(0, self.length)
let middle = parseInt((self.length / 2).toString())
let left = self.slice(0, middle)
let right = self.slice(middle, self.length)
return merge(left.bubbleSort(compFunc), right.bubbleSort(compFunc))
}
}
// ============================================================================
// Array.indexOf prptotype function
// Add if this browser (STUPID IE) doesn't support it
if (Array.prototype.indexOf == null) {
Array.prototype.indexOf = function (item: any): number {
let len = this.length >>> 0
let from = Number(arguments[1]) || 0
from = (from < 0) ? Math.ceil(from) : Math.floor(from)
if (from < 0)
from += len
for (; from < len; from++) {
if (from in this && this[from] === item)
return from
}
return -1
}
}
| 29.154762 | 93 | 0.492446 | 123 | 10 | 7 | 18 | 10 | 0 | 4 | 16 | 6 | 1 | 4 | 9.6 | 1,191 | 0.02351 | 0.008396 | 0 | 0.00084 | 0.003359 | 0.355556 | 0.133333 | 0.248537 | // Declare the TypeScript for Declaration Merging
// https://www.typescriptlang.org/docs/handbook/declaration-merging.html
interface Array<T> {
diff(a);
intersect(a);
remove(a);
add(a);
equals(array);
bubbleSort(compFunc);
indexOf(item);
}
// Start the javascript type patching
if (Array.prototype.diff == null) {
Array.prototype.diff = function (a) {
return this.filter(function (i) {
return !(a.indexOf(i) > -1)
})
}
}
if (Array.prototype.intersect == null) {
Array.prototype.intersect = function (a) {
return this.filter(function (i) {
return (a.indexOf(i) > -1)
})
}
}
if (Array.prototype.remove == null) {
Array.prototype.remove = function (objectOrArray) {
if (objectOrArray == null)
return this
if (objectOrArray instanceof Array) {
return this.diff(objectOrArray)
}
else {
let index = this.indexOf(objectOrArray)
if (index !== -1)
this.splice(index, 1)
return this
}
}
}
if (Array.prototype.add == null) {
Array.prototype.add = function (objectOrArray) {
if (objectOrArray == null)
return this
// If for some reasons they are trying to add us to our self, throw an exception.
if (objectOrArray === this)
throw new Error("Array.add, I was passed myself, i can't add my self to myself.")
if (objectOrArray instanceof Array) {
for (let i = 0; i < objectOrArray.length; ++i)
this.push(objectOrArray[i])
return this
}
this.push(objectOrArray)
return this
}
}
if (Array.prototype.equals == null) {
Array.prototype.equals = function (array) {
// if the other array is a false value, return
if (array == null)
return false
// compare object instances
if (this === array)
return true
// compare lengths - can save a lot of time
if (this.length !== array.length)
return false
for (let i = 0; i < this.length; i++) {
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].compare(array[i]))
return false
}
else if (this[i] !== array[i]) {
// Warning - two different object instances will never be equal: {x:20} !=
// {x:20}
return false
}
}
return true
}
}
if (Array.prototype.bubbleSort == null) {
Array.prototype.bubbleSort = function (compFunc) {
let self = this
/* Example usages of 'merge' are shown below:
merge(left.bubbleSort(compFunc), right.bubbleSort(compFunc));
*/
function merge(
left,
right
) {
let result = []
while (left.length && right.length) {
if (compFunc(left[0], right[0]) <= 0) {
result.push(left.shift())
}
else {
result.push(right.shift())
}
}
while (left.length)
result.push(left.shift())
while (right.length)
result.push(right.shift())
return result
}
if (self.length < 2)
return self.slice(0, self.length)
let middle = parseInt((self.length / 2).toString())
let left = self.slice(0, middle)
let right = self.slice(middle, self.length)
return merge(left.bubbleSort(compFunc), right.bubbleSort(compFunc))
}
}
// ============================================================================
// Array.indexOf prptotype function
// Add if this browser (STUPID IE) doesn't support it
if (Array.prototype.indexOf == null) {
Array.prototype.indexOf = function (item) {
let len = this.length >>> 0
let from = Number(arguments[1]) || 0
from = (from < 0) ? Math.ceil(from) : Math.floor(from)
if (from < 0)
from += len
for (; from < len; from++) {
if (from in this && this[from] === item)
return from
}
return -1
}
}
|
912bcee9d9b3cf98dedeb8a5ef90660fe5f4ef6d | 2,044 | ts | TypeScript | challenges/day8.ts | Ldoppea/advent-of-code-2020-typescript | 608c15619b9cae3bbc65d2d5d42455710d517221 | [
"MIT"
] | null | null | null | challenges/day8.ts | Ldoppea/advent-of-code-2020-typescript | 608c15619b9cae3bbc65d2d5d42455710d517221 | [
"MIT"
] | null | null | null | challenges/day8.ts | Ldoppea/advent-of-code-2020-typescript | 608c15619b9cae3bbc65d2d5d42455710d517221 | [
"MIT"
] | 1 | 2022-01-28T17:21:42.000Z | 2022-01-28T17:21:42.000Z | const ACC = 'acc';
const JMP = 'jmp';
const NOP = 'nop';
interface GameResult {
accumulator: number,
reachedEnd: boolean
}
interface GameInstruction {
hasBeenExecuted: boolean;
verb: string;
count: number;
}
const runGame = (instructions: GameInstruction[]): GameResult => {
let hasLooped = false;
let currentInstruction = 0;
let accumulator = 0;
while(!hasLooped && currentInstruction < instructions.length) {
const instruction = instructions[currentInstruction];
if(instruction.hasBeenExecuted) {
hasLooped = true;
} else {
instruction.hasBeenExecuted = true;
if (instruction.verb == ACC) {
accumulator += instruction.count;
currentInstruction += 1;
} else if (instruction.verb == JMP) {
currentInstruction += instruction.count;
} else {
currentInstruction += 1;
}
}
}
return {
accumulator,
reachedEnd: !hasLooped
};
}
const extratGameInstructions = (input: string[]): GameInstruction[] => {
return input.map(line => {
let [verb, count] = line.split(' ');
return {
hasBeenExecuted: false,
verb,
count: parseInt(count)
};
});
}
export function getAccumulatorValueAtLoop(input: string[]): number {
let instructions = extratGameInstructions(input);
return runGame(instructions).accumulator;
}
export function getAccumulatorValueAtEnd(input: string[]): number {
let currentReplacedIndex = 0
let reachedEnd = false;
let accumulator = 0;
while(!reachedEnd && currentReplacedIndex < input.length) {
let instructions = extratGameInstructions(input);
let currentInstruction = instructions[currentReplacedIndex];
if(currentInstruction.verb !== ACC && currentInstruction.count !== 0) {
currentInstruction.verb = currentInstruction.verb === NOP ? JMP : NOP;
const result = runGame(instructions);
reachedEnd = result.reachedEnd;
accumulator = result.accumulator;
}
currentReplacedIndex++;
}
return accumulator;
} | 23.767442 | 76 | 0.666341 | 68 | 5 | 0 | 5 | 17 | 5 | 2 | 0 | 10 | 2 | 0 | 10.8 | 500 | 0.02 | 0.034 | 0.01 | 0.004 | 0 | 0 | 0.3125 | 0.334522 | const ACC = 'acc';
const JMP = 'jmp';
const NOP = 'nop';
interface GameResult {
accumulator,
reachedEnd
}
interface GameInstruction {
hasBeenExecuted;
verb;
count;
}
/* Example usages of 'runGame' are shown below:
runGame(instructions).accumulator;
runGame(instructions);
*/
const runGame = (instructions) => {
let hasLooped = false;
let currentInstruction = 0;
let accumulator = 0;
while(!hasLooped && currentInstruction < instructions.length) {
const instruction = instructions[currentInstruction];
if(instruction.hasBeenExecuted) {
hasLooped = true;
} else {
instruction.hasBeenExecuted = true;
if (instruction.verb == ACC) {
accumulator += instruction.count;
currentInstruction += 1;
} else if (instruction.verb == JMP) {
currentInstruction += instruction.count;
} else {
currentInstruction += 1;
}
}
}
return {
accumulator,
reachedEnd: !hasLooped
};
}
/* Example usages of 'extratGameInstructions' are shown below:
extratGameInstructions(input);
*/
const extratGameInstructions = (input) => {
return input.map(line => {
let [verb, count] = line.split(' ');
return {
hasBeenExecuted: false,
verb,
count: parseInt(count)
};
});
}
export function getAccumulatorValueAtLoop(input) {
let instructions = extratGameInstructions(input);
return runGame(instructions).accumulator;
}
export function getAccumulatorValueAtEnd(input) {
let currentReplacedIndex = 0
let reachedEnd = false;
let accumulator = 0;
while(!reachedEnd && currentReplacedIndex < input.length) {
let instructions = extratGameInstructions(input);
let currentInstruction = instructions[currentReplacedIndex];
if(currentInstruction.verb !== ACC && currentInstruction.count !== 0) {
currentInstruction.verb = currentInstruction.verb === NOP ? JMP : NOP;
const result = runGame(instructions);
reachedEnd = result.reachedEnd;
accumulator = result.accumulator;
}
currentReplacedIndex++;
}
return accumulator;
} |
91554e5e0c36265a225da0fd691208ce4dc51000 | 4,885 | ts | TypeScript | src/ui-radar.ts | hai2007/grafana-panel-plugin-map | d0bade17d20be34e76e82e3d694b3f82a3d38c05 | [
"MIT"
] | 2 | 2022-01-25T16:49:14.000Z | 2022-01-26T02:54:44.000Z | src/ui-radar.ts | hai2007/grafana-panel-radar | d0bade17d20be34e76e82e3d694b3f82a3d38c05 | [
"MIT"
] | null | null | null | src/ui-radar.ts | hai2007/grafana-panel-radar | d0bade17d20be34e76e82e3d694b3f82a3d38c05 | [
"MIT"
] | null | null | null | /**
* 雷达图
*/
var initConfig = function (attr: any, that: any) {
if (attr.cx === null) {
attr.cx = that._width * 0.5;
}
if (attr.cy === null) {
attr.cy = that._height * 0.5;
}
if (attr.radius === null) {
attr.radius = that._min * 0.3;
}
};
export default [
'number',
'json',
'$rotate',
'$getLoopColors',
'color',
function ($number: any, $json: any, $rotate: any, $getLoopColors: any, $color: any) {
return {
attrs: {
// 圆心和半径
cx: $number(null)(true),
cy: $number(null)(true),
radius: $number(null)(true),
'font-color': $color()(true),
// 指示器
indicator: $json(),
// 数据
data: $json(),
},
region: {
default: function (render: any, attr: any) {
initConfig(attr, this);
var i,
j,
dot,
painter,
deg = (Math.PI * 2) / attr.indicator.length;
for (j = 0; j < attr.data.length; j++) {
painter = render(j, attr.data[j]).beginPath();
for (i = 0; i < attr.indicator.length; i++) {
dot = $rotate(
attr.cx,
attr.cy,
deg * i,
attr.cx,
attr.cy - (attr.data[j].value[i] / attr.indicator[i].max) * attr.radius
);
painter.lineTo(dot[0], dot[1]);
}
painter.closePath().full();
}
},
},
link: function (painter: any, attr: any) {
initConfig(attr, this);
var i, j, dot, textAlign;
var deg = (Math.PI * 2) / attr.indicator.length;
var dist = attr.radius * 0.2;
painter.config({
strokeStyle: '#eaeef5',
});
// 绘制背景
for (j = 5; j > 0; j--) {
// 外到内
painter.config('fillStyle', j % 2 === 0 ? 'white' : '#f5f7fb').beginPath();
for (i = 0; i < attr.indicator.length; i++) {
// 旋转
dot = $rotate(attr.cx, attr.cy, deg * i, attr.cx, attr.cy - dist * j);
painter.lineTo(dot[0], dot[1]);
}
painter.closePath().full();
}
painter.config({
fillStyle: attr['font-color'],
'font-size': 10,
});
// 绘制背景线条
for (i = 0; i < attr.indicator.length; i++) {
dot = $rotate(attr.cx, attr.cy, deg * i, attr.cx, attr.cy - attr.radius);
painter.beginPath().moveTo(attr.cx, attr.cy).lineTo(dot[0], dot[1]).stroke();
if (i === 0 || i === attr.indicator.length * 0.5) {
textAlign = 'center';
} else if (i > attr.indicator.length * 0.5) {
textAlign = 'right';
} else {
textAlign = 'left';
}
// 文字
dot = $rotate(attr.cx, attr.cy, deg * i, attr.cx, attr.cy - attr.radius - 10);
painter
.config({
textAlign: textAlign,
})
.fillText(attr.indicator[i].name, dot[0], dot[1]);
}
// 绘制数据
var colors = $getLoopColors(attr.data.length);
var colorsAlpha = $getLoopColors(attr.data.length, 0.7);
for (j = 0; j < attr.data.length; j++) {
painter
.config({
strokeStyle: colors[j],
fillStyle: colorsAlpha[j],
})
.beginPath();
for (i = 0; i < attr.indicator.length; i++) {
dot = $rotate(
attr.cx,
attr.cy,
deg * i,
attr.cx,
attr.cy - (attr.data[j].value[i] / attr.indicator[i].max) * attr.radius
);
painter.lineTo(dot[0], dot[1]);
}
painter.closePath().full();
}
},
};
},
];
| 33.923611 | 103 | 0.341863 | 113 | 4 | 0 | 11 | 14 | 0 | 1 | 11 | 0 | 0 | 0 | 44.75 | 1,096 | 0.013686 | 0.012774 | 0 | 0 | 0 | 0.37931 | 0 | 0.238189 | /**
* 雷达图
*/
/* Example usages of 'initConfig' are shown below:
initConfig(attr, this);
*/
var initConfig = function (attr, that) {
if (attr.cx === null) {
attr.cx = that._width * 0.5;
}
if (attr.cy === null) {
attr.cy = that._height * 0.5;
}
if (attr.radius === null) {
attr.radius = that._min * 0.3;
}
};
export default [
'number',
'json',
'$rotate',
'$getLoopColors',
'color',
function ($number, $json, $rotate, $getLoopColors, $color) {
return {
attrs: {
// 圆心和半径
cx: $number(null)(true),
cy: $number(null)(true),
radius: $number(null)(true),
'font-color': $color()(true),
// 指示器
indicator: $json(),
// 数据
data: $json(),
},
region: {
default: function (render, attr) {
initConfig(attr, this);
var i,
j,
dot,
painter,
deg = (Math.PI * 2) / attr.indicator.length;
for (j = 0; j < attr.data.length; j++) {
painter = render(j, attr.data[j]).beginPath();
for (i = 0; i < attr.indicator.length; i++) {
dot = $rotate(
attr.cx,
attr.cy,
deg * i,
attr.cx,
attr.cy - (attr.data[j].value[i] / attr.indicator[i].max) * attr.radius
);
painter.lineTo(dot[0], dot[1]);
}
painter.closePath().full();
}
},
},
link: function (painter, attr) {
initConfig(attr, this);
var i, j, dot, textAlign;
var deg = (Math.PI * 2) / attr.indicator.length;
var dist = attr.radius * 0.2;
painter.config({
strokeStyle: '#eaeef5',
});
// 绘制背景
for (j = 5; j > 0; j--) {
// 外到内
painter.config('fillStyle', j % 2 === 0 ? 'white' : '#f5f7fb').beginPath();
for (i = 0; i < attr.indicator.length; i++) {
// 旋转
dot = $rotate(attr.cx, attr.cy, deg * i, attr.cx, attr.cy - dist * j);
painter.lineTo(dot[0], dot[1]);
}
painter.closePath().full();
}
painter.config({
fillStyle: attr['font-color'],
'font-size': 10,
});
// 绘制背景线条
for (i = 0; i < attr.indicator.length; i++) {
dot = $rotate(attr.cx, attr.cy, deg * i, attr.cx, attr.cy - attr.radius);
painter.beginPath().moveTo(attr.cx, attr.cy).lineTo(dot[0], dot[1]).stroke();
if (i === 0 || i === attr.indicator.length * 0.5) {
textAlign = 'center';
} else if (i > attr.indicator.length * 0.5) {
textAlign = 'right';
} else {
textAlign = 'left';
}
// 文字
dot = $rotate(attr.cx, attr.cy, deg * i, attr.cx, attr.cy - attr.radius - 10);
painter
.config({
textAlign: textAlign,
})
.fillText(attr.indicator[i].name, dot[0], dot[1]);
}
// 绘制数据
var colors = $getLoopColors(attr.data.length);
var colorsAlpha = $getLoopColors(attr.data.length, 0.7);
for (j = 0; j < attr.data.length; j++) {
painter
.config({
strokeStyle: colors[j],
fillStyle: colorsAlpha[j],
})
.beginPath();
for (i = 0; i < attr.indicator.length; i++) {
dot = $rotate(
attr.cx,
attr.cy,
deg * i,
attr.cx,
attr.cy - (attr.data[j].value[i] / attr.indicator[i].max) * attr.radius
);
painter.lineTo(dot[0], dot[1]);
}
painter.closePath().full();
}
},
};
},
];
|
9180a15f95cb4dab686f4c84bc592617a389d299 | 2,455 | ts | TypeScript | packages/snap-preact-components/src/utilities/sprintf.ts | searchspring/snap | 050a3e8e94678c61db77c597e20bab6e9492bc4f | [
"MIT"
] | 4 | 2022-02-10T20:10:47.000Z | 2022-03-16T15:12:33.000Z | packages/snap-preact-components/src/utilities/sprintf.ts | searchspring/snap | 050a3e8e94678c61db77c597e20bab6e9492bc4f | [
"MIT"
] | 86 | 2022-02-01T20:51:18.000Z | 2022-03-31T21:20:13.000Z | packages/snap-preact-components/src/utilities/sprintf.ts | searchspring/snap | 050a3e8e94678c61db77c597e20bab6e9492bc4f | [
"MIT"
] | null | null | null | /**
* sprintf() for JavaScript v.0.4
*
* Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
* Thanks to David Baird (unit test and patch).
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*eslint-disable */
function str_repeat(i, m) {
for (var o = []; m > 0; o[--m] = i);
return o.join('');
}
export function sprintf(...args: any[]) {
var i = 0,
a,
f = args[i++],
o = [],
m,
p,
c,
x;
while (f) {
if ((m = /^[^\x25]+/.exec(f))) o.push(m[0]);
else if ((m = /^\x25{2}/.exec(f))) o.push('%');
else if ((m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f))) {
if ((a = args[m[1] || i++]) == null || a == undefined) throw 'Too few arguments.';
if (/[^s]/.test(m[7]) && typeof a != 'number') throw 'Expecting number but found ' + typeof a;
switch (m[7]) {
case 'b':
a = a.toString(2);
break;
case 'c':
a = String.fromCharCode(a);
break;
case 'd':
a = parseInt(a);
break;
case 'e':
a = m[6] ? a.toExponential(m[6]) : a.toExponential();
break;
case 'f':
a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a);
break;
case 'o':
a = a.toString(8);
break;
case 's':
a = (a = String(a)) && m[6] ? a.substring(0, m[6]) : a;
break;
case 'u':
a = Math.abs(a);
break;
case 'x':
a = a.toString(16);
break;
case 'X':
a = a.toString(16).toUpperCase();
break;
}
a = /[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a;
c = m[3] ? (m[3] == '0' ? '0' : m[3].charAt(1)) : ' ';
x = m[5] - String(a).length;
p = m[5] ? str_repeat(c, x) : '';
o.push(m[4] ? a + p : p + a);
} else throw 'Huh ?!';
f = f.substring(m[0].length);
}
return o.join('');
}
/*eslint-enable */
| 27.897727 | 97 | 0.545825 | 61 | 2 | 0 | 3 | 9 | 0 | 1 | 1 | 0 | 0 | 2 | 28.5 | 932 | 0.005365 | 0.009657 | 0 | 0 | 0.002146 | 0.071429 | 0 | 0.213018 | /**
* sprintf() for JavaScript v.0.4
*
* Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
* Thanks to David Baird (unit test and patch).
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*eslint-disable */
/* Example usages of 'str_repeat' are shown below:
p = m[5] ? str_repeat(c, x) : '';
*/
function str_repeat(i, m) {
for (var o = []; m > 0; o[--m] = i);
return o.join('');
}
export function sprintf(...args) {
var i = 0,
a,
f = args[i++],
o = [],
m,
p,
c,
x;
while (f) {
if ((m = /^[^\x25]+/.exec(f))) o.push(m[0]);
else if ((m = /^\x25{2}/.exec(f))) o.push('%');
else if ((m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f))) {
if ((a = args[m[1] || i++]) == null || a == undefined) throw 'Too few arguments.';
if (/[^s]/.test(m[7]) && typeof a != 'number') throw 'Expecting number but found ' + typeof a;
switch (m[7]) {
case 'b':
a = a.toString(2);
break;
case 'c':
a = String.fromCharCode(a);
break;
case 'd':
a = parseInt(a);
break;
case 'e':
a = m[6] ? a.toExponential(m[6]) : a.toExponential();
break;
case 'f':
a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a);
break;
case 'o':
a = a.toString(8);
break;
case 's':
a = (a = String(a)) && m[6] ? a.substring(0, m[6]) : a;
break;
case 'u':
a = Math.abs(a);
break;
case 'x':
a = a.toString(16);
break;
case 'X':
a = a.toString(16).toUpperCase();
break;
}
a = /[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a;
c = m[3] ? (m[3] == '0' ? '0' : m[3].charAt(1)) : ' ';
x = m[5] - String(a).length;
p = m[5] ? str_repeat(c, x) : '';
o.push(m[4] ? a + p : p + a);
} else throw 'Huh ?!';
f = f.substring(m[0].length);
}
return o.join('');
}
/*eslint-enable */
|
91da249cc7a179b9ae872e0553da8a47b6168d08 | 2,021 | ts | TypeScript | src/java/util/PriorityQueue.ts | carl-zk/java-like-lib-ts | f6b1dc7bb5abd85f33983c99d497633f8c486348 | [
"MIT"
] | 2 | 2022-03-21T07:12:03.000Z | 2022-03-21T14:34:29.000Z | src/java/util/PriorityQueue.ts | carl-zk/java-like-lib-ts | f6b1dc7bb5abd85f33983c99d497633f8c486348 | [
"MIT"
] | null | null | null | src/java/util/PriorityQueue.ts | carl-zk/java-like-lib-ts | f6b1dc7bb5abd85f33983c99d497633f8c486348 | [
"MIT"
] | null | null | null | export default class PriorityQueue<E> {
private queue: E[];
private _size: number;
private comparator: (u: E, v: E) => number;
constructor(comparator: (u: E, v: E) => number) {
this.comparator = comparator;
this.queue = [];
this._size = 0;
}
public push(e: E): void {
this.queue.push(e);
this._size++;
this.shiftUp(this.parentIndex(this._size));
}
private parentIndex(i: number): number {
return i > 0 ? (i - 1) >> 1 : -1;
}
private leftChildIndex(i: number): number {
return (i << 1) + 1;
}
private rightChildIndex(i: number): number {
return (i + 1) << 1;
}
private shiftUp(i: number): void {
if (i < 0) {
return;
}
let l = this.leftChildIndex(i),
r = this.rightChildIndex(i);
let j;
if (l < this._size && r < this._size) {
j = this.comparator(this.queue[l], this.queue[r]) < 0 ? l : r;
} else if (l < this._size) {
j = l;
} else {
j = r;
}
if (j < this._size && this.comparator(this.queue[j], this.queue[i]) < 0) {
this.swap(i, j);
this.shiftUp(this.parentIndex(i));
}
}
public poll(): E {
if (this.isEmpty()) {
return null;
}
this.swap(0, this._size - 1);
let v = this.queue.pop();
this._size--;
this.shiftDown(0);
return v;
}
private shiftDown(i: number): void {
if (i >= this._size) {
return;
}
let l = this.leftChildIndex(i),
r = this.rightChildIndex(i);
let j;
if (l < this._size && r < this._size) {
j = this.comparator(this.queue[l], this.queue[r]) < 0 ? l : r;
} else if (l < this._size) {
j = l;
} else {
j = r;
}
if (j < this._size && this.comparator(this.queue[j], this.queue[i]) < 0) {
this.swap(i, j);
this.shiftDown(j);
}
}
public isEmpty(): boolean {
return this._size == 0;
}
private swap(i: number, j: number): void {
let x = this.queue[i];
this.queue[i] = this.queue[j];
this.queue[j] = x;
}
}
| 22.208791 | 78 | 0.53241 | 80 | 10 | 0 | 9 | 8 | 3 | 8 | 0 | 18 | 1 | 0 | 5.5 | 691 | 0.027496 | 0.011577 | 0.004342 | 0.001447 | 0 | 0 | 0.6 | 0.275813 | export default class PriorityQueue<E> {
private queue;
private _size;
private comparator;
constructor(comparator) {
this.comparator = comparator;
this.queue = [];
this._size = 0;
}
public push(e) {
this.queue.push(e);
this._size++;
this.shiftUp(this.parentIndex(this._size));
}
private parentIndex(i) {
return i > 0 ? (i - 1) >> 1 : -1;
}
private leftChildIndex(i) {
return (i << 1) + 1;
}
private rightChildIndex(i) {
return (i + 1) << 1;
}
private shiftUp(i) {
if (i < 0) {
return;
}
let l = this.leftChildIndex(i),
r = this.rightChildIndex(i);
let j;
if (l < this._size && r < this._size) {
j = this.comparator(this.queue[l], this.queue[r]) < 0 ? l : r;
} else if (l < this._size) {
j = l;
} else {
j = r;
}
if (j < this._size && this.comparator(this.queue[j], this.queue[i]) < 0) {
this.swap(i, j);
this.shiftUp(this.parentIndex(i));
}
}
public poll() {
if (this.isEmpty()) {
return null;
}
this.swap(0, this._size - 1);
let v = this.queue.pop();
this._size--;
this.shiftDown(0);
return v;
}
private shiftDown(i) {
if (i >= this._size) {
return;
}
let l = this.leftChildIndex(i),
r = this.rightChildIndex(i);
let j;
if (l < this._size && r < this._size) {
j = this.comparator(this.queue[l], this.queue[r]) < 0 ? l : r;
} else if (l < this._size) {
j = l;
} else {
j = r;
}
if (j < this._size && this.comparator(this.queue[j], this.queue[i]) < 0) {
this.swap(i, j);
this.shiftDown(j);
}
}
public isEmpty() {
return this._size == 0;
}
private swap(i, j) {
let x = this.queue[i];
this.queue[i] = this.queue[j];
this.queue[j] = x;
}
}
|
e122e36be1673b2260622c3fcf602d300d5e922e | 3,289 | ts | TypeScript | problemset/divide-two-integers/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/divide-two-integers/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/divide-two-integers/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 二分法
* @desc 时间复杂度 O(logC ^ 2) 空间复杂度 O(logC)
* @param dividend {number} 被除数
* @param divisor {number} 除数
* @return {number}
*/
export function divide(dividend: number, divisor: number): number {
// 考虑边缘情况
const { isEdgeCage, value } = edgeCaseHandle(dividend, divisor)
if (isEdgeCage) return value
// 将除数和被除数都变成负数
let rev = false // 判断是否转变过
if (dividend > 0) {
dividend = -dividend
rev = !rev
}
if (divisor > 0) {
divisor = -divisor
rev = !rev
}
const MAX_VALUE: number = 2 ** 31 - 1
let left = 1
let right: number = MAX_VALUE
let ans = 0
while (left <= right) {
// 取中间值
const mid: number = left + ((right - left) >> 1) /* 除以2,向下取整 */
// 判断 divisor * mid 是否大于等于dividend
const check: boolean = quickAdd(divisor, mid, dividend)
if (check) {
ans = mid
// 边缘检测
if (mid === MAX_VALUE)
break
left = mid + 1
}
else {
right = mid - 1
}
}
return rev ? -ans : ans
/**
* 快速乘
* @desc 判断 y * z 是否大于等于 x
* @param y {number} 负数
* @param z {number} 正数
* @param x {number} 负数
* @return {boolean}
*/
function quickAdd(y: number, z: number, x: number): boolean {
let result = 0
let add: number = y
while (z !== 0) {
// 如果z是奇数的话,result += add
if ((z & 1) !== 0) {
// z & 1 判断奇偶数,0 -> 偶数;1 -> 奇数
// result + add >= x
if (result < x - add)
return false
result += add
}
if (z !== 1) {
// add + add >= x
if (add < x - add)
return false
add += add
}
// z除以2,向下取整
z >>= 1 // z = z / (2^1) -> z = z / 2
}
return true
}
}
/**
* 类二分法
* @desc 时间复杂度 O(logC) 空间复杂度 O(logC)
* @param dividend {number} 被除数
* @param divisor {number} 除数
* @return {number}
*/
export function divide2(dividend: number, divisor: number): number {
// 考虑边缘情况
const { isEdgeCage, value } = edgeCaseHandle(dividend, divisor)
if (isEdgeCage) return value
// 将除数和被除数都变成负数
let rev = false // 判断是否转变过
if (dividend < 0) {
dividend = -dividend
rev = !rev
}
if (divisor < 0) {
divisor = -divisor
rev = !rev
}
const candidates: number[] = [divisor]
let idx = 0
while (candidates[idx] <= dividend - candidates[idx]) {
candidates.push(candidates[idx] + candidates[idx])
idx++
}
let ans = 0
for (let i = candidates.length - 1; i >= 0; i--) {
if (candidates[i] <= dividend) {
ans += 1 << i /* 2^i */
dividend -= candidates[i]
}
}
return rev ? -ans : ans
}
/**
* 边缘情况检测
* @param dividend {number} 被除数
* @param divisor {number} 除数
*/
function edgeCaseHandle(
dividend: number,
divisor: number,
): { isEdgeCage: boolean; value: number } {
const MAX_VALUE: number = 2 ** 31 - 1
const MIN_VALUE: number = -(2 ** 31)
// 考虑被除数为最小值的情况
if (dividend === MIN_VALUE) {
if (divisor === 1) return { isEdgeCage: true, value: MIN_VALUE }
if (divisor === -1) return { isEdgeCage: true, value: MAX_VALUE }
}
// 考虑除数为最小值的情况
if (divisor === MIN_VALUE)
return { isEdgeCage: true, value: dividend === MIN_VALUE ? 1 : 0 }
// 考虑被除数为 0 的情况
if (dividend === 0) return { isEdgeCage: true, value: 0 }
return { isEdgeCage: false, value: NaN }
}
| 21.496732 | 70 | 0.550319 | 91 | 4 | 0 | 9 | 18 | 0 | 2 | 0 | 22 | 0 | 0 | 24.5 | 1,222 | 0.010638 | 0.01473 | 0 | 0 | 0 | 0 | 0.709677 | 0.24273 | /**
* 二分法
* @desc 时间复杂度 O(logC ^ 2) 空间复杂度 O(logC)
* @param dividend {number} 被除数
* @param divisor {number} 除数
* @return {number}
*/
export function divide(dividend, divisor) {
// 考虑边缘情况
const { isEdgeCage, value } = edgeCaseHandle(dividend, divisor)
if (isEdgeCage) return value
// 将除数和被除数都变成负数
let rev = false // 判断是否转变过
if (dividend > 0) {
dividend = -dividend
rev = !rev
}
if (divisor > 0) {
divisor = -divisor
rev = !rev
}
const MAX_VALUE = 2 ** 31 - 1
let left = 1
let right = MAX_VALUE
let ans = 0
while (left <= right) {
// 取中间值
const mid = left + ((right - left) >> 1) /* 除以2,向下取整 */
// 判断 divisor * mid 是否大于等于dividend
const check = quickAdd(divisor, mid, dividend)
if (check) {
ans = mid
// 边缘检测
if (mid === MAX_VALUE)
break
left = mid + 1
}
else {
right = mid - 1
}
}
return rev ? -ans : ans
/**
* 快速乘
* @desc 判断 y * z 是否大于等于 x
* @param y {number} 负数
* @param z {number} 正数
* @param x {number} 负数
* @return {boolean}
*/
/* Example usages of 'quickAdd' are shown below:
quickAdd(divisor, mid, dividend);
*/
function quickAdd(y, z, x) {
let result = 0
let add = y
while (z !== 0) {
// 如果z是奇数的话,result += add
if ((z & 1) !== 0) {
// z & 1 判断奇偶数,0 -> 偶数;1 -> 奇数
// result + add >= x
if (result < x - add)
return false
result += add
}
if (z !== 1) {
// add + add >= x
if (add < x - add)
return false
add += add
}
// z除以2,向下取整
z >>= 1 // z = z / (2^1) -> z = z / 2
}
return true
}
}
/**
* 类二分法
* @desc 时间复杂度 O(logC) 空间复杂度 O(logC)
* @param dividend {number} 被除数
* @param divisor {number} 除数
* @return {number}
*/
export function divide2(dividend, divisor) {
// 考虑边缘情况
const { isEdgeCage, value } = edgeCaseHandle(dividend, divisor)
if (isEdgeCage) return value
// 将除数和被除数都变成负数
let rev = false // 判断是否转变过
if (dividend < 0) {
dividend = -dividend
rev = !rev
}
if (divisor < 0) {
divisor = -divisor
rev = !rev
}
const candidates = [divisor]
let idx = 0
while (candidates[idx] <= dividend - candidates[idx]) {
candidates.push(candidates[idx] + candidates[idx])
idx++
}
let ans = 0
for (let i = candidates.length - 1; i >= 0; i--) {
if (candidates[i] <= dividend) {
ans += 1 << i /* 2^i */
dividend -= candidates[i]
}
}
return rev ? -ans : ans
}
/**
* 边缘情况检测
* @param dividend {number} 被除数
* @param divisor {number} 除数
*/
/* Example usages of 'edgeCaseHandle' are shown below:
edgeCaseHandle(dividend, divisor);
*/
function edgeCaseHandle(
dividend,
divisor,
) {
const MAX_VALUE = 2 ** 31 - 1
const MIN_VALUE = -(2 ** 31)
// 考虑被除数为最小值的情况
if (dividend === MIN_VALUE) {
if (divisor === 1) return { isEdgeCage: true, value: MIN_VALUE }
if (divisor === -1) return { isEdgeCage: true, value: MAX_VALUE }
}
// 考虑除数为最小值的情况
if (divisor === MIN_VALUE)
return { isEdgeCage: true, value: dividend === MIN_VALUE ? 1 : 0 }
// 考虑被除数为 0 的情况
if (dividend === 0) return { isEdgeCage: true, value: 0 }
return { isEdgeCage: false, value: NaN }
}
|
e1dfc6aae1d96a433899960780c2c7e265ab33da | 1,821 | ts | TypeScript | config/mail/email.ts | EC-Nordbund/deno-smtp | c2ecd167b90b885eac8dbff662c4fa29095c57b8 | [
"MIT"
] | 7 | 2022-02-04T00:59:44.000Z | 2022-03-31T09:12:18.000Z | config/mail/email.ts | EC-Nordbund/deno-smtp | c2ecd167b90b885eac8dbff662c4fa29095c57b8 | [
"MIT"
] | 5 | 2022-02-15T20:25:12.000Z | 2022-03-30T10:24:51.000Z | config/mail/email.ts | EC-Nordbund/deno-smtp | c2ecd167b90b885eac8dbff662c4fa29095c57b8 | [
"MIT"
] | 3 | 2022-02-10T08:55:04.000Z | 2022-03-30T08:44:13.000Z | export interface mailObject {
mail: string;
name?: string;
}
export interface saveMailObject {
mail: string;
name: string;
}
type singleMail = string | mailObject;
type mailListObject = Omit<Record<string, string>, "name" | "mail">;
export type mailList =
| mailListObject
| singleMail
| singleMail[]
| mailObject[];
export function isSingleMail(mail: string) {
return /^(([^<>()\[\]\\,;:\s@"]+@[a-zA-Z0-9\-]+\.([a-zA-Z0-9\-]+\.)*[a-zA-Z]{2,})|(<[^<>()\[\]\\,;:\s@"]+@[a-zA-Z0-9]+\.([a-zA-Z0-9\-]+\.)*[a-zA-Z]{2,}>)|([^<>]+ <[^<>()\[\]\\,;:\s@"]+@[a-zA-Z0-9]+\.([a-zA-Z0-9\-]+\.)*[a-zA-Z]{2,}>))$/
.test(mail);
}
export function parseSingleEmail(mail: singleMail): saveMailObject {
if (typeof mail !== "string") {
return {
mail: mail.mail,
name: mail.name ?? "",
};
}
const mailSplitRe = /^([^<]*)<([^>]+)>\s*$/;
const res = mailSplitRe.exec(mail);
if (!res) {
return {
mail,
name: "",
};
}
const [_, name, email] = res;
return {
name: name.trim(),
mail: email.trim(),
};
}
export function parseMailList(list: mailList): saveMailObject[] {
if (typeof list === "string") return [parseSingleEmail(list)];
if (Array.isArray(list)) return list.map((v) => parseSingleEmail(v));
if ("mail" in list) {
return [{
mail: list.mail,
name: list.name ?? "",
}];
}
return Object.entries(list as mailListObject).map(([name, mail]) => ({
name,
mail,
}));
}
export function validateEmailList(
list: saveMailObject[],
): { ok: saveMailObject[]; bad: saveMailObject[] } {
const ok: saveMailObject[] = [];
const bad: saveMailObject[] = [];
list.forEach((mail) => {
if (isSingleMail(mail.mail)) {
ok.push(mail);
} else {
bad.push(mail);
}
});
return { ok, bad };
}
| 22.207317 | 237 | 0.549149 | 68 | 7 | 0 | 7 | 5 | 4 | 2 | 0 | 8 | 5 | 3 | 7.571429 | 625 | 0.0224 | 0.008 | 0.0064 | 0.008 | 0.0048 | 0 | 0.347826 | 0.260842 | export interface mailObject {
mail;
name?;
}
export interface saveMailObject {
mail;
name;
}
type singleMail = string | mailObject;
type mailListObject = Omit<Record<string, string>, "name" | "mail">;
export type mailList =
| mailListObject
| singleMail
| singleMail[]
| mailObject[];
export /* Example usages of 'isSingleMail' are shown below:
isSingleMail(mail.mail);
*/
function isSingleMail(mail) {
return /^(([^<>()\[\]\\,;:\s@"]+@[a-zA-Z0-9\-]+\.([a-zA-Z0-9\-]+\.)*[a-zA-Z]{2,})|(<[^<>()\[\]\\,;:\s@"]+@[a-zA-Z0-9]+\.([a-zA-Z0-9\-]+\.)*[a-zA-Z]{2,}>)|([^<>]+ <[^<>()\[\]\\,;:\s@"]+@[a-zA-Z0-9]+\.([a-zA-Z0-9\-]+\.)*[a-zA-Z]{2,}>))$/
.test(mail);
}
export /* Example usages of 'parseSingleEmail' are shown below:
parseSingleEmail(list);
parseSingleEmail(v);
*/
function parseSingleEmail(mail) {
if (typeof mail !== "string") {
return {
mail: mail.mail,
name: mail.name ?? "",
};
}
const mailSplitRe = /^([^<]*)<([^>]+)>\s*$/;
const res = mailSplitRe.exec(mail);
if (!res) {
return {
mail,
name: "",
};
}
const [_, name, email] = res;
return {
name: name.trim(),
mail: email.trim(),
};
}
export function parseMailList(list) {
if (typeof list === "string") return [parseSingleEmail(list)];
if (Array.isArray(list)) return list.map((v) => parseSingleEmail(v));
if ("mail" in list) {
return [{
mail: list.mail,
name: list.name ?? "",
}];
}
return Object.entries(list as mailListObject).map(([name, mail]) => ({
name,
mail,
}));
}
export function validateEmailList(
list,
) {
const ok = [];
const bad = [];
list.forEach((mail) => {
if (isSingleMail(mail.mail)) {
ok.push(mail);
} else {
bad.push(mail);
}
});
return { ok, bad };
}
|
818a2300376cab79a024aa225b6f0e82d422faf1 | 5,406 | ts | TypeScript | src/components/date-picker/src/utils/index.ts | Luoyangs/yoga-ui | eab20e4a4dbe6e7841d85c66143ca271a1bf11ec | [
"MIT"
] | null | null | null | src/components/date-picker/src/utils/index.ts | Luoyangs/yoga-ui | eab20e4a4dbe6e7841d85c66143ca271a1bf11ec | [
"MIT"
] | null | null | null | src/components/date-picker/src/utils/index.ts | Luoyangs/yoga-ui | eab20e4a4dbe6e7841d85c66143ca271a1bf11ec | [
"MIT"
] | 1 | 2022-01-05T07:53:37.000Z | 2022-01-05T07:53:37.000Z | /**
* 获取传入月份的上个月
* @param year number
* @param month number
* @returns { year: number; month: number }
*/
export const getLastMonth = (year: number, month: number): { year: number; month: number } => {
if (month === 0) {
return {
year: year - 1,
month: 11,
};
}
return {
year,
month: month - 1,
};
};
/**
* 获取传入月的下个月
* @param year number
* @param month number
* @returns { year: number; month: number }
*/
export const getNextMonth = (year: number, month: number): { year: number; month: number } => {
if (month === 11) {
return {
year: year + 1,
month: 0,
};
}
return {
year,
month: month + 1,
};
};
/**
* 判断传入的年份是否是闰年
* @param year number
* @returns boolean
*/
const isLeap = (year: number): boolean => {
return (year % 4 === 0 && year % 100 === 0) || year % 400 === 0;
};
/**
* 获取传入年所在月的最大天数
* @param year number
* @param month number
* @returns number
*/
export const getMaxDayNumOfYearMonth = (year: number, month: number): number => {
switch (month) {
case 0:
case 2:
case 4:
case 6:
case 7:
case 9:
case 11:
return 31;
case 1:
return isLeap(year) ? 29 : 28;
default:
return 30;
}
};
/**
* 获取指定年所在月的第一天是星期几
* 返回一个0到6之间的整数值,代表星期几: 0 代表星期日
* @param year number
* @param month number
* @returns number
*/
export const getFirstDayOfYearMonth = (year: number, month: number): number => {
const date = new Date(year, month, 1);
return date.getDay();
};
const PER_DAY_MILLISECONDS = 86400000; // 24 * 60 * 60 * 1000
/**
* 获取指定年所在月的第一天
* @param year number
* @param month number
* @param startOfWeek number 一周是从周几开始,传值0~6,0表示周日
* @returns Date
*/
export const getStartDateOfCalendar = (year: number, month: number, startOfWeek: number = 0): Date => {
const date = new Date(year, month, 1);
const day = date.getDay();
date.setTime(date.getTime() - PER_DAY_MILLISECONDS * ((day - startOfWeek + 7) % 7));
return date;
};
export interface MonthItem {
year: number;
month: number;
}
/**
* 比较两个月的大小
* @param a MonthItem
* @param b MonthItem
* @returns number
*/
export const compareMonth = (a: MonthItem, b: MonthItem): number => {
if (a.year === b.year) {
if (a.month === b.month) {
return 0;
}
return a.month > b.month ? 1 : -1;
}
return a.year > b.year ? 1 : -1;
};
/**
* 比较两个日期大小
* @param a Date
* @param b Date
* @returns number 0 means same date, 1 means a > b
*/
export const compareDate = (a: Date, b: Date): number => {
const aYear = a.getFullYear();
const aMonth = a.getMonth();
const aDate = a.getDate();
const bYear = b.getFullYear();
const bMonth = b.getMonth();
const bDate = b.getDate();
if (aYear === bYear) {
if (aMonth === bMonth) {
if (aDate === bDate) {
return 0;
}
return aDate > bDate ? 1 : -1;
}
return aMonth > bMonth ? 1 : -1;
}
return aYear > bYear ? 1 : -1;
};
/**
* 判断是否是同一天
* @param a Date
* @param b Date
* @returns boolean
*/
export const isSameDay = (a: Date, b: Date): boolean => {
if (!a || !b) {
return false;
}
return compareDate(a, b) === 0;
};
/**
* 判断日期是否在所给的列表中
* @param date Date
* @param days Date[]
* @returns boolean
*/
export const isInRange = (date: Date, days: Date[]): boolean => {
if (!date || !days) {
return false;
}
return days.some((day) => isSameDay(day, date));
};
/**
* 判断给定的日期是否在两个日期之间
* @param date Date
* @param start Date
* @param end Date
* @param include boolean 是否包含等于
* @returns boolean
*/
export const isInRange2 = (date: Date, start: Date, end: Date, include: boolean = false): boolean => {
if (!date || !start || !end) {
return false;
}
let startDate = start;
let endDate = end;
if (start > end) {
startDate = end;
endDate = start;
}
return include
? compareDate(date, startDate) >= 0 && compareDate(date, endDate) <= 0
: compareDate(date, startDate) > 0 && compareDate(date, endDate) < 0;
};
export interface YearRange {
start: number;
end: number;
}
/**
* 获取指定年的10年间起始的年,如2021 => [2020, 2029]
* @param year number
* @returns YearRange
*/
export const getYearRange = (year?: number): YearRange => {
const y = year || new Date().getFullYear();
const start = Math.floor(y / 10) * 10;
const end = start + 9;
return { start, end };
};
/**
* 获取给定日期的起始时间
* @param date Date
* @returns Date
*/
export const getStartOfDate = (date: Date): Date => {
const d = new Date(date.getTime());
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
return d;
};
/**
* 获取指定日期的结束时间
* @param date Date
* @returns Date
*/
export const getEndOfDate = (date: Date): Date => {
const d = new Date(date.getTime());
d.setHours(23);
d.setMinutes(59);
d.setSeconds(59);
d.setMilliseconds(999);
return d;
};
/**
* 获取指定日期所在周的起始和结束日期
* @param date Date
* @param startOfWeek number 一周是从周几开始,传值0~6,0表示周日
* @returns [startDate, endDate]
*/
export const getWeekRange = (date: Date, startOfWeek: number = 0): Date[] => {
// 获取当前日期偏离当前周第一天的天数
// 如:startOfWeek = 0,周四 => 4; startOfWeek=1,周四 => 3
const day = (7 - (startOfWeek - date.getDay())) % 7;
const start = new Date(date.getTime() - PER_DAY_MILLISECONDS * day);
const end = new Date(start.getTime() + PER_DAY_MILLISECONDS * 6);
return [getStartOfDate(start), getEndOfDate(end)];
};
| 20.633588 | 103 | 0.601554 | 143 | 16 | 0 | 30 | 35 | 4 | 5 | 0 | 31 | 2 | 0 | 6.5625 | 1,914 | 0.024033 | 0.018286 | 0.00209 | 0.001045 | 0 | 0 | 0.364706 | 0.288522 | /**
* 获取传入月份的上个月
* @param year number
* @param month number
* @returns { year: number; month: number }
*/
export const getLastMonth = (year, month) => {
if (month === 0) {
return {
year: year - 1,
month: 11,
};
}
return {
year,
month: month - 1,
};
};
/**
* 获取传入月的下个月
* @param year number
* @param month number
* @returns { year: number; month: number }
*/
export const getNextMonth = (year, month) => {
if (month === 11) {
return {
year: year + 1,
month: 0,
};
}
return {
year,
month: month + 1,
};
};
/**
* 判断传入的年份是否是闰年
* @param year number
* @returns boolean
*/
/* Example usages of 'isLeap' are shown below:
isLeap(year) ? 29 : 28;
*/
const isLeap = (year) => {
return (year % 4 === 0 && year % 100 === 0) || year % 400 === 0;
};
/**
* 获取传入年所在月的最大天数
* @param year number
* @param month number
* @returns number
*/
export const getMaxDayNumOfYearMonth = (year, month) => {
switch (month) {
case 0:
case 2:
case 4:
case 6:
case 7:
case 9:
case 11:
return 31;
case 1:
return isLeap(year) ? 29 : 28;
default:
return 30;
}
};
/**
* 获取指定年所在月的第一天是星期几
* 返回一个0到6之间的整数值,代表星期几: 0 代表星期日
* @param year number
* @param month number
* @returns number
*/
export const getFirstDayOfYearMonth = (year, month) => {
const date = new Date(year, month, 1);
return date.getDay();
};
const PER_DAY_MILLISECONDS = 86400000; // 24 * 60 * 60 * 1000
/**
* 获取指定年所在月的第一天
* @param year number
* @param month number
* @param startOfWeek number 一周是从周几开始,传值0~6,0表示周日
* @returns Date
*/
export const getStartDateOfCalendar = (year, month, startOfWeek = 0) => {
const date = new Date(year, month, 1);
const day = date.getDay();
date.setTime(date.getTime() - PER_DAY_MILLISECONDS * ((day - startOfWeek + 7) % 7));
return date;
};
export interface MonthItem {
year;
month;
}
/**
* 比较两个月的大小
* @param a MonthItem
* @param b MonthItem
* @returns number
*/
export const compareMonth = (a, b) => {
if (a.year === b.year) {
if (a.month === b.month) {
return 0;
}
return a.month > b.month ? 1 : -1;
}
return a.year > b.year ? 1 : -1;
};
/**
* 比较两个日期大小
* @param a Date
* @param b Date
* @returns number 0 means same date, 1 means a > b
*/
export /* Example usages of 'compareDate' are shown below:
compareDate(a, b) === 0;
include
? compareDate(date, startDate) >= 0 && compareDate(date, endDate) <= 0
: compareDate(date, startDate) > 0 && compareDate(date, endDate) < 0;
*/
const compareDate = (a, b) => {
const aYear = a.getFullYear();
const aMonth = a.getMonth();
const aDate = a.getDate();
const bYear = b.getFullYear();
const bMonth = b.getMonth();
const bDate = b.getDate();
if (aYear === bYear) {
if (aMonth === bMonth) {
if (aDate === bDate) {
return 0;
}
return aDate > bDate ? 1 : -1;
}
return aMonth > bMonth ? 1 : -1;
}
return aYear > bYear ? 1 : -1;
};
/**
* 判断是否是同一天
* @param a Date
* @param b Date
* @returns boolean
*/
export /* Example usages of 'isSameDay' are shown below:
isSameDay(day, date);
*/
const isSameDay = (a, b) => {
if (!a || !b) {
return false;
}
return compareDate(a, b) === 0;
};
/**
* 判断日期是否在所给的列表中
* @param date Date
* @param days Date[]
* @returns boolean
*/
export const isInRange = (date, days) => {
if (!date || !days) {
return false;
}
return days.some((day) => isSameDay(day, date));
};
/**
* 判断给定的日期是否在两个日期之间
* @param date Date
* @param start Date
* @param end Date
* @param include boolean 是否包含等于
* @returns boolean
*/
export const isInRange2 = (date, start, end, include = false) => {
if (!date || !start || !end) {
return false;
}
let startDate = start;
let endDate = end;
if (start > end) {
startDate = end;
endDate = start;
}
return include
? compareDate(date, startDate) >= 0 && compareDate(date, endDate) <= 0
: compareDate(date, startDate) > 0 && compareDate(date, endDate) < 0;
};
export interface YearRange {
start;
end;
}
/**
* 获取指定年的10年间起始的年,如2021 => [2020, 2029]
* @param year number
* @returns YearRange
*/
export const getYearRange = (year?) => {
const y = year || new Date().getFullYear();
const start = Math.floor(y / 10) * 10;
const end = start + 9;
return { start, end };
};
/**
* 获取给定日期的起始时间
* @param date Date
* @returns Date
*/
export /* Example usages of 'getStartOfDate' are shown below:
getStartOfDate(start);
*/
const getStartOfDate = (date) => {
const d = new Date(date.getTime());
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
return d;
};
/**
* 获取指定日期的结束时间
* @param date Date
* @returns Date
*/
export /* Example usages of 'getEndOfDate' are shown below:
getEndOfDate(end);
*/
const getEndOfDate = (date) => {
const d = new Date(date.getTime());
d.setHours(23);
d.setMinutes(59);
d.setSeconds(59);
d.setMilliseconds(999);
return d;
};
/**
* 获取指定日期所在周的起始和结束日期
* @param date Date
* @param startOfWeek number 一周是从周几开始,传值0~6,0表示周日
* @returns [startDate, endDate]
*/
export const getWeekRange = (date, startOfWeek = 0) => {
// 获取当前日期偏离当前周第一天的天数
// 如:startOfWeek = 0,周四 => 4; startOfWeek=1,周四 => 3
const day = (7 - (startOfWeek - date.getDay())) % 7;
const start = new Date(date.getTime() - PER_DAY_MILLISECONDS * day);
const end = new Date(start.getTime() + PER_DAY_MILLISECONDS * 6);
return [getStartOfDate(start), getEndOfDate(end)];
};
|
4733b74aea0d17d14b81e7c0c573efc360663bdc | 3,355 | ts | TypeScript | src/example/styles.ts | asakura42/markwright | 7a390a21b2055076a00d4ec8be613e4bc04dc3fc | [
"MIT"
] | null | null | null | src/example/styles.ts | asakura42/markwright | 7a390a21b2055076a00d4ec8be613e4bc04dc3fc | [
"MIT"
] | 2 | 2022-02-14T12:44:35.000Z | 2022-02-27T17:05:05.000Z | src/example/styles.ts | asakura42/markwright | 7a390a21b2055076a00d4ec8be613e4bc04dc3fc | [
"MIT"
] | null | null | null | export const defaults = {
columns: 1,
manual: false
};
export default function styles<T extends typeof defaults>(
metadata: T,
width: number,
height: number
) {
const o = { ...defaults, ...(metadata as object) };
const marginInner = 1;
const marginOuter = 1;
const marginTop = 1;
const marginBottom = 1;
const gutter = 0.5;
const innerWidth = width - marginInner - marginOuter;
return `
:root {
--page-width: ${width}in;
--page-height: ${height}in;
--inner-width: ${innerWidth}in;
--col-width: ${(innerWidth - (o.columns - 1) * gutter) / o.columns}in;
--col-height: calc(${height - marginTop - marginBottom}in - 2rem);
--col-gutter: ${gutter}in;
--margin-inner: ${marginInner}in;
--margin-outer: ${marginOuter}in;
--margin-top: calc(${marginTop / 2}in - 0.5rem);
--margin-bottom: calc(${marginBottom / 2}in - 0.5rem);
}
html, body {
padding: 0;
margin: 0;
}
.mw {
height: var(--page-height);
width: var(--page-width);
}
.section {
display: flex;
flex-direction: column;
}
.section > div {
outline: none;
}
.page {
font-family: var(--sans-stack);
font-size: 15px;
overflow: hidden;
position: relative;
display: flex;
flex-direction: column;
height: var(--page-height);
width: var(--page-width);
}
.odd .header,
.odd .pagination,
.odd .body {
margin-right: var(--margin-inner);
margin-left: var(--margin-outer);
}
.even .header,
.even .pagination,
.even .body {
margin-left: var(--margin-inner);
margin-right: var(--margin-outer);
}
.header {
height: 1rem;
margin-top: var(--margin-top);
margin-bottom: var(--margin-top);
}
.pagination {
height: 1rem;
margin-top: var(--margin-bottom);
margin-bottom: var(--margin-bottom);
}
.body {
display: flex;
flex-direction: column;
width: var(--inner-width);
flex-basis: var(--col-height);
}
.even .header,
.even .pagination {
text-align: right;
}
.odd .header,
.odd .pagination {
text-align: left;
}
.body .content {
display: flex;
flex-grow: 1;
overflow: hidden;
flex-direction: row;
}
.column {
flex: 0 0 var(--col-width);
min-height: var(--col-height);
width: var(--col-width);
height: var(--col-height);
word-wrap: break-word;
}
.page-display {
display: flex;
}
.page-display > div {
margin-right: 1rem;
}
.column-separator {
display: block;
border: none;
height: 100%;
flex: 0 0 var(--col-gutter);
margin: 0;
}
.footnotes:not(.empty) {
border-top: 1px solid var(--grey-light);
margin-top: 0.5rem;
padding-top: 0.5rem;
}
.footnote {
display: block;
}
pre, code {
font-family: var(--font-mono);
}
blockquote {
padding-left: 0.5rem;
margin-left: 0.5rem;
}
@media screen {
.page {
border-radius: 3px;
background-color: white;
margin-bottom: 1rem;
}
}
`;
}
| 19.735294 | 76 | 0.5231 | 140 | 1 | 0 | 3 | 8 | 0 | 0 | 0 | 3 | 0 | 1 | 130 | 970 | 0.004124 | 0.008247 | 0 | 0 | 0.001031 | 0 | 0.25 | 0.206714 | export const defaults = {
columns: 1,
manual: false
};
export default function styles<T extends typeof defaults>(
metadata,
width,
height
) {
const o = { ...defaults, ...(metadata as object) };
const marginInner = 1;
const marginOuter = 1;
const marginTop = 1;
const marginBottom = 1;
const gutter = 0.5;
const innerWidth = width - marginInner - marginOuter;
return `
:root {
--page-width: ${width}in;
--page-height: ${height}in;
--inner-width: ${innerWidth}in;
--col-width: ${(innerWidth - (o.columns - 1) * gutter) / o.columns}in;
--col-height: calc(${height - marginTop - marginBottom}in - 2rem);
--col-gutter: ${gutter}in;
--margin-inner: ${marginInner}in;
--margin-outer: ${marginOuter}in;
--margin-top: calc(${marginTop / 2}in - 0.5rem);
--margin-bottom: calc(${marginBottom / 2}in - 0.5rem);
}
html, body {
padding: 0;
margin: 0;
}
.mw {
height: var(--page-height);
width: var(--page-width);
}
.section {
display: flex;
flex-direction: column;
}
.section > div {
outline: none;
}
.page {
font-family: var(--sans-stack);
font-size: 15px;
overflow: hidden;
position: relative;
display: flex;
flex-direction: column;
height: var(--page-height);
width: var(--page-width);
}
.odd .header,
.odd .pagination,
.odd .body {
margin-right: var(--margin-inner);
margin-left: var(--margin-outer);
}
.even .header,
.even .pagination,
.even .body {
margin-left: var(--margin-inner);
margin-right: var(--margin-outer);
}
.header {
height: 1rem;
margin-top: var(--margin-top);
margin-bottom: var(--margin-top);
}
.pagination {
height: 1rem;
margin-top: var(--margin-bottom);
margin-bottom: var(--margin-bottom);
}
.body {
display: flex;
flex-direction: column;
width: var(--inner-width);
flex-basis: var(--col-height);
}
.even .header,
.even .pagination {
text-align: right;
}
.odd .header,
.odd .pagination {
text-align: left;
}
.body .content {
display: flex;
flex-grow: 1;
overflow: hidden;
flex-direction: row;
}
.column {
flex: 0 0 var(--col-width);
min-height: var(--col-height);
width: var(--col-width);
height: var(--col-height);
word-wrap: break-word;
}
.page-display {
display: flex;
}
.page-display > div {
margin-right: 1rem;
}
.column-separator {
display: block;
border: none;
height: 100%;
flex: 0 0 var(--col-gutter);
margin: 0;
}
.footnotes:not(.empty) {
border-top: 1px solid var(--grey-light);
margin-top: 0.5rem;
padding-top: 0.5rem;
}
.footnote {
display: block;
}
pre, code {
font-family: var(--font-mono);
}
blockquote {
padding-left: 0.5rem;
margin-left: 0.5rem;
}
@media screen {
.page {
border-radius: 3px;
background-color: white;
margin-bottom: 1rem;
}
}
`;
}
|
47b865f58155b36ec7734a484b06a5da7ca2abc2 | 1,522 | ts | TypeScript | src/tools/level.ts | PixiColorEffects/pixi-color-effects | 2b26149b870fa826d6358b899b49be0f8d04d90a | [
"MIT"
] | 84 | 2022-03-03T05:42:35.000Z | 2022-03-21T12:36:25.000Z | src/tools/level.ts | PixiColorEffects/pixi-color-effects | 2b26149b870fa826d6358b899b49be0f8d04d90a | [
"MIT"
] | 1 | 2022-03-01T09:22:58.000Z | 2022-03-02T13:32:54.000Z | src/tools/level.ts | PixiColorEffects/pixi-color-effects | 2b26149b870fa826d6358b899b49be0f8d04d90a | [
"MIT"
] | 7 | 2022-03-04T07:04:42.000Z | 2022-03-22T03:57:22.000Z | // @ts-nocheck
export class LevelMapping {
constructor(e = 0, t = 255, s = 0, i = 255, n = 1, a = 0.5) {
(this.minin = e),
(this.maxin = t),
(this.minout = s),
(this.maxout = i),
(this.midin = n),
(this.mid = a),
(this.map = (e) => (
(e = (e - this.minin) / (this.maxin - this.minin)),
(e = Math.pow(e, this.midin)),
(e = this.minout + e * (this.maxout - this.minout)) > this.maxout
? (e = this.maxout)
: e < this.minout && (e = this.minout),
Math.round(e)
));
}
reset() {
(this.minout = 0),
(this.maxout = 255),
(this.midin = 1),
(this.minin = 0),
(this.maxin = 255),
(this.mid = 0.5);
}
isFlat() {
return Boolean(
0 == this.minout &&
255 == this.maxout &&
0.5 == this.mid &&
0 == this.minin &&
255 == this.maxin
);
}
setMid(e) {
(this.mid = (e - this.minin) / (this.maxin - this.minin)),
(this.midin = this.midToIn(this.mid));
}
midToIn(e) {
return Math.min(Math.max(Math.pow(9.99, 2 * e - 1), 0.1), 9.99);
}
static fillPaletteMap(e, t) {
for (let s = 0; s < 256; ++s) {
let i = e.map(s);
(t.data[4 * s] = i), (t.data[4 * s + 1] = i), (t.data[4 * s + 2] = i);
}
}
static fillRGBPaletteMap(e, t, s, i) {
for (let n = 0; n < 256; ++n)
(i.data[4 * n] = e ? e.map(n) : n),
(i.data[4 * n + 1] = t ? t.map(n) : n),
(i.data[4 * n + 2] = s ? s.map(n) : n);
}
}
| 27.178571 | 76 | 0.442181 | 54 | 8 | 0 | 15 | 3 | 0 | 2 | 0 | 0 | 1 | 0 | 5.75 | 651 | 0.03533 | 0.004608 | 0 | 0.001536 | 0 | 0 | 0 | 0.270755 | // @ts-nocheck
export class LevelMapping {
constructor(e = 0, t = 255, s = 0, i = 255, n = 1, a = 0.5) {
(this.minin = e),
(this.maxin = t),
(this.minout = s),
(this.maxout = i),
(this.midin = n),
(this.mid = a),
(this.map = (e) => (
(e = (e - this.minin) / (this.maxin - this.minin)),
(e = Math.pow(e, this.midin)),
(e = this.minout + e * (this.maxout - this.minout)) > this.maxout
? (e = this.maxout)
: e < this.minout && (e = this.minout),
Math.round(e)
));
}
reset() {
(this.minout = 0),
(this.maxout = 255),
(this.midin = 1),
(this.minin = 0),
(this.maxin = 255),
(this.mid = 0.5);
}
isFlat() {
return Boolean(
0 == this.minout &&
255 == this.maxout &&
0.5 == this.mid &&
0 == this.minin &&
255 == this.maxin
);
}
setMid(e) {
(this.mid = (e - this.minin) / (this.maxin - this.minin)),
(this.midin = this.midToIn(this.mid));
}
midToIn(e) {
return Math.min(Math.max(Math.pow(9.99, 2 * e - 1), 0.1), 9.99);
}
static fillPaletteMap(e, t) {
for (let s = 0; s < 256; ++s) {
let i = e.map(s);
(t.data[4 * s] = i), (t.data[4 * s + 1] = i), (t.data[4 * s + 2] = i);
}
}
static fillRGBPaletteMap(e, t, s, i) {
for (let n = 0; n < 256; ++n)
(i.data[4 * n] = e ? e.map(n) : n),
(i.data[4 * n + 1] = t ? t.map(n) : n),
(i.data[4 * n + 2] = s ? s.map(n) : n);
}
}
|
6a6db4d3da5521347d2bbadd27ec0c2d62649284 | 2,002 | ts | TypeScript | packages/jest-reporters/src/wrapAnsiString.ts | michalwarda/jest | 368eefd8637ff90f2eecc7238995776f586dcbbe | [
"MIT"
] | null | null | null | packages/jest-reporters/src/wrapAnsiString.ts | michalwarda/jest | 368eefd8637ff90f2eecc7238995776f586dcbbe | [
"MIT"
] | 5 | 2022-03-27T00:22:17.000Z | 2022-03-29T00:22:20.000Z | packages/jest-reporters/src/wrapAnsiString.ts | F3n67u/jest | 006d9f40742cf03117b4b527a8f98c2bf10e38d0 | [
"MIT"
] | 1 | 2022-01-29T22:58:26.000Z | 2022-01-29T22:58:26.000Z | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// word-wrap a string that contains ANSI escape sequences.
// ANSI escape sequences do not add to the string length.
export default function wrapAnsiString(
string: string,
terminalWidth: number,
): string {
if (terminalWidth === 0) {
// if the terminal width is zero, don't bother word-wrapping
return string;
}
const ANSI_REGEXP = /[\u001b\u009b]\[\d{1,2}m/gu;
const tokens = [];
let lastIndex = 0;
let match;
while ((match = ANSI_REGEXP.exec(string))) {
const ansi = match[0];
const index = match['index'];
if (index != lastIndex) {
tokens.push(['string', string.slice(lastIndex, index)]);
}
tokens.push(['ansi', ansi]);
lastIndex = index + ansi.length;
}
if (lastIndex != string.length - 1) {
tokens.push(['string', string.slice(lastIndex, string.length)]);
}
let lastLineLength = 0;
return tokens
.reduce(
(lines, [kind, token]) => {
if (kind === 'string') {
if (lastLineLength + token.length > terminalWidth) {
while (token.length) {
const chunk = token.slice(0, terminalWidth - lastLineLength);
const remaining = token.slice(
terminalWidth - lastLineLength,
token.length,
);
lines[lines.length - 1] += chunk;
lastLineLength += chunk.length;
token = remaining;
if (token.length) {
lines.push('');
lastLineLength = 0;
}
}
} else {
lines[lines.length - 1] += token;
lastLineLength += token.length;
}
} else {
lines[lines.length - 1] += token;
}
return lines;
},
[''],
)
.join('\n');
}
| 27.424658 | 75 | 0.552947 | 56 | 2 | 0 | 4 | 9 | 0 | 0 | 0 | 3 | 0 | 0 | 37.5 | 509 | 0.011788 | 0.017682 | 0 | 0 | 0 | 0 | 0.2 | 0.255271 | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// word-wrap a string that contains ANSI escape sequences.
// ANSI escape sequences do not add to the string length.
export default function wrapAnsiString(
string,
terminalWidth,
) {
if (terminalWidth === 0) {
// if the terminal width is zero, don't bother word-wrapping
return string;
}
const ANSI_REGEXP = /[\u001b\u009b]\[\d{1,2}m/gu;
const tokens = [];
let lastIndex = 0;
let match;
while ((match = ANSI_REGEXP.exec(string))) {
const ansi = match[0];
const index = match['index'];
if (index != lastIndex) {
tokens.push(['string', string.slice(lastIndex, index)]);
}
tokens.push(['ansi', ansi]);
lastIndex = index + ansi.length;
}
if (lastIndex != string.length - 1) {
tokens.push(['string', string.slice(lastIndex, string.length)]);
}
let lastLineLength = 0;
return tokens
.reduce(
(lines, [kind, token]) => {
if (kind === 'string') {
if (lastLineLength + token.length > terminalWidth) {
while (token.length) {
const chunk = token.slice(0, terminalWidth - lastLineLength);
const remaining = token.slice(
terminalWidth - lastLineLength,
token.length,
);
lines[lines.length - 1] += chunk;
lastLineLength += chunk.length;
token = remaining;
if (token.length) {
lines.push('');
lastLineLength = 0;
}
}
} else {
lines[lines.length - 1] += token;
lastLineLength += token.length;
}
} else {
lines[lines.length - 1] += token;
}
return lines;
},
[''],
)
.join('\n');
}
|
6a9f394309948df35048df7f8350b86b7219c38d | 1,293 | ts | TypeScript | src/utils/algorithms/mergeSort.ts | limivann/sorting-visualizer | e22c3d601d397f9d5fa702c02e9dadfbbb7c062d | [
"MIT"
] | 1 | 2022-03-31T02:53:39.000Z | 2022-03-31T02:53:39.000Z | src/utils/algorithms/mergeSort.ts | limivann/sorting-visualizer | e22c3d601d397f9d5fa702c02e9dadfbbb7c062d | [
"MIT"
] | null | null | null | src/utils/algorithms/mergeSort.ts | limivann/sorting-visualizer | e22c3d601d397f9d5fa702c02e9dadfbbb7c062d | [
"MIT"
] | null | null | null | export const getMergeSortAnimations = (
items: number[],
animationArray: number[][]
) => {
mergeSort(items, [], 0, items.length - 1, animationArray);
};
const merge = (
items: number[],
aux: number[],
low: number,
mid: number,
high: number,
animationArray: number[][]
) => {
// TODO: optimize merge sort
// copy
for (let i = low; i <= high; i++) {
aux[i] = items[i];
}
let a = low;
let b = mid + 1;
for (let i = low; i <= high; i++) {
// finished left
if (a > mid) {
// push to animation Array [the div changed, index of the div]
animationArray.push([aux[b], i]);
items[i] = aux[b++];
// finished right
} else if (b > high) {
animationArray.push([aux[a], i]);
items[i] = aux[a++];
} else if (aux[a] <= aux[b]) {
animationArray.push([aux[a], i]);
items[i] = aux[a++];
} else {
animationArray.push([aux[b], i]);
items[i] = aux[b++];
}
}
};
const mergeSort = (
items: number[],
aux: number[],
low: number,
high: number,
animationArray: number[][]
) => {
if (low >= high) {
return;
}
const mid: number = low + Math.floor((high - low) / 2); // prevent int overflow
mergeSort(items, aux, low, mid, animationArray);
mergeSort(items, aux, mid + 1, high, animationArray);
merge(items, aux, low, mid, high, animationArray);
};
| 22.293103 | 80 | 0.584687 | 50 | 3 | 0 | 13 | 8 | 0 | 2 | 0 | 14 | 0 | 0 | 9.333333 | 480 | 0.033333 | 0.016667 | 0 | 0 | 0 | 0 | 0.583333 | 0.302278 | export const getMergeSortAnimations = (
items,
animationArray
) => {
mergeSort(items, [], 0, items.length - 1, animationArray);
};
/* Example usages of 'merge' are shown below:
merge(items, aux, low, mid, high, animationArray);
*/
const merge = (
items,
aux,
low,
mid,
high,
animationArray
) => {
// TODO: optimize merge sort
// copy
for (let i = low; i <= high; i++) {
aux[i] = items[i];
}
let a = low;
let b = mid + 1;
for (let i = low; i <= high; i++) {
// finished left
if (a > mid) {
// push to animation Array [the div changed, index of the div]
animationArray.push([aux[b], i]);
items[i] = aux[b++];
// finished right
} else if (b > high) {
animationArray.push([aux[a], i]);
items[i] = aux[a++];
} else if (aux[a] <= aux[b]) {
animationArray.push([aux[a], i]);
items[i] = aux[a++];
} else {
animationArray.push([aux[b], i]);
items[i] = aux[b++];
}
}
};
/* Example usages of 'mergeSort' are shown below:
mergeSort(items, [], 0, items.length - 1, animationArray);
mergeSort(items, aux, low, mid, animationArray);
mergeSort(items, aux, mid + 1, high, animationArray);
*/
const mergeSort = (
items,
aux,
low,
high,
animationArray
) => {
if (low >= high) {
return;
}
const mid = low + Math.floor((high - low) / 2); // prevent int overflow
mergeSort(items, aux, low, mid, animationArray);
mergeSort(items, aux, mid + 1, high, animationArray);
merge(items, aux, low, mid, high, animationArray);
};
|
c7e79d94ea23f48d38126db8aaaad594d204dc5b | 2,035 | tsx | TypeScript | mixins/timestamp.tsx | Abel-Liao/Front-end-Component | 1762bc7b6b6fe0a3b3dd61fba9b2946e0c960af4 | [
"MIT"
] | 2 | 2022-02-25T06:30:12.000Z | 2022-02-25T06:30:14.000Z | mixins/timestamp.tsx | Abel-Liao/Front-end-Component | 1762bc7b6b6fe0a3b3dd61fba9b2946e0c960af4 | [
"MIT"
] | 1 | 2022-02-25T06:41:29.000Z | 2022-02-25T06:50:44.000Z | mixins/timestamp.tsx | Abel-Liao/Front-end-Component | 1762bc7b6b6fe0a3b3dd61fba9b2946e0c960af4 | [
"MIT"
] | 1 | 2022-02-25T05:48:55.000Z | 2022-02-25T05:48:55.000Z | /**
* @todo Time is converted to a fixed format
* @param {Date | number | string} [date] The time or format to convert
* @example date="YYYY/MM/DD hh:mm:ss"
* @example date="2022/2/2"
* @param {String} [style=MM-DD-YYYY hh:mm:ss] The format to convert
* @example style="YYYY年MM月DD日 hh时mm分ss秒"
* @returns {String} XXXX-XX-XX XX:XX:XX
*/
export const timestamp: Function = (
date?: Date | number | string,
style?: string
): string => {
let provisionalityTime: string = "MM-DD-YYYY HH:mm:ss";
let timeData: Date = new Date();
if (style) {
provisionalityTime = style;
}
if (date) {
if (Object.prototype.toString.call(date) === "[object String]") {
const regExp = /[y|Y]{4}|[m|M|D|d|H|h|s]{2} /;
if (regExp.test(date as string)) {
provisionalityTime = date as string;
} else {
timeData = new Date(date as string);
}
} else {
timeData = new Date(date as Date | number);
}
}
const year = (timeData as Date).getFullYear().toString();
const month = (timeData.getMonth() + 1).toString();
const day = timeData.getDate().toString();
const hours = timeData.getHours().toString();
const minutes = timeData.getMinutes().toString();
const seconds = timeData.getSeconds().toString();
provisionalityTime = provisionalityTime.replace("YYYY", year);
provisionalityTime = provisionalityTime.replace(
"MM",
month.length === 1 ? `0${month}` : month
);
provisionalityTime = provisionalityTime.replace(
"DD",
day.length === 1 ? `0${day}` : day
);
provisionalityTime = provisionalityTime.replace(
"HH",
hours.length === 1 ? `0${hours}` : hours
);
provisionalityTime = provisionalityTime.replace(
"hh",
hours.length === 1 ? `0${hours}` : hours
);
provisionalityTime = provisionalityTime.replace(
"mm",
minutes.length === 1 ? `0${minutes}` : minutes
);
provisionalityTime = provisionalityTime.replace(
"ss",
seconds.length === 1 ? `0${seconds}` : seconds
);
return provisionalityTime;
};
| 31.307692 | 71 | 0.633415 | 54 | 1 | 0 | 2 | 10 | 0 | 0 | 1 | 9 | 0 | 5 | 49 | 604 | 0.004967 | 0.016556 | 0 | 0 | 0.008278 | 0.076923 | 0.692308 | 0.232577 | /**
* @todo Time is converted to a fixed format
* @param {Date | number | string} [date] The time or format to convert
* @example date="YYYY/MM/DD hh:mm:ss"
* @example date="2022/2/2"
* @param {String} [style=MM-DD-YYYY hh:mm:ss] The format to convert
* @example style="YYYY年MM月DD日 hh时mm分ss秒"
* @returns {String} XXXX-XX-XX XX:XX:XX
*/
export const timestamp = (
date?,
style?
) => {
let provisionalityTime = "MM-DD-YYYY HH:mm:ss";
let timeData = new Date();
if (style) {
provisionalityTime = style;
}
if (date) {
if (Object.prototype.toString.call(date) === "[object String]") {
const regExp = /[y|Y]{4}|[m|M|D|d|H|h|s]{2} /;
if (regExp.test(date as string)) {
provisionalityTime = date as string;
} else {
timeData = new Date(date as string);
}
} else {
timeData = new Date(date as Date | number);
}
}
const year = (timeData as Date).getFullYear().toString();
const month = (timeData.getMonth() + 1).toString();
const day = timeData.getDate().toString();
const hours = timeData.getHours().toString();
const minutes = timeData.getMinutes().toString();
const seconds = timeData.getSeconds().toString();
provisionalityTime = provisionalityTime.replace("YYYY", year);
provisionalityTime = provisionalityTime.replace(
"MM",
month.length === 1 ? `0${month}` : month
);
provisionalityTime = provisionalityTime.replace(
"DD",
day.length === 1 ? `0${day}` : day
);
provisionalityTime = provisionalityTime.replace(
"HH",
hours.length === 1 ? `0${hours}` : hours
);
provisionalityTime = provisionalityTime.replace(
"hh",
hours.length === 1 ? `0${hours}` : hours
);
provisionalityTime = provisionalityTime.replace(
"mm",
minutes.length === 1 ? `0${minutes}` : minutes
);
provisionalityTime = provisionalityTime.replace(
"ss",
seconds.length === 1 ? `0${seconds}` : seconds
);
return provisionalityTime;
};
|
fbe26edfe77a14049836547c8e6eeeb0c09e28c5 | 2,733 | ts | TypeScript | modules/canvas/canvasUtil.ts | gurrrrrrett3/broglands-bot | a6996cf0b1d23abfed013751d1149810ae8d5420 | [
"MIT"
] | 1 | 2022-03-31T05:42:08.000Z | 2022-03-31T05:42:08.000Z | modules/canvas/canvasUtil.ts | gurrrrrrett3/broglands-bot | a6996cf0b1d23abfed013751d1149810ae8d5420 | [
"MIT"
] | null | null | null | modules/canvas/canvasUtil.ts | gurrrrrrett3/broglands-bot | a6996cf0b1d23abfed013751d1149810ae8d5420 | [
"MIT"
] | 1 | 2022-03-29T23:09:34.000Z | 2022-03-29T23:09:34.000Z | export type ValidColorCode =
| "0"
| "1"
| "2"
| "3"
| "4"
| "5"
| "6"
| "7"
| "8"
| "9"
| "a"
| "b"
| "c"
| "d"
| "e"
| "f";
export type ValidFormatCode = "k" | "l" | "m" | "n" | "o" | "r";
export interface ConvertedFormatInstance {
text: string;
color: string;
bold: boolean;
italic: boolean;
underline: boolean;
strikethrough: boolean;
obfuscated: boolean;
}
export default class CanvasUtil {
//Static color codes
public static colorCodes = {
"0": "#000000",
"1": "#0000AA",
"2": "#00AA00",
"3": "#00AAAA",
"4": "#AA0000",
"5": "#AA00AA",
"6": "#FFAA00",
"7": "#AAAAAA",
"8": "#555555",
"9": "#5555FF",
a: "#55FF55",
b: "#55FFFF",
c: "#FF5555",
d: "#FF55FF",
e: "#FFFF55",
f: "#FFFFFF",
};
public static getColorCodes(text: string) {
return text.replace(/\&([0-9a-f])/g, (match, color: ValidColorCode) => {
return `[${CanvasUtil.colorCodes[color]}]`;
});
}
public static getHexCodes(text: string) {
//format: &#rrggbb
return text.replace(/\&#([0-9a-f]{6})/g, (match, color: string) => {
return `[#${color}]`;
});
}
public static getFormatCodes(text: string) {
return text.match;
}
public static convertMinecraftFormat(text: string) {
let out: ConvertedFormatInstance[] = [];
let current: ConvertedFormatInstance = {
text: "",
color: "",
bold: false,
italic: false,
underline: false,
strikethrough: false,
obfuscated: false,
};
}
public static splitGroups(text: string) {
/*
Text is split into groups of text and format codes
Example:
"&0Hello &lWorld"
[
{
text: "Hello ",
format: &0
},
{
text: "World",
format: &l
}
]
Text can have multiple format codes, but the last color code overrides the previous one
Example:
"&0&bHello &lWorld"
The b code overrides the 0 code
Other Examples:
"&l&m&aHello &lWorld"
"�ffbbHello &l&aWorld"
*/
let out: { text: string; format: string }[] = [];
let groups = text.split("&");
for (let i = 0; i < groups.length; i++) {
let group = groups[i];
let format = "";
let text = group;
if (group.length == 1 && group.match(/[0-9a-fk-or]/)) {
//format or color code
format = `&${group}`;
} else if (group.length == 7 && group.match(/\#[0-9a-f]{6}/)) {
//hex code
format = `&#${group}`;
out.push({
text,
format,
});
}
}
}
}
| 19.246479 | 91 | 0.491401 | 90 | 7 | 0 | 9 | 8 | 8 | 0 | 0 | 15 | 4 | 0 | 5 | 861 | 0.018583 | 0.009292 | 0.009292 | 0.004646 | 0 | 0 | 0.46875 | 0.250759 | export type ValidColorCode =
| "0"
| "1"
| "2"
| "3"
| "4"
| "5"
| "6"
| "7"
| "8"
| "9"
| "a"
| "b"
| "c"
| "d"
| "e"
| "f";
export type ValidFormatCode = "k" | "l" | "m" | "n" | "o" | "r";
export interface ConvertedFormatInstance {
text;
color;
bold;
italic;
underline;
strikethrough;
obfuscated;
}
export default class CanvasUtil {
//Static color codes
public static colorCodes = {
"0": "#000000",
"1": "#0000AA",
"2": "#00AA00",
"3": "#00AAAA",
"4": "#AA0000",
"5": "#AA00AA",
"6": "#FFAA00",
"7": "#AAAAAA",
"8": "#555555",
"9": "#5555FF",
a: "#55FF55",
b: "#55FFFF",
c: "#FF5555",
d: "#FF55FF",
e: "#FFFF55",
f: "#FFFFFF",
};
public static getColorCodes(text) {
return text.replace(/\&([0-9a-f])/g, (match, color) => {
return `[${CanvasUtil.colorCodes[color]}]`;
});
}
public static getHexCodes(text) {
//format: &#rrggbb
return text.replace(/\&#([0-9a-f]{6})/g, (match, color) => {
return `[#${color}]`;
});
}
public static getFormatCodes(text) {
return text.match;
}
public static convertMinecraftFormat(text) {
let out = [];
let current = {
text: "",
color: "",
bold: false,
italic: false,
underline: false,
strikethrough: false,
obfuscated: false,
};
}
public static splitGroups(text) {
/*
Text is split into groups of text and format codes
Example:
"&0Hello &lWorld"
[
{
text: "Hello ",
format: &0
},
{
text: "World",
format: &l
}
]
Text can have multiple format codes, but the last color code overrides the previous one
Example:
"&0&bHello &lWorld"
The b code overrides the 0 code
Other Examples:
"&l&m&aHello &lWorld"
"�ffbbHello &l&aWorld"
*/
let out = [];
let groups = text.split("&");
for (let i = 0; i < groups.length; i++) {
let group = groups[i];
let format = "";
let text = group;
if (group.length == 1 && group.match(/[0-9a-fk-or]/)) {
//format or color code
format = `&${group}`;
} else if (group.length == 7 && group.match(/\#[0-9a-f]{6}/)) {
//hex code
format = `&#${group}`;
out.push({
text,
format,
});
}
}
}
}
|
4c21fc3b7d2f4f19613844c0afd5982ab62cbaa9 | 2,329 | ts | TypeScript | src/constants/quenyaRule.ts | Vrisel/quettale | a219d87c6a42848be71cab6af837e0b9df40be9b | [
"MIT"
] | 1 | 2022-03-06T13:36:40.000Z | 2022-03-06T13:36:40.000Z | src/constants/quenyaRule.ts | Vrisel/quettale | a219d87c6a42848be71cab6af837e0b9df40be9b | [
"MIT"
] | 5 | 2022-02-09T22:42:15.000Z | 2022-03-19T12:27:46.000Z | src/constants/quenyaRule.ts | Vrisel/quettale | a219d87c6a42848be71cab6af837e0b9df40be9b | [
"MIT"
] | null | null | null | export const VOWELS = [
// single vowel and dipthong
'a',
'e',
'i',
'o',
'u',
'á',
'é',
'í',
'ó',
'ú',
'ai',
'au',
'eu',
'iu',
'oi',
'ui',
// combinations
'aia',
'ea',
'eo',
'ie',
'io',
'oa',
'oe', // exists in corpula but only as 'loëndë'
'oia',
'oio',
'ua',
'uo', // exist in corpula but only as 'Eruo'
'uio',
'úa',
];
export const CONSONANTS = [
// single tengwa
't',
'nd',
/* 'th', */
'nt',
'n',
'r',
'p',
'mb',
'f',
'mp',
'm',
'v',
'c', // k
'ng',
'h',
'nc',
'y',
'qu', // cw
'ngw',
'hw',
'nqu', // ncw
'nw',
'w',
'rd',
'l',
'ld',
's',
'ss',
// double
'cc',
/* 'ff', // occurs only 'effir- */
'll',
'mm',
'rr',
// digraphs
'hy',
'ly',
'my',
'ny',
'ry',
'ty',
'hr',
'hl',
// -s
'ls',
'ps',
'rs',
'ts',
'x', // cs
// others
'ht',
'lc',
'lm',
'lv',
'lqu',
'lt',
'mn',
'nv',
'pt',
'rc',
'rqu',
'rn',
'rm',
'st',
'ts',
];
export const INITIAL_CONSONANTS = [
'c',
'f',
'h',
'l',
'm',
'n',
'p',
'r',
's',
't',
'v',
'w',
'y',
'nw',
'qu',
'hy',
'ly',
'ny',
'ty',
'hl',
'hr',
];
export const LAST_CONSONANTS = [
'l',
'n',
'r',
's',
't',
'nt', // occurs grammatically only
];
export const IMPOSSIBLE_CLUSTER = [
'ct', // ht
'ln', // ld
'lr', // ll
'ls', // ld
'ns', // ss
'nr', // rr
'nm', // mm
'np', // mp
'rl', // ll
'sf', // ff?
'sh',
'sl',
'sm',
'sn',
'sr',
'sv',
'tc',
'tf',
'th', // s
'tl',
'tn', // nt
'tr',
'yi',
'yí',
];
export function wordValidation(word: string): boolean {
const forInitCons = `^(?:${INITIAL_CONSONANTS.join('|')})?`;
const forVowels = `(?:${VOWELS.join('|')})`;
const forCons = `(?:${CONSONANTS.join('|')})`;
const forLastCons = `[${LAST_CONSONANTS.join('')}]?$`;
const isValid = new RegExp(
`${forInitCons}${forVowels}(?:${forCons}${forVowels})*${forLastCons}`
);
const hasInvalidCluster = new RegExp(`(?:${IMPOSSIBLE_CLUSTER.join('|')})`);
const hasClusterAfterLongVowel = new RegExp(
`[áéíóú](?:mb|ld|nd|rd|ng|x|[cfhlmnprstvw](?:[cfhlmnprstvw]|y))`
);
return (
isValid.test(word) &&
!hasInvalidCluster.test(word) &&
!hasClusterAfterLongVowel.test(word)
);
}
| 12.796703 | 78 | 0.433233 | 167 | 1 | 0 | 1 | 12 | 0 | 0 | 0 | 2 | 0 | 0 | 16 | 981 | 0.002039 | 0.012232 | 0 | 0 | 0 | 0 | 0.142857 | 0.214612 | export const VOWELS = [
// single vowel and dipthong
'a',
'e',
'i',
'o',
'u',
'á',
'é',
'í',
'ó',
'ú',
'ai',
'au',
'eu',
'iu',
'oi',
'ui',
// combinations
'aia',
'ea',
'eo',
'ie',
'io',
'oa',
'oe', // exists in corpula but only as 'loëndë'
'oia',
'oio',
'ua',
'uo', // exist in corpula but only as 'Eruo'
'uio',
'úa',
];
export const CONSONANTS = [
// single tengwa
't',
'nd',
/* 'th', */
'nt',
'n',
'r',
'p',
'mb',
'f',
'mp',
'm',
'v',
'c', // k
'ng',
'h',
'nc',
'y',
'qu', // cw
'ngw',
'hw',
'nqu', // ncw
'nw',
'w',
'rd',
'l',
'ld',
's',
'ss',
// double
'cc',
/* 'ff', // occurs only 'effir- */
'll',
'mm',
'rr',
// digraphs
'hy',
'ly',
'my',
'ny',
'ry',
'ty',
'hr',
'hl',
// -s
'ls',
'ps',
'rs',
'ts',
'x', // cs
// others
'ht',
'lc',
'lm',
'lv',
'lqu',
'lt',
'mn',
'nv',
'pt',
'rc',
'rqu',
'rn',
'rm',
'st',
'ts',
];
export const INITIAL_CONSONANTS = [
'c',
'f',
'h',
'l',
'm',
'n',
'p',
'r',
's',
't',
'v',
'w',
'y',
'nw',
'qu',
'hy',
'ly',
'ny',
'ty',
'hl',
'hr',
];
export const LAST_CONSONANTS = [
'l',
'n',
'r',
's',
't',
'nt', // occurs grammatically only
];
export const IMPOSSIBLE_CLUSTER = [
'ct', // ht
'ln', // ld
'lr', // ll
'ls', // ld
'ns', // ss
'nr', // rr
'nm', // mm
'np', // mp
'rl', // ll
'sf', // ff?
'sh',
'sl',
'sm',
'sn',
'sr',
'sv',
'tc',
'tf',
'th', // s
'tl',
'tn', // nt
'tr',
'yi',
'yí',
];
export function wordValidation(word) {
const forInitCons = `^(?:${INITIAL_CONSONANTS.join('|')})?`;
const forVowels = `(?:${VOWELS.join('|')})`;
const forCons = `(?:${CONSONANTS.join('|')})`;
const forLastCons = `[${LAST_CONSONANTS.join('')}]?$`;
const isValid = new RegExp(
`${forInitCons}${forVowels}(?:${forCons}${forVowels})*${forLastCons}`
);
const hasInvalidCluster = new RegExp(`(?:${IMPOSSIBLE_CLUSTER.join('|')})`);
const hasClusterAfterLongVowel = new RegExp(
`[áéíóú](?:mb|ld|nd|rd|ng|x|[cfhlmnprstvw](?:[cfhlmnprstvw]|y))`
);
return (
isValid.test(word) &&
!hasInvalidCluster.test(word) &&
!hasClusterAfterLongVowel.test(word)
);
}
|
4c415d598efd140b84e949e32a132ebe5ef4c1d3 | 7,775 | ts | TypeScript | src/data-structure/rope.ts | linkdotnet/ts-stringoperations | 3ce2d25cfe7823492ccd37c1b6fd7abcf24b0455 | [
"MIT"
] | 2 | 2022-03-19T08:46:42.000Z | 2022-03-22T15:02:33.000Z | src/data-structure/rope.ts | linkdotnet/ts-stringoperations | 3ce2d25cfe7823492ccd37c1b6fd7abcf24b0455 | [
"MIT"
] | null | null | null | src/data-structure/rope.ts | linkdotnet/ts-stringoperations | 3ce2d25cfe7823492ccd37c1b6fd7abcf24b0455 | [
"MIT"
] | null | null | null | /**
* Represents a rope
*/
export class Rope {
private fragment: string
private hasToRecaluclateWeights: boolean
private left: Rope | undefined
private right: Rope | undefined
private weight: number
private constructor () {
this.left = undefined
this.right = undefined
this.hasToRecaluclateWeights = false
this.fragment = ''
this.weight = 0
}
/**
* Returns the character at the given index
* @param index The zero-based index of the desired character.
* @returns Returns the character at the specified index.
*/
public charAt (index: number): string {
this.checkRecalculation()
return Rope.charAtInternal(this, index)
}
/**
* Represents the rope as a single string
* @returns The whole rope as string
*/
public toString (): string {
const results: string[] = []
Rope.getStrings(this, results)
return results.join('')
}
/**
* Concats a string to the rope and returns the new rope
* @param other Other string which will be appended to the rope
* @param recalculateWeights If set to true the weights of the new rope will be calculated immediately
* @returns New rope instance with both texts
* @remarks If concating a lot of strings, setting recalculateWeights to true is very expensive.
* Operations which require the calculated weight will check if a recalculation is needed.
* ```ts
* for (let i = 0; i < 10000; i++) {
* newRope = newRope.concat('test', false)
* }
* newRope.charAt(2) // This will automatically recalculate the weight
* ```
*/
public concatString (other: string, recalculateWeights = false): Rope {
const otherRope = Rope.create(other)
return this.concatRope(otherRope, recalculateWeights)
}
/**
* Concats a rope to the current one and returns the new combined rope
* @param other Other string which will be appended to the rope
* @param recalculateWeights If set to true the weights of the new rope will be calculated immediately
* @returns New rope instance with both texts
* @remarks If concating a lot of strings, setting recalculateWeights to true is very expensive.
* Operations which require the calculated weight will check if a recalculation is needed.
* ```ts
* for (let i = 0; i < 10000; i++) {
* newRope = newRope.concat('test', false)
* }
* newRope.charAt(2) // This will automatically recalculate the weight
* ```
*/
public concatRope (other: Rope | undefined, recalculateWeights = false): Rope {
const newRope = new Rope()
newRope.left = this
newRope.right = other
newRope.hasToRecaluclateWeights = true
if (recalculateWeights) {
this.checkRecalculation()
}
return newRope
}
/**
* Splits the rope into two new ones at the defined index
* @param index Zero based index where the rope should be split. The index is always part of the left side of the rope
*/
public split (index: number): [Rope, Rope | undefined] {
if (index < 0) {
throw new RangeError('Index was negative')
}
this.checkRecalculation()
return Rope.splitRope(this, index)
}
/**
* Inserts another rope into the current one and returns the merger
* @param rope New rope to add to the current one
* @param index Zero based index where the new rope has to be inserted
* @returns The merged rope
*/
public insert (rope: Rope, index: number): Rope {
const pair = this.split(index)
const left = pair[0].concatRope(rope)
return left.concatRope(pair[1])
}
/**
* Inserts a string into the current rope and returns the merger
* @param rope New rope to add to the current one
* @param index Zero based index where the new rope has to be inserted
* @returns The merged rope
*/
public insertString (text: string, index: number): Rope {
return this.insert(Rope.create(text), index)
}
/**
* Deletes a substring from the rope
* @param startIndex Inclusive starting index
* @param length Length to delete
* @returns New rope with deleted range
*/
public delete (startIndex: number, length: number): Rope {
if (startIndex < 0) {
throw new RangeError('Index was negative')
}
if (length <= 0) {
throw new RangeError('Length has to be at least 1')
}
this.checkRecalculation()
const beforeStartIndex = this.split(startIndex - 1)[0]
const afterEndIndex = this.split(startIndex + length - 1)[1]
return beforeStartIndex.concatRope(afterEndIndex)
}
/**
* Creates the rope with the given text
* @param text The initial text to add in the rope
* @param leafLength Size of a single leaf. Every leaf is a substring of the given text
* @returns Instance of a rope
*/
public static create (text: string, leafLength = 8): Rope {
return this.createInternal(text, leafLength, 0, text.length - 1)
}
private static createInternal (text: string, leafLength: number, leftIndex: number, rightIndex: number): Rope {
const node = new Rope()
if (rightIndex - leftIndex > leafLength) {
const center = (rightIndex + leftIndex + 1) / 2
node.left = Rope.createInternal(text, leafLength, leftIndex, center)
node.right = Rope.createInternal(text, leafLength, center + 1, rightIndex)
} else {
node.fragment = text.slice(leftIndex, rightIndex + 1)
}
node.calculateAndSetWeight()
return node
}
private static getWeightInternal (node: Rope): number {
if (node.left !== undefined && node.right !== undefined) {
return this.getWeightInternal(node.left) + this.getWeightInternal(node.right)
}
return node.left !== undefined ? this.getWeightInternal(node.left) : node.fragment.length
}
private static charAtInternal (node: Rope, index: number): string {
if (node.weight <= index && node.right) {
return Rope.charAtInternal(node.right, index - node.weight)
}
if (node.left) {
return Rope.charAtInternal(node.left, index)
}
return node.fragment[index]
}
private static getStrings (node: Rope, results: string[]) {
if (!node) {
return
}
if (!node.left && !node.right) {
results.push(node.fragment)
}
Rope.getStrings(node.left!, results)
Rope.getStrings(node.right!, results)
}
private static splitRope (node: Rope, index: number): [Rope, Rope | undefined] {
if (!node.left) {
if (index === node.weight - 1) {
return [node, undefined]
}
const item1 = Rope.create(node.fragment.slice(0, index + 1))
const item2 = Rope.create(node.fragment.slice(index + 1, node.weight))
return [item1, item2]
}
if (index === node.weight - 1) {
return [node.left, node.right]
}
if (index < node.weight) {
const splitLeftSide = Rope.splitRope(node.left, index)
return [splitLeftSide[0], splitLeftSide[1]!.concatRope(node.right!)]
}
const splitRightSide = Rope.splitRope(node.right!, index - node.weight)
return [node.left.concatRope(splitRightSide[0]), splitRightSide[1]]
}
private calculateAndSetWeight () {
this.weight = this.left === undefined ? this.fragment.length : Rope.getWeightInternal(this.left)
}
private checkRecalculation () {
if (this.hasToRecaluclateWeights) {
this.calculateAndSetWeight()
this.hasToRecaluclateWeights = false
}
}
}
| 32.531381 | 122 | 0.636656 | 132 | 17 | 0 | 25 | 13 | 5 | 11 | 0 | 24 | 1 | 0 | 5.352941 | 2,018 | 0.020813 | 0.006442 | 0.002478 | 0.000496 | 0 | 0 | 0.4 | 0.242871 | /**
* Represents a rope
*/
export class Rope {
private fragment
private hasToRecaluclateWeights
private left
private right
private weight
private constructor () {
this.left = undefined
this.right = undefined
this.hasToRecaluclateWeights = false
this.fragment = ''
this.weight = 0
}
/**
* Returns the character at the given index
* @param index The zero-based index of the desired character.
* @returns Returns the character at the specified index.
*/
public charAt (index) {
this.checkRecalculation()
return Rope.charAtInternal(this, index)
}
/**
* Represents the rope as a single string
* @returns The whole rope as string
*/
public toString () {
const results = []
Rope.getStrings(this, results)
return results.join('')
}
/**
* Concats a string to the rope and returns the new rope
* @param other Other string which will be appended to the rope
* @param recalculateWeights If set to true the weights of the new rope will be calculated immediately
* @returns New rope instance with both texts
* @remarks If concating a lot of strings, setting recalculateWeights to true is very expensive.
* Operations which require the calculated weight will check if a recalculation is needed.
* ```ts
* for (let i = 0; i < 10000; i++) {
* newRope = newRope.concat('test', false)
* }
* newRope.charAt(2) // This will automatically recalculate the weight
* ```
*/
public concatString (other, recalculateWeights = false) {
const otherRope = Rope.create(other)
return this.concatRope(otherRope, recalculateWeights)
}
/**
* Concats a rope to the current one and returns the new combined rope
* @param other Other string which will be appended to the rope
* @param recalculateWeights If set to true the weights of the new rope will be calculated immediately
* @returns New rope instance with both texts
* @remarks If concating a lot of strings, setting recalculateWeights to true is very expensive.
* Operations which require the calculated weight will check if a recalculation is needed.
* ```ts
* for (let i = 0; i < 10000; i++) {
* newRope = newRope.concat('test', false)
* }
* newRope.charAt(2) // This will automatically recalculate the weight
* ```
*/
public concatRope (other, recalculateWeights = false) {
const newRope = new Rope()
newRope.left = this
newRope.right = other
newRope.hasToRecaluclateWeights = true
if (recalculateWeights) {
this.checkRecalculation()
}
return newRope
}
/**
* Splits the rope into two new ones at the defined index
* @param index Zero based index where the rope should be split. The index is always part of the left side of the rope
*/
public split (index) {
if (index < 0) {
throw new RangeError('Index was negative')
}
this.checkRecalculation()
return Rope.splitRope(this, index)
}
/**
* Inserts another rope into the current one and returns the merger
* @param rope New rope to add to the current one
* @param index Zero based index where the new rope has to be inserted
* @returns The merged rope
*/
public insert (rope, index) {
const pair = this.split(index)
const left = pair[0].concatRope(rope)
return left.concatRope(pair[1])
}
/**
* Inserts a string into the current rope and returns the merger
* @param rope New rope to add to the current one
* @param index Zero based index where the new rope has to be inserted
* @returns The merged rope
*/
public insertString (text, index) {
return this.insert(Rope.create(text), index)
}
/**
* Deletes a substring from the rope
* @param startIndex Inclusive starting index
* @param length Length to delete
* @returns New rope with deleted range
*/
public delete (startIndex, length) {
if (startIndex < 0) {
throw new RangeError('Index was negative')
}
if (length <= 0) {
throw new RangeError('Length has to be at least 1')
}
this.checkRecalculation()
const beforeStartIndex = this.split(startIndex - 1)[0]
const afterEndIndex = this.split(startIndex + length - 1)[1]
return beforeStartIndex.concatRope(afterEndIndex)
}
/**
* Creates the rope with the given text
* @param text The initial text to add in the rope
* @param leafLength Size of a single leaf. Every leaf is a substring of the given text
* @returns Instance of a rope
*/
public static create (text, leafLength = 8) {
return this.createInternal(text, leafLength, 0, text.length - 1)
}
private static createInternal (text, leafLength, leftIndex, rightIndex) {
const node = new Rope()
if (rightIndex - leftIndex > leafLength) {
const center = (rightIndex + leftIndex + 1) / 2
node.left = Rope.createInternal(text, leafLength, leftIndex, center)
node.right = Rope.createInternal(text, leafLength, center + 1, rightIndex)
} else {
node.fragment = text.slice(leftIndex, rightIndex + 1)
}
node.calculateAndSetWeight()
return node
}
private static getWeightInternal (node) {
if (node.left !== undefined && node.right !== undefined) {
return this.getWeightInternal(node.left) + this.getWeightInternal(node.right)
}
return node.left !== undefined ? this.getWeightInternal(node.left) : node.fragment.length
}
private static charAtInternal (node, index) {
if (node.weight <= index && node.right) {
return Rope.charAtInternal(node.right, index - node.weight)
}
if (node.left) {
return Rope.charAtInternal(node.left, index)
}
return node.fragment[index]
}
private static getStrings (node, results) {
if (!node) {
return
}
if (!node.left && !node.right) {
results.push(node.fragment)
}
Rope.getStrings(node.left!, results)
Rope.getStrings(node.right!, results)
}
private static splitRope (node, index) {
if (!node.left) {
if (index === node.weight - 1) {
return [node, undefined]
}
const item1 = Rope.create(node.fragment.slice(0, index + 1))
const item2 = Rope.create(node.fragment.slice(index + 1, node.weight))
return [item1, item2]
}
if (index === node.weight - 1) {
return [node.left, node.right]
}
if (index < node.weight) {
const splitLeftSide = Rope.splitRope(node.left, index)
return [splitLeftSide[0], splitLeftSide[1]!.concatRope(node.right!)]
}
const splitRightSide = Rope.splitRope(node.right!, index - node.weight)
return [node.left.concatRope(splitRightSide[0]), splitRightSide[1]]
}
private calculateAndSetWeight () {
this.weight = this.left === undefined ? this.fragment.length : Rope.getWeightInternal(this.left)
}
private checkRecalculation () {
if (this.hasToRecaluclateWeights) {
this.calculateAndSetWeight()
this.hasToRecaluclateWeights = false
}
}
}
|
4c8705a6f372281a1388f66e06775cf6faae5024 | 1,907 | ts | TypeScript | src/index.ts | osteele/terminal-codes-to-html | da618b7a75f397571c2a9a2844d95865cc48e1f0 | [
"MIT"
] | 1 | 2022-02-25T07:13:41.000Z | 2022-02-25T07:13:41.000Z | src/index.ts | osteele/terminal-codes-to-html | da618b7a75f397571c2a9a2844d95865cc48e1f0 | [
"MIT"
] | null | null | null | src/index.ts | osteele/terminal-codes-to-html | da618b7a75f397571c2a9a2844d95865cc48e1f0 | [
"MIT"
] | null | null | null | const escapeCodeColors = [
"black",
"red",
"green",
"yellow",
"blue",
"magenta",
"cyan",
"white",
];
const colorNamesToRGB: Record<string, number> = {
black: 0x000000,
red: 0xcc0000,
green: 0x4e9a06,
yellow: 0xc4a000,
blue: 0x729fcf,
magenta: 0x75507b,
cyan: 0x06989a,
white: 0xd3d7cf,
};
export function removeTerminalCodes(s: string) {
// eslint-disable-next-line no-control-regex
return s.replace(/(\x1b\[\d*m)/g, "");
}
export function terminalCodesToHtml(s: string, usePalette = false): string {
let output = "";
const stack = [];
const state: { color: string | null; background: string | null } = {
color: null,
background: null,
};
// eslint-disable-next-line no-control-regex
for (const f of s.split(/(\x1b\[\d*m)/)) {
if (f.startsWith("\x1b")) {
const code = parseInt(f.slice(2), 10) || 0;
if (code === 0) {
state.color = null;
state.background = null;
} else if (30 <= code && code <= 39) {
state.color = color(code - 30);
} else if (40 <= code && code <= 49) {
state.background = color(code - 40);
}
while (stack.length > 0) output += stack.pop();
const style = Object.entries(state)
.filter(([_k, v]) => v)
.map(([k, v]) => `${k}: ${v}`)
.join(";");
if (style) {
output += `<span style="${style}">`;
stack.push("</span>");
}
} else {
output += f
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
}
}
while (stack.length > 0) output += stack.pop();
return output;
function color(code: number) {
if (code >= 8) return null;
const name = escapeCodeColors[code];
if (usePalette) {
const hex = (0x1000000 + colorNamesToRGB[name]).toString(16).substring(1);
return `#${hex}`;
} else {
return name;
}
}
}
| 24.766234 | 80 | 0.541164 | 70 | 5 | 0 | 6 | 9 | 0 | 1 | 0 | 8 | 0 | 0 | 11.2 | 653 | 0.016845 | 0.013783 | 0 | 0 | 0 | 0 | 0.4 | 0.254243 | const escapeCodeColors = [
"black",
"red",
"green",
"yellow",
"blue",
"magenta",
"cyan",
"white",
];
const colorNamesToRGB = {
black: 0x000000,
red: 0xcc0000,
green: 0x4e9a06,
yellow: 0xc4a000,
blue: 0x729fcf,
magenta: 0x75507b,
cyan: 0x06989a,
white: 0xd3d7cf,
};
export function removeTerminalCodes(s) {
// eslint-disable-next-line no-control-regex
return s.replace(/(\x1b\[\d*m)/g, "");
}
export function terminalCodesToHtml(s, usePalette = false) {
let output = "";
const stack = [];
const state = {
color: null,
background: null,
};
// eslint-disable-next-line no-control-regex
for (const f of s.split(/(\x1b\[\d*m)/)) {
if (f.startsWith("\x1b")) {
const code = parseInt(f.slice(2), 10) || 0;
if (code === 0) {
state.color = null;
state.background = null;
} else if (30 <= code && code <= 39) {
state.color = color(code - 30);
} else if (40 <= code && code <= 49) {
state.background = color(code - 40);
}
while (stack.length > 0) output += stack.pop();
const style = Object.entries(state)
.filter(([_k, v]) => v)
.map(([k, v]) => `${k}: ${v}`)
.join(";");
if (style) {
output += `<span style="${style}">`;
stack.push("</span>");
}
} else {
output += f
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
}
}
while (stack.length > 0) output += stack.pop();
return output;
/* Example usages of 'color' are shown below:
;
state.color = null;
state.color = color(code - 30);
state.background = color(code - 40);
*/
function color(code) {
if (code >= 8) return null;
const name = escapeCodeColors[code];
if (usePalette) {
const hex = (0x1000000 + colorNamesToRGB[name]).toString(16).substring(1);
return `#${hex}`;
} else {
return name;
}
}
}
|
4cf3f56f9e9718eaad8dc6f2e853ec4deabd5c81 | 1,431 | ts | TypeScript | src/method/object.ts | vodyani/core | 160f437f572ee3bca27fe246355d032a37c1a5fe | [
"MIT"
] | 2 | 2022-03-16T10:54:46.000Z | 2022-03-17T02:18:17.000Z | src/method/object.ts | vodyani/core | 160f437f572ee3bca27fe246355d032a37c1a5fe | [
"MIT"
] | 2 | 2022-03-16T10:24:15.000Z | 2022-03-20T04:26:29.000Z | src/method/object.ts | vodyani/core | 160f437f572ee3bca27fe246355d032a37c1a5fe | [
"MIT"
] | null | null | null | export function isKeyof(data: object, key: string | number | symbol): key is keyof typeof data {
return key in data && Object.prototype.hasOwnProperty.call(data, key);
}
export function toMatchProperties<T = any>(data: object, properties: string, rule = '.'): T {
if (!data || !properties) {
return null;
}
const stack = [];
const factors = properties.split(rule);
let node;
let nodeResult = null;
let nodeDeepLevel = 0;
stack.push(data);
while (stack.length > 0) {
node = stack.pop();
if (nodeDeepLevel === factors.length) {
nodeResult = node;
break;
}
if (node) {
for (const key of Object.keys(node)) {
const indexResult = factors.indexOf(key);
const factorResult = factors[nodeDeepLevel];
if (key === factorResult && indexResult === nodeDeepLevel) {
stack.push((node as any)[key]);
nodeDeepLevel += 1;
break;
}
}
}
}
return nodeResult;
}
export function toRestoreProperties<T = any>(value: any, properties: string, rule = '.'): T {
if (!properties) {
return null;
}
const factors = properties.split(rule);
const object = Object();
let node = object;
while (factors.length > 0) {
const key = factors.shift();
node[key] = Object();
if (factors.length === 0) {
node[key] = value;
} else {
node = node[key];
}
}
return object;
}
| 20.73913 | 96 | 0.591195 | 51 | 3 | 0 | 8 | 11 | 0 | 0 | 4 | 7 | 0 | 1 | 15 | 391 | 0.028133 | 0.028133 | 0 | 0 | 0.002558 | 0.181818 | 0.318182 | 0.324155 | export function isKeyof(data, key): key is keyof typeof data {
return key in data && Object.prototype.hasOwnProperty.call(data, key);
}
export function toMatchProperties<T = any>(data, properties, rule = '.') {
if (!data || !properties) {
return null;
}
const stack = [];
const factors = properties.split(rule);
let node;
let nodeResult = null;
let nodeDeepLevel = 0;
stack.push(data);
while (stack.length > 0) {
node = stack.pop();
if (nodeDeepLevel === factors.length) {
nodeResult = node;
break;
}
if (node) {
for (const key of Object.keys(node)) {
const indexResult = factors.indexOf(key);
const factorResult = factors[nodeDeepLevel];
if (key === factorResult && indexResult === nodeDeepLevel) {
stack.push((node as any)[key]);
nodeDeepLevel += 1;
break;
}
}
}
}
return nodeResult;
}
export function toRestoreProperties<T = any>(value, properties, rule = '.') {
if (!properties) {
return null;
}
const factors = properties.split(rule);
const object = Object();
let node = object;
while (factors.length > 0) {
const key = factors.shift();
node[key] = Object();
if (factors.length === 0) {
node[key] = value;
} else {
node = node[key];
}
}
return object;
}
|
Subsets and Splits