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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b350ec9afb7525ac8312058890c66c9660eef021 | 1,690 | ts | TypeScript | src/utils/sort-inner-arrays.ts | RexSkz/json-diff-kit | 339bac1947e69ba3a7bab2cc648a916814ee8d62 | [
"MIT"
] | 8 | 2022-02-09T07:58:55.000Z | 2022-03-28T10:54:19.000Z | src/utils/sort-inner-arrays.ts | RexSkz/json-diff-kit | 339bac1947e69ba3a7bab2cc648a916814ee8d62 | [
"MIT"
] | null | null | null | src/utils/sort-inner-arrays.ts | RexSkz/json-diff-kit | 339bac1947e69ba3a7bab2cc648a916814ee8d62 | [
"MIT"
] | null | null | null | /**
* The compare function to correct the order for "array" or "object":
* - The order for 2 values with different types are: boolean, number, string, null, array, object.
* - The order for 2 values with the same type is according to the type:
* - For boolean, number, string: use the `<` sign.
* - For array and object: preserve the original order (or do we have a better idea?)
*/
const getOrderByType = (value: any) => {
if (typeof value === 'boolean') {
return 0;
}
if (typeof value === 'number') {
return 1;
}
if (typeof value === 'string') {
return 2;
}
if (value === null) {
return 3;
}
if (Array.isArray(value)) {
return 4;
}
if (typeof value === 'object') {
return 5;
}
};
const cmp = (a: any, b: any) => {
const orderByTypeA = getOrderByType(a);
const orderByTypeB = getOrderByType(b);
if (orderByTypeA !== orderByTypeB) {
return orderByTypeA - orderByTypeB;
}
if (a === null && b === null || Array.isArray(a) && Array.isArray(b) || orderByTypeA === 5 && orderByTypeB === 5) {
return 0;
}
switch (typeof a) {
case 'number':
return a - b;
case 'string':
return a.localeCompare(b);
case 'boolean':
return (+a) - (+b);
}
};
const sortInnerArrays = (source: any) => {
if (!source || typeof source !== 'object') {
return source;
}
if (Array.isArray(source)) {
const result = [...source];
result.sort((a, b) => cmp(a, b));
return result.map(item => sortInnerArrays(item));
}
const result = { ...source };
for (const key in result) {
result[key] = sortInnerArrays(result[key]);
}
return result;
};
export default sortInnerArrays;
| 23.802817 | 117 | 0.593491 | 54 | 5 | 0 | 7 | 7 | 0 | 3 | 4 | 0 | 0 | 6 | 9.8 | 509 | 0.023576 | 0.013752 | 0 | 0 | 0.011788 | 0.210526 | 0 | 0.265792 | /**
* The compare function to correct the order for "array" or "object":
* - The order for 2 values with different types are: boolean, number, string, null, array, object.
* - The order for 2 values with the same type is according to the type:
* - For boolean, number, string: use the `<` sign.
* - For array and object: preserve the original order (or do we have a better idea?)
*/
/* Example usages of 'getOrderByType' are shown below:
getOrderByType(a);
getOrderByType(b);
*/
const getOrderByType = (value) => {
if (typeof value === 'boolean') {
return 0;
}
if (typeof value === 'number') {
return 1;
}
if (typeof value === 'string') {
return 2;
}
if (value === null) {
return 3;
}
if (Array.isArray(value)) {
return 4;
}
if (typeof value === 'object') {
return 5;
}
};
/* Example usages of 'cmp' are shown below:
cmp(a, b);
*/
const cmp = (a, b) => {
const orderByTypeA = getOrderByType(a);
const orderByTypeB = getOrderByType(b);
if (orderByTypeA !== orderByTypeB) {
return orderByTypeA - orderByTypeB;
}
if (a === null && b === null || Array.isArray(a) && Array.isArray(b) || orderByTypeA === 5 && orderByTypeB === 5) {
return 0;
}
switch (typeof a) {
case 'number':
return a - b;
case 'string':
return a.localeCompare(b);
case 'boolean':
return (+a) - (+b);
}
};
/* Example usages of 'sortInnerArrays' are shown below:
sortInnerArrays(item);
result[key] = sortInnerArrays(result[key]);
;
*/
const sortInnerArrays = (source) => {
if (!source || typeof source !== 'object') {
return source;
}
if (Array.isArray(source)) {
const result = [...source];
result.sort((a, b) => cmp(a, b));
return result.map(item => sortInnerArrays(item));
}
const result = { ...source };
for (const key in result) {
result[key] = sortInnerArrays(result[key]);
}
return result;
};
export default sortInnerArrays;
|
b36cde52744c4f1c3282c28def200b23a577ef0c | 2,025 | ts | TypeScript | services/oneBot/src/filter.ts | lc-cn/oicq-bots | 9ec23b98c3700bdb8bca203084208a3f092d35f0 | [
"MIT"
] | 1 | 2022-03-19T09:32:25.000Z | 2022-03-19T09:32:25.000Z | plugins/oneBot/src/filter.ts | oitq/oitq | 7f55199ee2f3844b1720d53aa5b20acacde5e765 | [
"MIT"
] | null | null | null | plugins/oneBot/src/filter.ts | oitq/oitq | 7f55199ee2f3844b1720d53aa5b20acacde5e765 | [
"MIT"
] | null | null | null | //@ts-nocheck
let event: any;
function _exec(o: any, op = "and", field): boolean {
if (["and", "not", "or"].includes(op)) {
if (Array.isArray(o)) {
for (let rule of o) {
let matched = _exec(rule, "and", field);
if (!matched && op === "and")
return false;
if (matched && op === "not")
return false;
if (matched && op === "or")
return true;
}
return op !== "or" || !o.length;
} else if (typeof o === "object" && o !== null) {
for (let k in o) {
let matched;
if (k.startsWith("."))
matched = _exec(o[k], k.substr(1), field);
else
matched = _exec(o[k], "eq", k);
if (!matched && op === "and")
return false;
if (matched && op === "not")
return false;
if (matched && op === "or")
return true;
}
return op !== "or" || !Object.keys(o).length;
} else {
return false;
}
}
if (typeof o === "object" && o !== null && !Array.isArray(o))
return _exec(o, "and", field);
if (op === "eq") {
return o === event[field];
}
if (op === "neq") {
return o !== event[field];
}
if (op === "in") {
return o.includes(event[field]);
}
if (op === "contains") {
return event[field].includes(o);
}
if (op === "regex") {
if (o.startsWith("/"))
o = o.substr(1);
const split = o.split("/");
const regex = new RegExp(split[0], split[1]);
return !!event[field].match(regex);
}
return true;
}
export function assert(filter: any, e: any) {
if (!filter)
return true;
event = e;
try {
return _exec(filter);
} catch {
return false;
}
}
| 25.632911 | 65 | 0.401975 | 66 | 2 | 0 | 5 | 5 | 0 | 1 | 4 | 1 | 0 | 2 | 30.5 | 515 | 0.013592 | 0.009709 | 0 | 0 | 0.003883 | 0.333333 | 0.083333 | 0.227924 | //@ts-nocheck
let event;
/* Example usages of '_exec' are shown below:
_exec(rule, "and", field);
matched = _exec(o[k], k.substr(1), field);
matched = _exec(o[k], "eq", k);
_exec(o, "and", field);
_exec(filter);
*/
function _exec(o, op = "and", field) {
if (["and", "not", "or"].includes(op)) {
if (Array.isArray(o)) {
for (let rule of o) {
let matched = _exec(rule, "and", field);
if (!matched && op === "and")
return false;
if (matched && op === "not")
return false;
if (matched && op === "or")
return true;
}
return op !== "or" || !o.length;
} else if (typeof o === "object" && o !== null) {
for (let k in o) {
let matched;
if (k.startsWith("."))
matched = _exec(o[k], k.substr(1), field);
else
matched = _exec(o[k], "eq", k);
if (!matched && op === "and")
return false;
if (matched && op === "not")
return false;
if (matched && op === "or")
return true;
}
return op !== "or" || !Object.keys(o).length;
} else {
return false;
}
}
if (typeof o === "object" && o !== null && !Array.isArray(o))
return _exec(o, "and", field);
if (op === "eq") {
return o === event[field];
}
if (op === "neq") {
return o !== event[field];
}
if (op === "in") {
return o.includes(event[field]);
}
if (op === "contains") {
return event[field].includes(o);
}
if (op === "regex") {
if (o.startsWith("/"))
o = o.substr(1);
const split = o.split("/");
const regex = new RegExp(split[0], split[1]);
return !!event[field].match(regex);
}
return true;
}
export function assert(filter, e) {
if (!filter)
return true;
event = e;
try {
return _exec(filter);
} catch {
return false;
}
}
|
b3a95cd9c8ab0fd31af880468df9d4a43f378cb6 | 2,010 | ts | TypeScript | packages/bridge-extension-handler/src/models/Caller.ts | smartsheet-bridge/create-bridge-extension | ab68045cc05312ee94ae4edf30c16b1e177af05d | [
"Apache-2.0"
] | 4 | 2022-01-04T10:42:03.000Z | 2022-03-30T15:53:41.000Z | packages/bridge-extension-handler/src/models/Caller.ts | smartsheet-bridge/create-bridge-extension | ab68045cc05312ee94ae4edf30c16b1e177af05d | [
"Apache-2.0"
] | null | null | null | packages/bridge-extension-handler/src/models/Caller.ts | smartsheet-bridge/create-bridge-extension | ab68045cc05312ee94ae4edf30c16b1e177af05d | [
"Apache-2.0"
] | null | null | null | interface Invoker {
userUUID: string;
email?: string;
firstName?: string;
lastName?: string;
admin?: boolean;
systemAdmin?: boolean;
providerUUID?: string;
}
interface Provider {
providerUUID: string;
workspaceUUID: string;
providerDomain?: string;
}
interface CallToken {
validUntil: number;
signature: string;
}
export interface Caller {
invoker: Invoker;
provider: Provider;
callTime: number;
msgid: string;
installUUID: string;
pluginUUID: string;
callToken: CallToken;
revision: string;
instanceID?: string;
}
export class Caller {
/**
* the bridge user that executed the function.
*/
invoker: Invoker;
/**
* the bridge account that executed the function.
*/
provider: Provider;
/**
* unix timestamp of when the function was executed.
*/
callTime: number;
/**
* unique identifier for this function request.
*/
msgid: string;
/**
* unique identifer for the extension runner.
*/
installUUID: string;
/**
* unique identifier for the bridge extension.
*/
pluginUUID: string;
/**
* an object used to validate the caller.
*/
callToken: CallToken;
/**
* the extension revision code.
*/
revision: string;
/**
* an identifer for the extension runner instance.
*/
instanceID?: string;
public static create(props: Partial<Caller> = {}) {
return new Caller(props);
}
public constructor({
invoker,
provider,
callTime,
msgid,
installUUID,
pluginUUID,
callToken,
revision,
instanceID,
}: Partial<Caller> = {}) {
if (invoker) this.invoker = invoker;
if (provider) this.provider = provider;
if (callTime) this.callTime = callTime;
if (msgid) this.msgid = msgid;
if (installUUID) this.installUUID = installUUID;
if (pluginUUID) this.pluginUUID = pluginUUID;
if (callToken) this.callToken = callToken;
if (revision) this.revision = revision;
if (instanceID) this.instanceID = instanceID;
}
}
| 18.962264 | 54 | 0.655224 | 64 | 2 | 0 | 2 | 0 | 30 | 0 | 0 | 24 | 5 | 0 | 5 | 526 | 0.007605 | 0 | 0.057034 | 0.009506 | 0 | 0 | 0.705882 | 0.202233 | interface Invoker {
userUUID;
email?;
firstName?;
lastName?;
admin?;
systemAdmin?;
providerUUID?;
}
interface Provider {
providerUUID;
workspaceUUID;
providerDomain?;
}
interface CallToken {
validUntil;
signature;
}
export interface Caller {
invoker;
provider;
callTime;
msgid;
installUUID;
pluginUUID;
callToken;
revision;
instanceID?;
}
export class Caller {
/**
* the bridge user that executed the function.
*/
invoker;
/**
* the bridge account that executed the function.
*/
provider;
/**
* unix timestamp of when the function was executed.
*/
callTime;
/**
* unique identifier for this function request.
*/
msgid;
/**
* unique identifer for the extension runner.
*/
installUUID;
/**
* unique identifier for the bridge extension.
*/
pluginUUID;
/**
* an object used to validate the caller.
*/
callToken;
/**
* the extension revision code.
*/
revision;
/**
* an identifer for the extension runner instance.
*/
instanceID?;
public static create(props = {}) {
return new Caller(props);
}
public constructor({
invoker,
provider,
callTime,
msgid,
installUUID,
pluginUUID,
callToken,
revision,
instanceID,
} = {}) {
if (invoker) this.invoker = invoker;
if (provider) this.provider = provider;
if (callTime) this.callTime = callTime;
if (msgid) this.msgid = msgid;
if (installUUID) this.installUUID = installUUID;
if (pluginUUID) this.pluginUUID = pluginUUID;
if (callToken) this.callToken = callToken;
if (revision) this.revision = revision;
if (instanceID) this.instanceID = instanceID;
}
}
|
b3d650b91e31795c02e556fe0094ad34611d1255 | 1,451 | ts | TypeScript | src/channels/socket-io-channel.ts | yubarajshrestha/masonite-broadcast-client | 2afc99380abb6c445bce0a9b1c23d0c738431d17 | [
"MIT"
] | 4 | 2022-01-09T20:26:38.000Z | 2022-03-14T04:44:40.000Z | src/channels/socket-io-channel.ts | yubarajshrestha/masonite-broadcast-client | 2afc99380abb6c445bce0a9b1c23d0c738431d17 | [
"MIT"
] | null | null | null | src/channels/socket-io-channel.ts | yubarajshrestha/masonite-broadcast-client | 2afc99380abb6c445bce0a9b1c23d0c738431d17 | [
"MIT"
] | null | null | null | export class SocketIoChannel {
socket: any;
options: any;
name: any;
private listeners: any = {};
constructor(socket, name, options) {
this.socket = socket;
this.name = name;
this.options = options;
this.listeners = {};
this.subscribe();
}
speak(event: any, data: Object): SocketIoChannel {
this.socket.emit('speak', {
channel: this.name,
event: event,
message: data,
auth: this.options.authToken || {}
});
return this;
}
whisper(event: any, data: Object): SocketIoChannel {
this.socket.emit('whisper', {
channel: this.name,
event: event,
message: data,
auth: this.options.authToken || {}
});
return this;
}
listen(event: any, callback: Function): SocketIoChannel {
if (!this.listeners[event]) {
this.listeners[event] = (data) => {
callback(data);
}
this.socket.on(event, this.listeners[event]);
}
return this;
}
subscribe(): void {
this.socket.emit('subscribe', {
channel: this.name,
auth: this.options.authToken || null
});
}
unsubscribe(): void {
this.socket.emit('unsubscribe', {
channel: this.name,
auth: this.options.auth || {}
});
}
} | 25.017241 | 61 | 0.500345 | 52 | 7 | 0 | 10 | 0 | 4 | 1 | 8 | 2 | 1 | 0 | 5 | 337 | 0.050445 | 0 | 0.011869 | 0.002967 | 0 | 0.380952 | 0.095238 | 0.286949 | export class SocketIoChannel {
socket;
options;
name;
private listeners = {};
constructor(socket, name, options) {
this.socket = socket;
this.name = name;
this.options = options;
this.listeners = {};
this.subscribe();
}
speak(event, data) {
this.socket.emit('speak', {
channel: this.name,
event: event,
message: data,
auth: this.options.authToken || {}
});
return this;
}
whisper(event, data) {
this.socket.emit('whisper', {
channel: this.name,
event: event,
message: data,
auth: this.options.authToken || {}
});
return this;
}
listen(event, callback) {
if (!this.listeners[event]) {
this.listeners[event] = (data) => {
callback(data);
}
this.socket.on(event, this.listeners[event]);
}
return this;
}
subscribe() {
this.socket.emit('subscribe', {
channel: this.name,
auth: this.options.authToken || null
});
}
unsubscribe() {
this.socket.emit('unsubscribe', {
channel: this.name,
auth: this.options.auth || {}
});
}
} |
b3dd3889c56d04a5df4dda54ed61bd873ddd1236 | 9,091 | ts | TypeScript | src/plugins/jjzgenerator/generator.ts | Thungghuan/LvBao | 80831101f79ca50257830a863a9df7bd49418a47 | [
"MIT"
] | 3 | 2022-01-16T08:13:36.000Z | 2022-02-11T14:15:53.000Z | src/plugins/jjzgenerator/generator.ts | Thungghuan/LvBao | 80831101f79ca50257830a863a9df7bd49418a47 | [
"MIT"
] | null | null | null | src/plugins/jjzgenerator/generator.ts | Thungghuan/LvBao | 80831101f79ca50257830a863a9df7bd49418a47 | [
"MIT"
] | null | null | null | // MODIFY FROM https://github.com/kingcos/JueJueZiGenerator
// JueJueZiGenerator
// --- SETUPS ---
const matierailsJSON = `
{
"emotions": {
"emoji": [
"😊",
"🌟",
"🧩",
"✨",
"☀️",
"🌹",
"🌸",
"🌼",
"🥝",
"🥤",
"🍑",
"🍹",
"🥑",
"🙋♀️",
"🎀",
"❤️",
"🧡",
"💛",
"💚",
"💙",
"💜",
"🖤",
"🤍",
"🤎",
"💕",
"💞",
"💓",
"💗",
"💖",
"💝"
],
"xiaohongshu": [
"[微笑R]",
"[害羞R]",
"[失望R]",
"[汗颜R]",
"[哇R]",
"[喝奶茶R]",
"[自拍R]",
"[偷笑R]",
"[飞吻R]",
"[石化R]",
"[笑哭R]",
"[赞R]",
"[暗中观察R]",
"[买爆R]",
"[大笑R]",
"[色色R]",
"[生气R]",
"[哭惹R]",
"[萌萌哒R]",
"[斜眼R]",
"[可怜R]",
"[鄙视R]",
"[皱眉R]",
"[抓狂R]",
"[派对R]",
"[吧唧R]",
"[惊恐R]",
"[抠鼻R]",
"[再见R]",
"[叹气R]",
"[睡觉R]",
"[得意R]",
"[吃瓜R]",
"[扶墙R]",
"[黑薯问号R]",
"[黄金薯R]",
"[吐舌头H]",
"[扯脸H]",
"[doge]"
],
"weibo": []
},
"symbols": [
"!",
"?",
"~",
"❓",
"❔",
"‼️",
"⁉️",
"❗️",
"❕"
],
"auxiliaryWords": [
"鸭",
"呜",
"啦",
"呐",
"呀",
"咩",
"呢",
"哈",
"嘿",
"哒",
"害",
"啊"
],
"dividers": [
" ",
","
],
"beginning": [
"今日份who营业啦",
"who下班啦",
"投递日常",
"今天的who也营业啦",
"今日份甜甜碎片已加载完毕",
"忙里偷闲的生活碎片",
"和someone逛吃的一天",
"分享開心",
"分享今日份開心",
"营业一下"
],
"who": [
"打工人",
"仙女",
"普信男",
"Java男",
"普信女",
"小可爱",
"本公主"
],
"someone": [
"小狗勾",
"小姐姐",
"集美",
"集美们",
"闺蜜",
"闺蜜👭",
"姐妹",
"姐妹们",
"姐妹👭",
"好姐妹",
"好姐妹👭",
"小姐妹",
"小姐妹👭"
],
"todosth": [
"今天去dosth",
"今天去dosth了",
"今天去dosth啦",
"今天去dosth鸭",
"今天去dosth噜",
"今天又又又dosth啦",
"今天又又又dosth鸭",
"又去dosth啦",
"又是dosth的一天啦",
"今天又是dosth的一天啦",
"宝~我今天dosth了",
"宝!我今天dosth了",
"还是去dosth了",
"无聊去dosth",
"今天去体验了dosth"
],
"another": [
"买 小蛋糕",
"买 小布丁",
"喝 奶茶",
"穿 JK",
"吃 迷hotel",
"喝 咖啡",
"买 蜜雪冰城",
"买 喜茶",
"喝 谬可"
],
"ending": [
"也是在逃公主的一天",
"好想谈一场双向奔赴的恋爱",
"星星月亮和我都要睡啦",
"散会",
"我是一面镜子 所以 晚安 我碎啦",
"岁月漫长 那就一起拯救地球与乐趣吧"
],
"collections": [
"路上还看见一个普信男",
"路边捡到了一分钱",
"不小心踩了狗屎",
"路上还看见一个Java男"
],
"attribute": [
"绝绝子",
"无语子",
"真下头",
"yyds",
"奈斯",
"有被惊艳到",
"🉑️",
"太可了",
"太🉑️了",
"真的绝",
"太牛了",
"太🐮了",
"好dosth到跺脚",
"好dosth到爆",
"好dosth到跺jiojio",
"太爱了"
],
"fashion": [
"救命🆘",
"噎死莫拉",
"不管啦",
"就是玩儿",
"无语子",
"我真的哭死",
"冲鸭",
"笑死",
"那我走",
"我都惊了",
"大无语事件",
"就很烦",
"心态炸裂",
"搞快点",
"不是吧",
"不是8⃣️",
"全都给我冲",
"啥也不是"
],
"default": [
"豁 奶茶",
"撸 代码",
"刷 微博",
"买 基金",
"摸 鱼",
"玩 绝绝子生成器"
]
}
`
const ContentLengthConstraint = 300 // 内容长度约束
// --- INTERFACES ---
interface Matierail {
emotions: {
// 表情
emoji: string[]
xiaohongshu: string[]
weibo: string[]
}
symbols: string[]
auxiliaryWords: string[]
dividers: string[] // 断句符
fashion: string[] // 潮流
attribute: string[] // 定语
beginning: string[] // 开头
ending: string[] // 结尾
who: string[] // 主语
someone: string[] // 和/跟谁
todosth: string[] // 干什么
another: string[] // 扯另一个淡
collections: string[] // 一些固定搭配
default: string[] // 默认 something
}
// --- UTILITIES ---
function parseMatieraials(matierailsJSON: string): Matierail {
return JSON.parse(matierailsJSON)
}
function randomWord(words: string[], nullable = false, divider = ''): string {
var maxRange = words.length
if (nullable) {
// 增加 1/3 概率
maxRange += maxRange / 3
}
var index = Math.floor(Math.random() * maxRange)
if (index >= words.length) {
return ''
} else {
return words[index] + divider
}
}
function randomWords(words: string[], count: number): string[] {
if (words.length < count) {
return words
}
// Inspired by: https://www.imooc.com/wenda/detail/440036
return words.sort(() => Math.random() - 0.5).slice(0, count)
}
function randomRepeat(word: string, times = -1): string {
if (times > 0) {
var result = ''
for (let index = 0; index < times; index++) {
result += word
}
return result
}
var index = Math.floor(Math.random() * 3)
if (index == 2) {
return randomRepeat(word, 3)
}
if (index == 0) {
return randomRepeat(word, 1)
}
return ''
}
// --- CORE ---
function generateBeginning(matierail: Matierail, divider: string) {
var beginning = randomWord(matierail.beginning)
if (beginning.indexOf('who') != -1) {
// 拼 who
beginning = beginning.replace('who', randomWord(matierail.who))
}
if (beginning.indexOf('someone') != -1) {
// 拼 someone
beginning = beginning.replace('someone', randomWord(matierail.someone))
}
var emotion = randomWord(matierail.emotions.emoji, true)
// if (emotion == '') {
// emotion = divider
// }
return beginning + emotion + divider
}
function generateDoSth(
matierail: Matierail,
something: string,
divider: string
): string {
var todosth = randomWord(matierail.todosth)
if (todosth.indexOf('dosth') != -1) {
// 拼 something
if (something.indexOf(' ') != -1) {
something = something.replace(' ', '') // 去间隔
}
todosth = todosth.replace('dosth', something)
}
// 拼 emotions
var emotions = randomRepeat(randomWord(matierail.emotions.emoji))
// if (emotions.length == 0) {
// emotions = divider
// }
return todosth + emotions + divider
}
function praiseSth(
something: string,
praisedWords: string[],
hasAlso = false
): string {
var praiseWord = randomWord(praisedWords)
var verb = something.split(' ')[0]
var noun = something.split(' ')[1]
var result = ''
var intro = randomWord(['这家的', '这家店的', '这个', '这件', '这杯'])
var also = hasAlso ? '也' : ''
if (praiseWord.indexOf('dosth') != -1) {
// eg. 好dosth到爆
praiseWord = praiseWord.replace('dosth', verb)
result = intro + noun + also + praiseWord
} else {
// eg. 绝绝子
result = intro + noun + also + praiseWord
}
return result
}
function randomButNotContain(words: string[], already: string): string {
var random = randomWord(words)
// Inspired by: https://www.cnblogs.com/mengff/p/7350005.html
var set = new Set(already.replace(' ', '').split(''))
var intersect = new Set(
random
.replace(' ', '')
.split('')
.filter((x) => set.has(x))
)
if (Array.from(intersect).length == 0) {
return random
} else {
return randomButNotContain(words, already)
}
}
export function generate(something: string): string {
var matierail = parseMatieraials(matierailsJSON)
// 开场白
var divider = randomWord(matierail.dividers) // 分隔符
var fashionWords = randomWords(matierail.fashion, matierail.fashion.length) // 不重复的词组
var first = generateBeginning(matierail, divider)
var second = fashionWords[0] + divider
var third = generateDoSth(matierail, something, divider)
var forth = fashionWords[1] + divider
var fifth = randomRepeat(randomWord(matierail.auxiliaryWords), 3) + divider
var sixth =
praiseSth(something, matierail.attribute) +
randomRepeat(randomWord(matierail.symbols), 3)
var seventh =
praiseSth(
randomButNotContain(matierail.another, something),
matierail.attribute,
true
) + randomRepeat(randomWord(matierail.symbols), 3)
var eighth = fashionWords[2] + divider
var ninth =
randomWord(matierail.collections, true, divider) + fashionWords[3] + divider
var tenth = randomRepeat(randomWord(matierail.auxiliaryWords), 3) + divider
var last = randomWord(matierail.ending) + randomWord(matierail.emotions.emoji)
return (
first +
second +
third +
forth +
fifth +
sixth +
seventh +
eighth +
ninth +
tenth +
last
)
}
| 20.202222 | 87 | 0.456935 | 389 | 11 | 0 | 20 | 34 | 14 | 8 | 0 | 36 | 1 | 0 | 10.090909 | 3,381 | 0.009169 | 0.010056 | 0.004141 | 0.000296 | 0 | 0 | 0.455696 | 0.226286 | // MODIFY FROM https://github.com/kingcos/JueJueZiGenerator
// JueJueZiGenerator
// --- SETUPS ---
const matierailsJSON = `
{
"emotions": {
"emoji": [
"😊",
"🌟",
"🧩",
"✨",
"☀️",
"🌹",
"🌸",
"🌼",
"🥝",
"🥤",
"🍑",
"🍹",
"🥑",
"🙋♀️",
"🎀",
"❤️",
"🧡",
"💛",
"💚",
"💙",
"💜",
"🖤",
"🤍",
"🤎",
"💕",
"💞",
"💓",
"💗",
"💖",
"💝"
],
"xiaohongshu": [
"[微笑R]",
"[害羞R]",
"[失望R]",
"[汗颜R]",
"[哇R]",
"[喝奶茶R]",
"[自拍R]",
"[偷笑R]",
"[飞吻R]",
"[石化R]",
"[笑哭R]",
"[赞R]",
"[暗中观察R]",
"[买爆R]",
"[大笑R]",
"[色色R]",
"[生气R]",
"[哭惹R]",
"[萌萌哒R]",
"[斜眼R]",
"[可怜R]",
"[鄙视R]",
"[皱眉R]",
"[抓狂R]",
"[派对R]",
"[吧唧R]",
"[惊恐R]",
"[抠鼻R]",
"[再见R]",
"[叹气R]",
"[睡觉R]",
"[得意R]",
"[吃瓜R]",
"[扶墙R]",
"[黑薯问号R]",
"[黄金薯R]",
"[吐舌头H]",
"[扯脸H]",
"[doge]"
],
"weibo": []
},
"symbols": [
"!",
"?",
"~",
"❓",
"❔",
"‼️",
"⁉️",
"❗️",
"❕"
],
"auxiliaryWords": [
"鸭",
"呜",
"啦",
"呐",
"呀",
"咩",
"呢",
"哈",
"嘿",
"哒",
"害",
"啊"
],
"dividers": [
" ",
","
],
"beginning": [
"今日份who营业啦",
"who下班啦",
"投递日常",
"今天的who也营业啦",
"今日份甜甜碎片已加载完毕",
"忙里偷闲的生活碎片",
"和someone逛吃的一天",
"分享開心",
"分享今日份開心",
"营业一下"
],
"who": [
"打工人",
"仙女",
"普信男",
"Java男",
"普信女",
"小可爱",
"本公主"
],
"someone": [
"小狗勾",
"小姐姐",
"集美",
"集美们",
"闺蜜",
"闺蜜👭",
"姐妹",
"姐妹们",
"姐妹👭",
"好姐妹",
"好姐妹👭",
"小姐妹",
"小姐妹👭"
],
"todosth": [
"今天去dosth",
"今天去dosth了",
"今天去dosth啦",
"今天去dosth鸭",
"今天去dosth噜",
"今天又又又dosth啦",
"今天又又又dosth鸭",
"又去dosth啦",
"又是dosth的一天啦",
"今天又是dosth的一天啦",
"宝~我今天dosth了",
"宝!我今天dosth了",
"还是去dosth了",
"无聊去dosth",
"今天去体验了dosth"
],
"another": [
"买 小蛋糕",
"买 小布丁",
"喝 奶茶",
"穿 JK",
"吃 迷hotel",
"喝 咖啡",
"买 蜜雪冰城",
"买 喜茶",
"喝 谬可"
],
"ending": [
"也是在逃公主的一天",
"好想谈一场双向奔赴的恋爱",
"星星月亮和我都要睡啦",
"散会",
"我是一面镜子 所以 晚安 我碎啦",
"岁月漫长 那就一起拯救地球与乐趣吧"
],
"collections": [
"路上还看见一个普信男",
"路边捡到了一分钱",
"不小心踩了狗屎",
"路上还看见一个Java男"
],
"attribute": [
"绝绝子",
"无语子",
"真下头",
"yyds",
"奈斯",
"有被惊艳到",
"🉑️",
"太可了",
"太🉑️了",
"真的绝",
"太牛了",
"太🐮了",
"好dosth到跺脚",
"好dosth到爆",
"好dosth到跺jiojio",
"太爱了"
],
"fashion": [
"救命🆘",
"噎死莫拉",
"不管啦",
"就是玩儿",
"无语子",
"我真的哭死",
"冲鸭",
"笑死",
"那我走",
"我都惊了",
"大无语事件",
"就很烦",
"心态炸裂",
"搞快点",
"不是吧",
"不是8⃣️",
"全都给我冲",
"啥也不是"
],
"default": [
"豁 奶茶",
"撸 代码",
"刷 微博",
"买 基金",
"摸 鱼",
"玩 绝绝子生成器"
]
}
`
const ContentLengthConstraint = 300 // 内容长度约束
// --- INTERFACES ---
interface Matierail {
emotions
symbols
auxiliaryWords
dividers // 断句符
fashion // 潮流
attribute // 定语
beginning // 开头
ending // 结尾
who // 主语
someone // 和/跟谁
todosth // 干什么
another // 扯另一个淡
collections // 一些固定搭配
default // 默认 something
}
// --- UTILITIES ---
/* Example usages of 'parseMatieraials' are shown below:
parseMatieraials(matierailsJSON);
*/
function parseMatieraials(matierailsJSON) {
return JSON.parse(matierailsJSON)
}
/* Example usages of 'randomWord' are shown below:
randomWord(matierail.beginning);
// 拼 who
beginning = beginning.replace('who', randomWord(matierail.who));
// 拼 someone
beginning = beginning.replace('someone', randomWord(matierail.someone));
randomWord(matierail.emotions.emoji, true);
randomWord(matierail.todosth);
randomRepeat(randomWord(matierail.emotions.emoji));
randomWord(praisedWords);
randomWord(['这家的', '这家店的', '这个', '这件', '这杯']);
randomWord(words);
randomWord(matierail.dividers) // 分隔符
;
randomRepeat(randomWord(matierail.auxiliaryWords), 3) + divider;
praiseSth(something, matierail.attribute) +
randomRepeat(randomWord(matierail.symbols), 3);
praiseSth(randomButNotContain(matierail.another, something), matierail.attribute, true) + randomRepeat(randomWord(matierail.symbols), 3);
randomWord(matierail.collections, true, divider) + fashionWords[3] + divider;
randomWord(matierail.ending) + randomWord(matierail.emotions.emoji);
*/
function randomWord(words, nullable = false, divider = '') {
var maxRange = words.length
if (nullable) {
// 增加 1/3 概率
maxRange += maxRange / 3
}
var index = Math.floor(Math.random() * maxRange)
if (index >= words.length) {
return ''
} else {
return words[index] + divider
}
}
/* Example usages of 'randomWords' are shown below:
randomWords(matierail.fashion, matierail.fashion.length) // 不重复的词组
;
*/
function randomWords(words, count) {
if (words.length < count) {
return words
}
// Inspired by: https://www.imooc.com/wenda/detail/440036
return words.sort(() => Math.random() - 0.5).slice(0, count)
}
/* Example usages of 'randomRepeat' are shown below:
randomRepeat(word, 3);
randomRepeat(word, 1);
randomRepeat(randomWord(matierail.emotions.emoji));
randomRepeat(randomWord(matierail.auxiliaryWords), 3) + divider;
praiseSth(something, matierail.attribute) +
randomRepeat(randomWord(matierail.symbols), 3);
praiseSth(randomButNotContain(matierail.another, something), matierail.attribute, true) + randomRepeat(randomWord(matierail.symbols), 3);
*/
function randomRepeat(word, times = -1) {
if (times > 0) {
var result = ''
for (let index = 0; index < times; index++) {
result += word
}
return result
}
var index = Math.floor(Math.random() * 3)
if (index == 2) {
return randomRepeat(word, 3)
}
if (index == 0) {
return randomRepeat(word, 1)
}
return ''
}
// --- CORE ---
/* Example usages of 'generateBeginning' are shown below:
generateBeginning(matierail, divider);
*/
function generateBeginning(matierail, divider) {
var beginning = randomWord(matierail.beginning)
if (beginning.indexOf('who') != -1) {
// 拼 who
beginning = beginning.replace('who', randomWord(matierail.who))
}
if (beginning.indexOf('someone') != -1) {
// 拼 someone
beginning = beginning.replace('someone', randomWord(matierail.someone))
}
var emotion = randomWord(matierail.emotions.emoji, true)
// if (emotion == '') {
// emotion = divider
// }
return beginning + emotion + divider
}
/* Example usages of 'generateDoSth' are shown below:
generateDoSth(matierail, something, divider);
*/
function generateDoSth(
matierail,
something,
divider
) {
var todosth = randomWord(matierail.todosth)
if (todosth.indexOf('dosth') != -1) {
// 拼 something
if (something.indexOf(' ') != -1) {
something = something.replace(' ', '') // 去间隔
}
todosth = todosth.replace('dosth', something)
}
// 拼 emotions
var emotions = randomRepeat(randomWord(matierail.emotions.emoji))
// if (emotions.length == 0) {
// emotions = divider
// }
return todosth + emotions + divider
}
/* Example usages of 'praiseSth' are shown below:
praiseSth(something, matierail.attribute) +
randomRepeat(randomWord(matierail.symbols), 3);
praiseSth(randomButNotContain(matierail.another, something), matierail.attribute, true) + randomRepeat(randomWord(matierail.symbols), 3);
*/
function praiseSth(
something,
praisedWords,
hasAlso = false
) {
var praiseWord = randomWord(praisedWords)
var verb = something.split(' ')[0]
var noun = something.split(' ')[1]
var result = ''
var intro = randomWord(['这家的', '这家店的', '这个', '这件', '这杯'])
var also = hasAlso ? '也' : ''
if (praiseWord.indexOf('dosth') != -1) {
// eg. 好dosth到爆
praiseWord = praiseWord.replace('dosth', verb)
result = intro + noun + also + praiseWord
} else {
// eg. 绝绝子
result = intro + noun + also + praiseWord
}
return result
}
/* Example usages of 'randomButNotContain' are shown below:
randomButNotContain(words, already);
praiseSth(randomButNotContain(matierail.another, something), matierail.attribute, true) + randomRepeat(randomWord(matierail.symbols), 3);
*/
function randomButNotContain(words, already) {
var random = randomWord(words)
// Inspired by: https://www.cnblogs.com/mengff/p/7350005.html
var set = new Set(already.replace(' ', '').split(''))
var intersect = new Set(
random
.replace(' ', '')
.split('')
.filter((x) => set.has(x))
)
if (Array.from(intersect).length == 0) {
return random
} else {
return randomButNotContain(words, already)
}
}
export function generate(something) {
var matierail = parseMatieraials(matierailsJSON)
// 开场白
var divider = randomWord(matierail.dividers) // 分隔符
var fashionWords = randomWords(matierail.fashion, matierail.fashion.length) // 不重复的词组
var first = generateBeginning(matierail, divider)
var second = fashionWords[0] + divider
var third = generateDoSth(matierail, something, divider)
var forth = fashionWords[1] + divider
var fifth = randomRepeat(randomWord(matierail.auxiliaryWords), 3) + divider
var sixth =
praiseSth(something, matierail.attribute) +
randomRepeat(randomWord(matierail.symbols), 3)
var seventh =
praiseSth(
randomButNotContain(matierail.another, something),
matierail.attribute,
true
) + randomRepeat(randomWord(matierail.symbols), 3)
var eighth = fashionWords[2] + divider
var ninth =
randomWord(matierail.collections, true, divider) + fashionWords[3] + divider
var tenth = randomRepeat(randomWord(matierail.auxiliaryWords), 3) + divider
var last = randomWord(matierail.ending) + randomWord(matierail.emotions.emoji)
return (
first +
second +
third +
forth +
fifth +
sixth +
seventh +
eighth +
ninth +
tenth +
last
)
}
|
b3de2aad34e90f150704f50246a36c29074c99b6 | 2,066 | ts | TypeScript | app/src/app/home/models/metric.model.ts | trytouca/trytouca | eae38a96407d1ecac543c5a5fb05cbbe632ddfca | [
"Apache-2.0"
] | 6 | 2022-03-19T02:57:11.000Z | 2022-03-31T16:34:34.000Z | app/src/app/home/models/metric.model.ts | trytouca/trytouca | eae38a96407d1ecac543c5a5fb05cbbe632ddfca | [
"Apache-2.0"
] | null | null | null | app/src/app/home/models/metric.model.ts | trytouca/trytouca | eae38a96407d1ecac543c5a5fb05cbbe632ddfca | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 Touca, Inc. Subject to Apache-2.0 License.
export enum MetricChangeType {
Missing = 1,
Slower,
Same,
Faster,
Fresh
}
export class Metric {
constructor(
readonly name: string,
readonly src: number | null,
readonly dst: number | null
) {}
public changeType(): MetricChangeType {
// define threshold (in milliseconds) for the amount of time
// that is considered prone to noise and measurement error
const isSmall = (t: number) => t < 50;
// if metric has no base value, it must be newly submitted
if (this.dst === null) {
return MetricChangeType.Fresh;
}
// if metric has no head value, it must be missing
if (this.src === null) {
return MetricChangeType.Missing;
}
// if measured time is too small for both head and base versions,
// it is prone to noise and measurement error so report as not changed
if (isSmall(this.dst) && isSmall(this.src)) {
return MetricChangeType.Same;
}
// if measured time has not changed noticeably, report as not changed
if (isSmall(this.absoluteDifference())) {
return MetricChangeType.Same;
}
return this.src < this.dst
? MetricChangeType.Faster
: MetricChangeType.Slower;
}
public changeDescription(): string {
const score = this.score();
if (score === 0) {
return 'same';
}
const abs = Math.abs(score);
if (abs < 2) {
return `${Math.floor(abs * 100) / 1}%`;
}
return `${Math.floor(abs)}x`;
}
public duration(): number {
return this.src === null ? this.dst : this.src;
}
public absoluteDifference(): number {
return Math.abs(this.src - this.dst);
}
public score(): number {
const sign = this.src < this.dst ? -1 : +1;
switch (this.changeType()) {
case MetricChangeType.Missing:
return -1;
case MetricChangeType.Fresh:
return 1;
default:
if (this.dst === 0) {
return 0;
}
return (this.absoluteDifference() * sign) / this.dst;
}
}
}
| 25.825 | 74 | 0.613746 | 63 | 7 | 0 | 4 | 4 | 0 | 4 | 0 | 8 | 1 | 0 | 5.714286 | 554 | 0.019856 | 0.00722 | 0 | 0.001805 | 0 | 0 | 0.533333 | 0.243328 | // Copyright 2021 Touca, Inc. Subject to Apache-2.0 License.
export enum MetricChangeType {
Missing = 1,
Slower,
Same,
Faster,
Fresh
}
export class Metric {
constructor(
readonly name,
readonly src,
readonly dst
) {}
public changeType() {
// define threshold (in milliseconds) for the amount of time
// that is considered prone to noise and measurement error
/* Example usages of 'isSmall' are shown below:
isSmall(this.dst) && isSmall(this.src);
isSmall(this.absoluteDifference());
*/
const isSmall = (t) => t < 50;
// if metric has no base value, it must be newly submitted
if (this.dst === null) {
return MetricChangeType.Fresh;
}
// if metric has no head value, it must be missing
if (this.src === null) {
return MetricChangeType.Missing;
}
// if measured time is too small for both head and base versions,
// it is prone to noise and measurement error so report as not changed
if (isSmall(this.dst) && isSmall(this.src)) {
return MetricChangeType.Same;
}
// if measured time has not changed noticeably, report as not changed
if (isSmall(this.absoluteDifference())) {
return MetricChangeType.Same;
}
return this.src < this.dst
? MetricChangeType.Faster
: MetricChangeType.Slower;
}
public changeDescription() {
const score = this.score();
if (score === 0) {
return 'same';
}
const abs = Math.abs(score);
if (abs < 2) {
return `${Math.floor(abs * 100) / 1}%`;
}
return `${Math.floor(abs)}x`;
}
public duration() {
return this.src === null ? this.dst : this.src;
}
public absoluteDifference() {
return Math.abs(this.src - this.dst);
}
public score() {
const sign = this.src < this.dst ? -1 : +1;
switch (this.changeType()) {
case MetricChangeType.Missing:
return -1;
case MetricChangeType.Fresh:
return 1;
default:
if (this.dst === 0) {
return 0;
}
return (this.absoluteDifference() * sign) / this.dst;
}
}
}
|
424b3d2094e457d2a7532c6598ed0631fdcc56e3 | 2,115 | ts | TypeScript | docs/scripts/restructureUtils.ts | saeedhemmati/material-ui | 8e4c482d99aa08293d92116a3ba9995f09afbf64 | [
"MIT"
] | 1 | 2022-01-20T10:48:45.000Z | 2022-01-20T10:48:45.000Z | docs/scripts/restructureUtils.ts | saeedhemmati/material-ui | 8e4c482d99aa08293d92116a3ba9995f09afbf64 | [
"MIT"
] | 2 | 2022-02-17T23:55:43.000Z | 2022-03-02T13:09:43.000Z | docs/scripts/restructureUtils.ts | saeedhemmati/material-ui | 8e4c482d99aa08293d92116a3ba9995f09afbf64 | [
"MIT"
] | 1 | 2022-01-30T08:22:19.000Z | 2022-01-30T08:22:19.000Z | export const productPathnames = {
material: ['/getting-started', '/components', '/customization', '/guides', '/discover-more'],
system: ['/system'],
styles: ['/styles'],
} as const;
export const markdown = {
removeDemoRelativePath: (content: string) =>
content.replace(/"pages\/[/\-a-zA-Z]*\/([a-zA-Z]*\.js)"/gm, `"$1"`),
addMaterialPrefixToLinks: (content: string) => {
productPathnames.material.forEach((path) => {
content = content.replace(
new RegExp(`\\(${path}`, 'g'),
`(/material${path.replace('/components/', '/react-')}`,
);
});
return content;
},
addProductFrontmatter: (content: string, product: string) =>
content.replace('---', `---\nproduct: ${product}`),
};
export const getNewDataLocation = (
filePath: string,
product: string,
): { directory: string; path: string } | null => {
const match = filePath.match(/^(.*)\/[^/]+\.(ts|js|tsx|md|json|tsx\.preview)$/);
if (!match) {
return null;
}
return {
directory: match[1].replace('src/pages', product === 'material' ? `data/${product}` : 'data'),
path: filePath.replace('src/pages', product === 'material' ? `data/${product}` : 'data'),
};
};
const nonComponents = ['about-the-lab'];
export const getNewPageLocation = (
filePath: string,
): { directory: string; path: string } | null => {
const match = filePath.match(/^(.*)\/[^/]+\.(ts|js|tsx|md|json|tsx\.preview)$/);
if (!match) {
return null;
}
if (filePath.includes('components')) {
if (nonComponents.some((path) => filePath.includes(path))) {
return {
directory: match[1].replace('docs/pages/components', 'docs/pages/material'),
path: filePath.replace('docs/pages/components/', 'docs/pages/material/'),
};
}
return {
directory: match[1].replace('docs/pages/components', 'docs/pages/material'),
path: filePath.replace('docs/pages/components/', 'docs/pages/material/react-'),
};
}
return {
directory: match[1].replace('docs/pages', 'docs/pages/material'),
path: filePath.replace('docs/pages', 'docs/pages/material'),
};
};
| 33.571429 | 98 | 0.607565 | 58 | 7 | 0 | 9 | 7 | 0 | 0 | 0 | 11 | 0 | 1 | 6 | 600 | 0.026667 | 0.011667 | 0 | 0 | 0.001667 | 0 | 0.478261 | 0.269687 | export const productPathnames = {
material: ['/getting-started', '/components', '/customization', '/guides', '/discover-more'],
system: ['/system'],
styles: ['/styles'],
} as const;
export const markdown = {
removeDemoRelativePath: (content) =>
content.replace(/"pages\/[/\-a-zA-Z]*\/([a-zA-Z]*\.js)"/gm, `"$1"`),
addMaterialPrefixToLinks: (content) => {
productPathnames.material.forEach((path) => {
content = content.replace(
new RegExp(`\\(${path}`, 'g'),
`(/material${path.replace('/components/', '/react-')}`,
);
});
return content;
},
addProductFrontmatter: (content, product) =>
content.replace('---', `---\nproduct: ${product}`),
};
export const getNewDataLocation = (
filePath,
product,
) => {
const match = filePath.match(/^(.*)\/[^/]+\.(ts|js|tsx|md|json|tsx\.preview)$/);
if (!match) {
return null;
}
return {
directory: match[1].replace('src/pages', product === 'material' ? `data/${product}` : 'data'),
path: filePath.replace('src/pages', product === 'material' ? `data/${product}` : 'data'),
};
};
const nonComponents = ['about-the-lab'];
export const getNewPageLocation = (
filePath,
) => {
const match = filePath.match(/^(.*)\/[^/]+\.(ts|js|tsx|md|json|tsx\.preview)$/);
if (!match) {
return null;
}
if (filePath.includes('components')) {
if (nonComponents.some((path) => filePath.includes(path))) {
return {
directory: match[1].replace('docs/pages/components', 'docs/pages/material'),
path: filePath.replace('docs/pages/components/', 'docs/pages/material/'),
};
}
return {
directory: match[1].replace('docs/pages/components', 'docs/pages/material'),
path: filePath.replace('docs/pages/components/', 'docs/pages/material/react-'),
};
}
return {
directory: match[1].replace('docs/pages', 'docs/pages/material'),
path: filePath.replace('docs/pages', 'docs/pages/material'),
};
};
|
42babdf92b9adfc667a66cac6a565ae365c6d6e8 | 1,661 | ts | TypeScript | web/src/shared/store/reducers/taskReducer.ts | jordanos/todo-api | 31e10e45984f937470ca51591f1b779cb61265c8 | [
"MIT"
] | null | null | null | web/src/shared/store/reducers/taskReducer.ts | jordanos/todo-api | 31e10e45984f937470ca51591f1b779cb61265c8 | [
"MIT"
] | 6 | 2022-03-26T07:07:44.000Z | 2022-03-31T17:23:54.000Z | web/src/shared/store/reducers/taskReducer.ts | jordanos/todo-server-and-client | 31e10e45984f937470ca51591f1b779cb61265c8 | [
"MIT"
] | null | null | null | /* eslint-disable @typescript-eslint/default-param-last */
export type Task = {
id: string;
title: string;
description: string;
date: Date;
status: 'todo' | 'progress' | 'done';
assignedTo: string;
};
interface TaskState {
tasks: Task[];
editableTask: Task;
}
const initialState: TaskState = {
tasks: [],
editableTask: {
id: '',
title: '',
description: '',
date: new Date(),
status: 'todo',
assignedTo: '',
},
};
function taskReducer(
state = initialState,
action: { type: string; payload: any }
) {
switch (action.type) {
case 'ADD_TASK':
return { ...state, tasks: [...state.tasks, action.payload] };
case 'ADD_MANY_TASKS':
return { ...state, tasks: action.payload };
case 'PRE_EDIT':
return {
...state,
editableTask: { ...state.editableTask, ...action.payload },
};
case 'EDIT_TASK':
return {
...state,
tasks: state.tasks.map((task) => {
if (task.id !== action.payload.id) return task;
return { ...task, ...action.payload };
}),
};
case 'MOVE_TASK':
return {
...state,
tasks: state.tasks.map((task) => {
if (task.id !== action.payload.id) return task;
return { ...task, status: action.payload.status };
}),
};
case 'DELETE_TASK':
return {
...state,
tasks: state.tasks.filter((task) => {
return task.id !== action.payload.id;
}),
};
case 'DELETE_ALL_TASK':
return { ...state, tasks: initialState.tasks };
default:
return state;
}
}
export default taskReducer;
| 22.753425 | 67 | 0.544852 | 67 | 4 | 0 | 5 | 1 | 8 | 0 | 1 | 5 | 2 | 0 | 10.75 | 447 | 0.020134 | 0.002237 | 0.017897 | 0.004474 | 0 | 0.055556 | 0.277778 | 0.230448 | /* eslint-disable @typescript-eslint/default-param-last */
export type Task = {
id;
title;
description;
date;
status;
assignedTo;
};
interface TaskState {
tasks;
editableTask;
}
const initialState = {
tasks: [],
editableTask: {
id: '',
title: '',
description: '',
date: new Date(),
status: 'todo',
assignedTo: '',
},
};
/* Example usages of 'taskReducer' are shown below:
;
*/
function taskReducer(
state = initialState,
action
) {
switch (action.type) {
case 'ADD_TASK':
return { ...state, tasks: [...state.tasks, action.payload] };
case 'ADD_MANY_TASKS':
return { ...state, tasks: action.payload };
case 'PRE_EDIT':
return {
...state,
editableTask: { ...state.editableTask, ...action.payload },
};
case 'EDIT_TASK':
return {
...state,
tasks: state.tasks.map((task) => {
if (task.id !== action.payload.id) return task;
return { ...task, ...action.payload };
}),
};
case 'MOVE_TASK':
return {
...state,
tasks: state.tasks.map((task) => {
if (task.id !== action.payload.id) return task;
return { ...task, status: action.payload.status };
}),
};
case 'DELETE_TASK':
return {
...state,
tasks: state.tasks.filter((task) => {
return task.id !== action.payload.id;
}),
};
case 'DELETE_ALL_TASK':
return { ...state, tasks: initialState.tasks };
default:
return state;
}
}
export default taskReducer;
|
42de6b2e407d74c7adad1279632ac37ac5ea0699 | 1,741 | ts | TypeScript | design-hashmap/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | 1 | 2022-03-30T11:10:14.000Z | 2022-03-30T11:10:14.000Z | design-hashmap/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | null | null | null | design-hashmap/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | null | null | null | interface MyHashMap {
contains(key: number): boolean;
put(key: number, value: number): void;
get(key: number): number;
remove(key: number): void;
}
function MyHashMap(): MyHashMap {
//由于我们使用整数除法作为哈希函数,为了尽可能避免冲突,应当将 \textit{base}base 取为一个质数。
const BASE = 1009;
type Value = Array<[number, number]>;
const storage: Record<number, Value> = Object.create(null);
function getsub(key: number): Value {
const hash = key % BASE;
const sub = storage[hash];
if (sub) {
return sub;
} else {
const res: Value = [];
storage[hash] = res;
return res;
}
}
function put(key: number, value: number): void {
const sub = getsub(key);
const pair = sub.find((v) => v[0] === key);
if (pair) {
pair[1] = value;
return;
} else {
sub.push([key, value]);
}
// Reflect.set(sub, key, true)
}
function remove(key: number): void {
const sub = getsub(key);
const index = sub.findIndex((v) => v[0] === key);
if (index >= 0) {
sub.splice(index, 1);
}
// Reflect.set(sub, key, false)
}
function contains(key: number): boolean {
const sub = getsub(key);
return sub.findIndex((v) => v[0] === key) >= 0;
// return !!Reflect.get(sub, key,)
}
function get(key: number): number {
// if(!contains(key)){return -1}
const sub = getsub(key);
const pair = sub.find((v) => v[0] === key);
if (pair) {
return pair[1];
}
return -1;
}
return { put, get, remove, contains };
}
export default MyHashMap;
| 27.203125 | 63 | 0.508329 | 53 | 10 | 4 | 15 | 12 | 0 | 1 | 0 | 22 | 2 | 0 | 7.8 | 506 | 0.049407 | 0.023715 | 0 | 0.003953 | 0 | 0 | 0.536585 | 0.369119 | interface MyHashMap {
contains(key);
put(key, value);
get(key);
remove(key);
}
/* Example usages of 'MyHashMap' are shown below:
;
*/
function MyHashMap() {
//由于我们使用整数除法作为哈希函数,为了尽可能避免冲突,应当将 \textit{base}base 取为一个质数。
const BASE = 1009;
type Value = Array<[number, number]>;
const storage = Object.create(null);
/* Example usages of 'getsub' are shown below:
getsub(key);
*/
function getsub(key) {
const hash = key % BASE;
const sub = storage[hash];
if (sub) {
return sub;
} else {
const res = [];
storage[hash] = res;
return res;
}
}
/* Example usages of 'put' are shown below:
;
*/
function put(key, value) {
const sub = getsub(key);
const pair = sub.find((v) => v[0] === key);
if (pair) {
pair[1] = value;
return;
} else {
sub.push([key, value]);
}
// Reflect.set(sub, key, true)
}
/* Example usages of 'remove' are shown below:
;
*/
function remove(key) {
const sub = getsub(key);
const index = sub.findIndex((v) => v[0] === key);
if (index >= 0) {
sub.splice(index, 1);
}
// Reflect.set(sub, key, false)
}
/* Example usages of 'contains' are shown below:
;
*/
function contains(key) {
const sub = getsub(key);
return sub.findIndex((v) => v[0] === key) >= 0;
// return !!Reflect.get(sub, key,)
}
/* Example usages of 'get' are shown below:
;
*/
function get(key) {
// if(!contains(key)){return -1}
const sub = getsub(key);
const pair = sub.find((v) => v[0] === key);
if (pair) {
return pair[1];
}
return -1;
}
return { put, get, remove, contains };
}
export default MyHashMap;
|
42fef2d8a94057730d79e77422443b63fe649e9b | 1,343 | ts | TypeScript | src/utils/image-naming.ts | kubevious/logic-processor | f3b502fdd851fc955ddb00b39da589bbf05566e3 | [
"Apache-2.0"
] | null | null | null | src/utils/image-naming.ts | kubevious/logic-processor | f3b502fdd851fc955ddb00b39da589bbf05566e3 | [
"Apache-2.0"
] | null | null | null | src/utils/image-naming.ts | kubevious/logic-processor | f3b502fdd851fc955ddb00b39da589bbf05566e3 | [
"Apache-2.0"
] | 1 | 2022-01-16T20:19:54.000Z | 2022-01-16T20:19:54.000Z |
export function parseImageString(fullImage: string) : ImageInfo
{
const imageTagInfo = splitImageTag(fullImage);
const repoInfo = splitRepo(imageTagInfo.imagePath);
return {
fullImage: fullImage,
imagePath: imageTagInfo.imagePath,
repository: repoInfo.repo,
name: repoInfo.path,
tag: imageTagInfo.tag
}
}
export function splitRepo(imagePath: string) : ImageRepoInfo
{
const re = /^([^\/]+\.[^\/]+)\/(\S+)$/i;
const matches = imagePath.match(re);
if (matches) {
return {
repo: matches[1],
path: matches[2]
}
}
return {
repo: 'dockerhub',
path: imagePath
}
}
export function splitImageTag(fullImage: string) : ImageTagParseInfo
{
const re = /^(\S+):([^\/]+)$/i;
const matches = fullImage.match(re);
if (matches) {
return {
imagePath: matches[1],
tag: matches[2]
}
}
return {
imagePath: fullImage,
tag: 'latest'
}
}
export interface ImageRepoInfo
{
repo: string;
path: string;
}
export interface ImageTagParseInfo
{
imagePath: string;
tag: string;
}
export interface ImageInfo
{
fullImage: string;
imagePath: string;
repository: string;
name: string;
tag: string;
} | 18.148649 | 68 | 0.573343 | 60 | 3 | 0 | 3 | 6 | 9 | 2 | 0 | 12 | 3 | 0 | 11 | 354 | 0.016949 | 0.016949 | 0.025424 | 0.008475 | 0 | 0 | 0.571429 | 0.278548 |
export function parseImageString(fullImage)
{
const imageTagInfo = splitImageTag(fullImage);
const repoInfo = splitRepo(imageTagInfo.imagePath);
return {
fullImage: fullImage,
imagePath: imageTagInfo.imagePath,
repository: repoInfo.repo,
name: repoInfo.path,
tag: imageTagInfo.tag
}
}
export /* Example usages of 'splitRepo' are shown below:
splitRepo(imageTagInfo.imagePath);
*/
function splitRepo(imagePath)
{
const re = /^([^\/]+\.[^\/]+)\/(\S+)$/i;
const matches = imagePath.match(re);
if (matches) {
return {
repo: matches[1],
path: matches[2]
}
}
return {
repo: 'dockerhub',
path: imagePath
}
}
export /* Example usages of 'splitImageTag' are shown below:
splitImageTag(fullImage);
*/
function splitImageTag(fullImage)
{
const re = /^(\S+):([^\/]+)$/i;
const matches = fullImage.match(re);
if (matches) {
return {
imagePath: matches[1],
tag: matches[2]
}
}
return {
imagePath: fullImage,
tag: 'latest'
}
}
export interface ImageRepoInfo
{
repo;
path;
}
export interface ImageTagParseInfo
{
imagePath;
tag;
}
export interface ImageInfo
{
fullImage;
imagePath;
repository;
name;
tag;
} |
a8285a862a6357e80925055242d2cdef520074fe | 2,464 | ts | TypeScript | problemset/largest-triangle-area/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/largest-triangle-area/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/largest-triangle-area/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 枚举
* @desc 时间复杂度 O(N³) 空间复杂度 O(1)
* @param points
* @returns
*/
export function largestTriangleArea(points: number[][]): number {
const triangleArea = ([x1, y1]: number[], [x2, y2]: number[], [x3, y3]: number[]) =>
0.5 * Math.abs(x1 * y2 + x2 * y3 + x3 * y1 - x1 * y3 - x2 * y1 - x3 * y2)
const len = points.length
let res = 0
for (let i = 0; i < len; i++) {
for (let j = i + 1; j < len; j++) {
for (let k = j + 1; k < len; k++)
res = Math.max(res, triangleArea(points[i], points[j], points[k]))
}
}
return res
}
/**
* 凸包
* @desc 时间复杂度 O(N²) 空间复杂度 O(N)
* @param points
* @returns
*/
export function largestTriangleArea2(points: number[][]): number {
const triangleArea = ([x1, y1]: number[], [x2, y2]: number[], [x3, y3]: number[]) =>
0.5 * Math.abs(x1 * y2 + x2 * y3 + x3 * y1 - x1 * y3 - x2 * y1 - x3 * y2)
const convexHull = getConvexHull(points)
const len = convexHull.length
let res = 0
for (let i = 0; i < len; i++) {
for (let j = i + 1, k = i + 2; j + 1 < len; j++) {
while (k + 1 < len) {
const curArea = triangleArea(convexHull[i], convexHull[j], convexHull[k])
const nextArea = triangleArea(convexHull[i], convexHull[j], convexHull[k + 1])
if (curArea >= nextArea) break
k++
}
res = Math.max(res, triangleArea(convexHull[i], convexHull[j], convexHull[k]))
}
}
return res
function getConvexHull(points: number[][]): number[][] {
const cross = ([x1, y1]: number[], [x2, y2]: number[], [x3, y3]: number[]) =>
(x2 - x1) * (y3 - y2) - (y2 - y1) * (x3 - x2)
const n = points.length
if (n < 4) return points
/* 按照 x 大小进行排序,如果 x 相同,则按照 y 的大小进行排序 */
points.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0])
const hull: number[][] = []
/* 求出凸包的下半部分 */
for (let i = 0; i < n; i++) {
while (hull.length > 1 && cross(hull[hull.length - 2], hull[hull.length - 1], points[i]) <= 0)
hull.pop()
hull.push(points[i])
}
let m = hull.length
/* 求出凸包的上半部分 */
for (let i = n - 2; i >= 0; i--) {
while (hull.length > m && cross(hull[hull.length - 2], hull[hull.length - 1], points[i]) <= 0)
hull.pop()
hull.push(points[i])
}
/* hull[0] 同时参与凸包的上半部分检测,因此需去掉重复的 hull[0] */
hull.pop()
m = hull.length
const hullArr: number[][] = []
for (let i = 0; i < m; i++)
hullArr[i] = hull[i]
return hullArr
}
}
| 29.333333 | 100 | 0.523539 | 57 | 7 | 0 | 14 | 23 | 0 | 3 | 0 | 17 | 0 | 0 | 11.428571 | 995 | 0.021106 | 0.023116 | 0 | 0 | 0 | 0 | 0.386364 | 0.295247 | /**
* 枚举
* @desc 时间复杂度 O(N³) 空间复杂度 O(1)
* @param points
* @returns
*/
export function largestTriangleArea(points) {
/* Example usages of 'triangleArea' are shown below:
res = Math.max(res, triangleArea(points[i], points[j], points[k]));
triangleArea(convexHull[i], convexHull[j], convexHull[k]);
triangleArea(convexHull[i], convexHull[j], convexHull[k + 1]);
res = Math.max(res, triangleArea(convexHull[i], convexHull[j], convexHull[k]));
*/
/* Example usages of 'triangleArea' are shown below:
res = Math.max(res, triangleArea(points[i], points[j], points[k]));
triangleArea(convexHull[i], convexHull[j], convexHull[k]);
triangleArea(convexHull[i], convexHull[j], convexHull[k + 1]);
res = Math.max(res, triangleArea(convexHull[i], convexHull[j], convexHull[k]));
*/
const triangleArea = ([x1, y1], [x2, y2], [x3, y3]) =>
0.5 * Math.abs(x1 * y2 + x2 * y3 + x3 * y1 - x1 * y3 - x2 * y1 - x3 * y2)
const len = points.length
let res = 0
for (let i = 0; i < len; i++) {
for (let j = i + 1; j < len; j++) {
for (let k = j + 1; k < len; k++)
res = Math.max(res, triangleArea(points[i], points[j], points[k]))
}
}
return res
}
/**
* 凸包
* @desc 时间复杂度 O(N²) 空间复杂度 O(N)
* @param points
* @returns
*/
export function largestTriangleArea2(points) {
/* Example usages of 'triangleArea' are shown below:
res = Math.max(res, triangleArea(points[i], points[j], points[k]));
triangleArea(convexHull[i], convexHull[j], convexHull[k]);
triangleArea(convexHull[i], convexHull[j], convexHull[k + 1]);
res = Math.max(res, triangleArea(convexHull[i], convexHull[j], convexHull[k]));
*/
/* Example usages of 'triangleArea' are shown below:
res = Math.max(res, triangleArea(points[i], points[j], points[k]));
triangleArea(convexHull[i], convexHull[j], convexHull[k]);
triangleArea(convexHull[i], convexHull[j], convexHull[k + 1]);
res = Math.max(res, triangleArea(convexHull[i], convexHull[j], convexHull[k]));
*/
const triangleArea = ([x1, y1], [x2, y2], [x3, y3]) =>
0.5 * Math.abs(x1 * y2 + x2 * y3 + x3 * y1 - x1 * y3 - x2 * y1 - x3 * y2)
const convexHull = getConvexHull(points)
const len = convexHull.length
let res = 0
for (let i = 0; i < len; i++) {
for (let j = i + 1, k = i + 2; j + 1 < len; j++) {
while (k + 1 < len) {
const curArea = triangleArea(convexHull[i], convexHull[j], convexHull[k])
const nextArea = triangleArea(convexHull[i], convexHull[j], convexHull[k + 1])
if (curArea >= nextArea) break
k++
}
res = Math.max(res, triangleArea(convexHull[i], convexHull[j], convexHull[k]))
}
}
return res
/* Example usages of 'getConvexHull' are shown below:
getConvexHull(points);
*/
function getConvexHull(points) {
/* Example usages of 'cross' are shown below:
hull.length > 1 && cross(hull[hull.length - 2], hull[hull.length - 1], points[i]) <= 0;
hull.length > m && cross(hull[hull.length - 2], hull[hull.length - 1], points[i]) <= 0;
*/
const cross = ([x1, y1], [x2, y2], [x3, y3]) =>
(x2 - x1) * (y3 - y2) - (y2 - y1) * (x3 - x2)
const n = points.length
if (n < 4) return points
/* 按照 x 大小进行排序,如果 x 相同,则按照 y 的大小进行排序 */
points.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0])
const hull = []
/* 求出凸包的下半部分 */
for (let i = 0; i < n; i++) {
while (hull.length > 1 && cross(hull[hull.length - 2], hull[hull.length - 1], points[i]) <= 0)
hull.pop()
hull.push(points[i])
}
let m = hull.length
/* 求出凸包的上半部分 */
for (let i = n - 2; i >= 0; i--) {
while (hull.length > m && cross(hull[hull.length - 2], hull[hull.length - 1], points[i]) <= 0)
hull.pop()
hull.push(points[i])
}
/* hull[0] 同时参与凸包的上半部分检测,因此需去掉重复的 hull[0] */
hull.pop()
m = hull.length
const hullArr = []
for (let i = 0; i < m; i++)
hullArr[i] = hull[i]
return hullArr
}
}
|
a82baefa18a0fd725d357639aed4d06750499589 | 3,228 | ts | TypeScript | packages/react/src/utils/serialize.ts | codingwithmanny/wagmi | 8a5f6c209049c35f16f9c6a86cd4ea71106e84a6 | [
"MIT"
] | 1,250 | 2022-01-02T20:41:50.000Z | 2022-03-31T23:50:51.000Z | packages/react/src/utils/serialize.ts | codingwithmanny/wagmi | 8a5f6c209049c35f16f9c6a86cd4ea71106e84a6 | [
"MIT"
] | 157 | 2022-01-02T21:06:33.000Z | 2022-03-31T19:01:19.000Z | packages/react/src/utils/serialize.ts | codingwithmanny/wagmi | 8a5f6c209049c35f16f9c6a86cd4ea71106e84a6 | [
"MIT"
] | 105 | 2022-01-04T19:00:08.000Z | 2022-03-29T06:26:33.000Z | /**
* @function getReferenceKey
*
* @description
* get the reference key for the circular value
*
* @param keys the keys to build the reference key from
* @param cutoff the maximum number of keys to include
* @returns the reference key
*/
function getReferenceKey(keys: string[], cutoff: number) {
return keys.slice(0, cutoff).join('.') || '.'
}
/**
* @function getCutoff
*
* @description
* faster `Array.prototype.indexOf` implementation build for slicing / splicing
*
* @param array the array to match the value in
* @param value the value to match
* @returns the matching index, or -1
*/
function getCutoff(array: any[], value: any) {
const { length } = array
for (let index = 0; index < length; ++index) {
if (array[index] === value) {
return index + 1
}
}
return 0
}
type StandardReplacer = (key: string, value: any) => any
type CircularReplacer = (key: string, value: any, referenceKey: string) => any
/**
* @function createReplacer
*
* @description
* create a replacer method that handles circular values
*
* @param [replacer] a custom replacer to use for non-circular values
* @param [circularReplacer] a custom replacer to use for circular methods
* @returns the value to stringify
*/
function createReplacer(
replacer?: StandardReplacer | null | undefined,
circularReplacer?: CircularReplacer | null | undefined,
): StandardReplacer {
const hasReplacer = typeof replacer === 'function'
const hasCircularReplacer = typeof circularReplacer === 'function'
const cache: any[] = []
const keys: string[] = []
return function replace(this: any, key: string, value: any) {
if (typeof value === 'object') {
if (cache.length) {
const thisCutoff = getCutoff(cache, this)
if (thisCutoff === 0) {
cache[cache.length] = this
} else {
cache.splice(thisCutoff)
keys.splice(thisCutoff)
}
keys[keys.length] = key
const valueCutoff = getCutoff(cache, value)
if (valueCutoff !== 0) {
return hasCircularReplacer
? circularReplacer.call(
this,
key,
value,
getReferenceKey(keys, valueCutoff),
)
: `[ref=${getReferenceKey(keys, valueCutoff)}]`
}
} else {
cache[0] = value
keys[0] = key
}
}
return hasReplacer ? replacer.call(this, key, value) : value
}
}
/**
* @function stringify
*
* @description
* strinigifer that handles circular values
* Forked from https://github.com/planttheidea/fast-stringify
*
* @param value to stringify
* @param [replacer] a custom replacer function for handling standard values
* @param [indent] the number of spaces to indent the output by
* @param [circularReplacer] a custom replacer function for handling circular values
* @returns the stringified output
*/
export function serialize(
value: any,
replacer?: StandardReplacer | null | undefined,
indent?: number | null | undefined,
circularReplacer?: CircularReplacer | null | undefined,
) {
return JSON.stringify(
value,
createReplacer(replacer, circularReplacer),
indent ?? undefined,
)
}
| 26.677686 | 84 | 0.64746 | 64 | 5 | 0 | 13 | 8 | 0 | 3 | 10 | 8 | 2 | 3 | 14.6 | 808 | 0.022277 | 0.009901 | 0 | 0.002475 | 0.003713 | 0.384615 | 0.307692 | 0.252238 | /**
* @function getReferenceKey
*
* @description
* get the reference key for the circular value
*
* @param keys the keys to build the reference key from
* @param cutoff the maximum number of keys to include
* @returns the reference key
*/
/* Example usages of 'getReferenceKey' are shown below:
hasCircularReplacer
? circularReplacer.call(this, key, value, getReferenceKey(keys, valueCutoff))
: `[ref=${getReferenceKey(keys, valueCutoff)}]`;
getReferenceKey(keys, valueCutoff);
*/
function getReferenceKey(keys, cutoff) {
return keys.slice(0, cutoff).join('.') || '.'
}
/**
* @function getCutoff
*
* @description
* faster `Array.prototype.indexOf` implementation build for slicing / splicing
*
* @param array the array to match the value in
* @param value the value to match
* @returns the matching index, or -1
*/
/* Example usages of 'getCutoff' are shown below:
getCutoff(cache, this);
getCutoff(cache, value);
*/
function getCutoff(array, value) {
const { length } = array
for (let index = 0; index < length; ++index) {
if (array[index] === value) {
return index + 1
}
}
return 0
}
type StandardReplacer = (key, value) => any
type CircularReplacer = (key, value, referenceKey) => any
/**
* @function createReplacer
*
* @description
* create a replacer method that handles circular values
*
* @param [replacer] a custom replacer to use for non-circular values
* @param [circularReplacer] a custom replacer to use for circular methods
* @returns the value to stringify
*/
/* Example usages of 'createReplacer' are shown below:
JSON.stringify(value, createReplacer(replacer, circularReplacer), indent ?? undefined);
*/
function createReplacer(
replacer?,
circularReplacer?,
) {
const hasReplacer = typeof replacer === 'function'
const hasCircularReplacer = typeof circularReplacer === 'function'
const cache = []
const keys = []
return function replace(this, key, value) {
if (typeof value === 'object') {
if (cache.length) {
const thisCutoff = getCutoff(cache, this)
if (thisCutoff === 0) {
cache[cache.length] = this
} else {
cache.splice(thisCutoff)
keys.splice(thisCutoff)
}
keys[keys.length] = key
const valueCutoff = getCutoff(cache, value)
if (valueCutoff !== 0) {
return hasCircularReplacer
? circularReplacer.call(
this,
key,
value,
getReferenceKey(keys, valueCutoff),
)
: `[ref=${getReferenceKey(keys, valueCutoff)}]`
}
} else {
cache[0] = value
keys[0] = key
}
}
return hasReplacer ? replacer.call(this, key, value) : value
}
}
/**
* @function stringify
*
* @description
* strinigifer that handles circular values
* Forked from https://github.com/planttheidea/fast-stringify
*
* @param value to stringify
* @param [replacer] a custom replacer function for handling standard values
* @param [indent] the number of spaces to indent the output by
* @param [circularReplacer] a custom replacer function for handling circular values
* @returns the stringified output
*/
export function serialize(
value,
replacer?,
indent?,
circularReplacer?,
) {
return JSON.stringify(
value,
createReplacer(replacer, circularReplacer),
indent ?? undefined,
)
}
|
a870166147846325968b684afd6a7c134ac418f5 | 1,174 | ts | TypeScript | src/mantine-styles/src/theme/utils/to-rgba/to-rgba.ts | gabrielcraveiro/mantine | 8516a5ca4f52ed6cdd2ec1765286935967a41e0b | [
"MIT"
] | 2 | 2022-01-07T20:32:55.000Z | 2022-01-31T01:37:47.000Z | src/mantine-styles/src/theme/utils/to-rgba/to-rgba.ts | gabrielcraveiro/mantine | 8516a5ca4f52ed6cdd2ec1765286935967a41e0b | [
"MIT"
] | null | null | null | src/mantine-styles/src/theme/utils/to-rgba/to-rgba.ts | gabrielcraveiro/mantine | 8516a5ca4f52ed6cdd2ec1765286935967a41e0b | [
"MIT"
] | null | null | null | /* eslint-disable no-bitwise */
interface RGBA {
r: number;
g: number;
b: number;
a: number;
}
function isHexColor(hex: string): boolean {
const HEX_REGEXP = /^#?([0-9A-F]{3}){1,2}$/i;
return HEX_REGEXP.test(hex);
}
function hexToRgba(color: string): RGBA {
let hexString = color.replace('#', '');
if (hexString.length === 3) {
const shorthandHex = hexString.split('');
hexString = [
shorthandHex[0],
shorthandHex[0],
shorthandHex[1],
shorthandHex[1],
shorthandHex[2],
shorthandHex[2],
].join('');
}
const parsed = parseInt(hexString, 16);
const r = (parsed >> 16) & 255;
const g = (parsed >> 8) & 255;
const b = parsed & 255;
return {
r,
g,
b,
a: 1,
};
}
function rgbStringToRgba(color: string): RGBA {
const [r, g, b, a] = color
.replace(/[^0-9,.]/g, '')
.split(',')
.map(Number);
return { r, g, b, a: a || 1 };
}
export function toRgba(color: string): RGBA {
if (isHexColor(color)) {
return hexToRgba(color);
}
if (color.startsWith('rgb')) {
return rgbStringToRgba(color);
}
return {
r: 0,
g: 0,
b: 0,
a: 1,
};
}
| 17.014493 | 47 | 0.551959 | 55 | 4 | 0 | 4 | 8 | 4 | 3 | 0 | 9 | 1 | 0 | 10.25 | 421 | 0.019002 | 0.019002 | 0.009501 | 0.002375 | 0 | 0 | 0.45 | 0.280628 | /* eslint-disable no-bitwise */
interface RGBA {
r;
g;
b;
a;
}
/* Example usages of 'isHexColor' are shown below:
isHexColor(color);
*/
function isHexColor(hex) {
const HEX_REGEXP = /^#?([0-9A-F]{3}){1,2}$/i;
return HEX_REGEXP.test(hex);
}
/* Example usages of 'hexToRgba' are shown below:
hexToRgba(color);
*/
function hexToRgba(color) {
let hexString = color.replace('#', '');
if (hexString.length === 3) {
const shorthandHex = hexString.split('');
hexString = [
shorthandHex[0],
shorthandHex[0],
shorthandHex[1],
shorthandHex[1],
shorthandHex[2],
shorthandHex[2],
].join('');
}
const parsed = parseInt(hexString, 16);
const r = (parsed >> 16) & 255;
const g = (parsed >> 8) & 255;
const b = parsed & 255;
return {
r,
g,
b,
a: 1,
};
}
/* Example usages of 'rgbStringToRgba' are shown below:
rgbStringToRgba(color);
*/
function rgbStringToRgba(color) {
const [r, g, b, a] = color
.replace(/[^0-9,.]/g, '')
.split(',')
.map(Number);
return { r, g, b, a: a || 1 };
}
export function toRgba(color) {
if (isHexColor(color)) {
return hexToRgba(color);
}
if (color.startsWith('rgb')) {
return rgbStringToRgba(color);
}
return {
r: 0,
g: 0,
b: 0,
a: 1,
};
}
|
a26a42831f8c3aaeb290ff62c384e6941be344cb | 2,056 | ts | TypeScript | src/utils/index.ts | zguiyang/quick-utils-js | 66dc5d1db02f061f98b2afec0de0086184c0a532 | [
"MIT"
] | null | null | null | src/utils/index.ts | zguiyang/quick-utils-js | 66dc5d1db02f061f98b2afec0de0086184c0a532 | [
"MIT"
] | 1 | 2022-01-12T09:20:01.000Z | 2022-01-12T09:20:01.000Z | src/utils/index.ts | zguiyang/quick-utils-js | 66dc5d1db02f061f98b2afec0de0086184c0a532 | [
"MIT"
] | 1 | 2022-01-12T06:31:21.000Z | 2022-01-12T06:31:21.000Z |
/**
*
* @desc Change the cash amount to uppercase
* @param {Number} money
* @return {String}
*/
export function digitUppercase ( money: number ): string {
let num = money;
// 向右移位
const shiftRight = ( number, digit ) => {
const digitNum = parseInt ( digit, 10 );
let value = number.toString ().split ( 'e' );
return Number ( `${value[ 0 ] }e${ value[ 1 ] ? Number ( value[ 1 ] ) + digitNum : digitNum}` );
};
// 向左移位
const shiftLeft = ( number, digit ) => {
const digitNum = parseInt ( digit, 10 );
let value = number.toString ().split ( 'e' );
return Number ( `${value[ 0 ] }e${ value[ 1 ] ? Number ( value[ 1 ] ) - digitNum : -digitNum}` );
};
let fraction = [ '角', '分' ];
let digit = [ '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' ];
let unit = [
[ '元', '万', '亿' ],
[ '', '拾', '佰', '仟' ],
];
let head = num < 0 ? '欠' : '';
num = Math.abs ( num );
let s = '';
for ( let i = 0; i < fraction.length; i ++ ) {
s += ( digit[ Math.floor ( shiftRight ( num, 1 + i ) ) % 10 ] + fraction[ i ] ).replace ( /零./,
'' );
}
s = s || '整';
num = Math.floor ( num );
for ( let i = 0; i < unit[ 0 ].length && num > 0; i ++ ) {
let p = '';
for ( let j = 0; j < unit[ 1 ].length && num > 0; j ++ ) {
p = digit[ num % 10 ] + unit[ 1 ][ j ] + p;
num = Math.floor ( shiftLeft ( num, 1 ) );
}
s = p.replace ( /(零.)*零$/, '' ).replace ( /^$/, '零' ) + unit[ 0 ][ i ] + s;
}
return (
head +
s.
replace ( /(零.)*零元/, '元' ).
replace ( /(零.)+/g, '零' ).
replace ( /^整$/, '零元整' )
);
}
/**
* @desc get file extension name xxx.txt => txt
* @param { string } filename file name
* @return { string | undefined }
* **/
export function getFileExtension ( filename:string ): string | undefined {
const reg1 = /[.]/.exec ( filename );
const reg2 = /[^.]+$/.exec ( filename );
if ( reg1 && reg2 && reg2.length ) {
return reg2[ 0 ].toLocaleLowerCase ();
}
return undefined;
} | 18.690909 | 101 | 0.47179 | 51 | 4 | 0 | 6 | 18 | 0 | 2 | 0 | 4 | 0 | 0 | 13.25 | 734 | 0.013624 | 0.024523 | 0 | 0 | 0 | 0 | 0.142857 | 0.282398 |
/**
*
* @desc Change the cash amount to uppercase
* @param {Number} money
* @return {String}
*/
export function digitUppercase ( money ) {
let num = money;
// 向右移位
/* Example usages of 'shiftRight' are shown below:
digit[Math.floor(shiftRight(num, 1 + i)) % 10] + fraction[i];
*/
const shiftRight = ( number, digit ) => {
const digitNum = parseInt ( digit, 10 );
let value = number.toString ().split ( 'e' );
return Number ( `${value[ 0 ] }e${ value[ 1 ] ? Number ( value[ 1 ] ) + digitNum : digitNum}` );
};
// 向左移位
/* Example usages of 'shiftLeft' are shown below:
num = Math.floor(shiftLeft(num, 1));
*/
const shiftLeft = ( number, digit ) => {
const digitNum = parseInt ( digit, 10 );
let value = number.toString ().split ( 'e' );
return Number ( `${value[ 0 ] }e${ value[ 1 ] ? Number ( value[ 1 ] ) - digitNum : -digitNum}` );
};
let fraction = [ '角', '分' ];
let digit = [ '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' ];
let unit = [
[ '元', '万', '亿' ],
[ '', '拾', '佰', '仟' ],
];
let head = num < 0 ? '欠' : '';
num = Math.abs ( num );
let s = '';
for ( let i = 0; i < fraction.length; i ++ ) {
s += ( digit[ Math.floor ( shiftRight ( num, 1 + i ) ) % 10 ] + fraction[ i ] ).replace ( /零./,
'' );
}
s = s || '整';
num = Math.floor ( num );
for ( let i = 0; i < unit[ 0 ].length && num > 0; i ++ ) {
let p = '';
for ( let j = 0; j < unit[ 1 ].length && num > 0; j ++ ) {
p = digit[ num % 10 ] + unit[ 1 ][ j ] + p;
num = Math.floor ( shiftLeft ( num, 1 ) );
}
s = p.replace ( /(零.)*零$/, '' ).replace ( /^$/, '零' ) + unit[ 0 ][ i ] + s;
}
return (
head +
s.
replace ( /(零.)*零元/, '元' ).
replace ( /(零.)+/g, '零' ).
replace ( /^整$/, '零元整' )
);
}
/**
* @desc get file extension name xxx.txt => txt
* @param { string } filename file name
* @return { string | undefined }
* **/
export function getFileExtension ( filename ) {
const reg1 = /[.]/.exec ( filename );
const reg2 = /[^.]+$/.exec ( filename );
if ( reg1 && reg2 && reg2.length ) {
return reg2[ 0 ].toLocaleLowerCase ();
}
return undefined;
} |
a2a2403d2587f28fb6f602be79d169360b30748d | 17,272 | ts | TypeScript | src/seagull.ts | fnando/seagull | 83f15076b9b9d7efdda844fcd681989942c40748 | [
"MIT"
] | 6 | 2022-01-10T06:54:42.000Z | 2022-03-01T02:07:54.000Z | src/seagull.ts | fnando/seagull | 83f15076b9b9d7efdda844fcd681989942c40748 | [
"MIT"
] | 1 | 2022-01-10T19:06:57.000Z | 2022-01-11T07:29:12.000Z | src/seagull.ts | fnando/seagull | 83f15076b9b9d7efdda844fcd681989942c40748 | [
"MIT"
] | null | null | null | type Scope = {
globalCaptures: Set<string>;
localCaptures: Set<string>[];
blocks: string[];
buffer: string;
};
type Location = { line: number; column: number };
type ExpressionParserResult = {
output: string;
globalCaptures: string[];
localCaptures: string[];
popBlock?: boolean;
};
type ExpressionParser = {
match: RegExp;
process(expression: string, scope: Scope): ExpressionParserResult;
};
type CompileToStringResult = {
/**
* The function body.
* @type {string}
*/
output: string;
/**
* The list of variables that must be provided to the template function.
* @type {string[]}
*/
captures: string[];
};
class UnmatchedBlockError extends Error {
public detail: {
/**
* The template's line number that generated the error.
* @type {number}
*/
line: number;
/**
* The template's column number that generated the error.
* @type {number}
*/
column: number;
/**
* The expected block.
* @type {string}
*/
expected: string;
/**
* The actual block that was found.
* @type {string}
*/
actual: string;
} = { line: 1, column: 1, expected: "", actual: "" };
}
class InvalidTemplateError extends Error {
public detail: {
template: string;
output: string;
captures: string[];
} = { template: "", output: "", captures: [] };
}
class UnknownExpressionError extends Error {
public detail: {
line: number;
column: number;
expression: string;
} = { expression: "", line: 1, column: 1 };
}
class GenericExpressionError extends Error {
public detail: {
line: number;
column: number;
expression: string;
} = { expression: "", line: 1, column: 1 };
}
export const encodeHelper = `
const _encode = (unsafe) =>
String(unsafe).replace(
/(?![0-9A-Za-z ])[\\u0000-\\u00FF]/g,
(c) => "&#" + c.charCodeAt(0).toString().padStart(4, "0") + ";"
);
`;
/**
* Decode HTML entities into their character equivalent.
* This is supposed to help with testing, not to bypass escaped values in
* templates.
*
* @param {string} input The encoded string.
* @return {string} The decoded string.
*/
export const decode = (input: string): string =>
input.replace(/(&#(\d+);)/g, (_entity, _match, code) =>
String.fromCharCode(parseInt(code, 10)),
);
/**
* Generate the tree for a template string.
*
* @param {string} template The template string.
* @return {string[]} The template parsed into a tree. Each expression will be
* isolated into its own array item.
*/
export const parse = (template: string): string[] => {
let result = /{(.*?)}/g.exec(template);
const tree = [];
let position: number;
while (result) {
position = result.index;
if (position !== 0) {
tree.push(template.substring(0, position));
template = template.slice(position);
}
tree.push(result[0]);
template = template.slice(result[0].length);
result = /{(.*?)}/g.exec(template);
}
if (template) {
tree.push(template);
}
return tree;
};
const buildHelperChain = (
input: string,
rawHelpers: string,
): { output: string; captures: string[] } => {
const helpers = rawHelpers.replace(/^ \| /, "").split(/ \| /);
const output = helpers.reduce(
(buffer, helper) => `${helper}(${buffer})`,
input,
);
return {
output,
captures: helpers,
};
};
const extractLocation = (scope: Scope): Location => {
const lines = scope.buffer.split(/\r?\n/);
const line = Math.max(1, lines.length);
const column = Math.max(1, (lines.pop() ?? "").length);
return { line, column };
};
const hasLocalCapture = (scope: Scope, capture: string): boolean =>
scope.localCaptures
.flatMap((captures) => Array.from(captures.values()))
.includes(capture);
const validateKnownExpressionParser = (
expression: string,
location: Location,
parser: ExpressionParser | undefined,
): ExpressionParser | never => {
if (parser) {
return parser;
}
const { line, column } = location;
const error = new UnknownExpressionError(
`Unknown expression: ${expression} (line: ${line}, column: ${column})`,
);
error.detail = { line, column, expression };
throw error;
};
const validateExpressionMatches = (
scope: Scope,
expression: string,
matches: RegExpMatchArray | null,
): RegExpMatchArray | never => {
if (matches) {
return matches;
}
const error = new GenericExpressionError(
`Cannot run expression parser without matches: ${expression}`,
);
let { line, column } = extractLocation(scope);
column -= expression.length;
error.detail = { line, column, expression };
throw error;
};
const validateClosingBlock = (
scope: Scope,
currentBlock: string,
): void | never => {
const expectedBlock = scope.blocks.pop() ?? "unknown";
if (expectedBlock === currentBlock) {
return;
}
let { line, column } = extractLocation(scope);
column -= currentBlock.length + 2;
const error = new UnmatchedBlockError(
`Expected {/${expectedBlock}}, got {/${currentBlock}} (line: ${line}, column: ${column})`,
);
error.detail = {
line,
column,
expected: expectedBlock,
actual: currentBlock,
};
throw error;
};
const variableExpressionParser = {
match: /^{([a-z0-9._]+)((?: *\| *[a-z0-9_]+)+)?}$/i,
process(expression: string, scope: Scope): ExpressionParserResult {
const matches = validateExpressionMatches(
scope,
expression,
expression.match(this.match),
);
const [, capture, piping] = matches;
let input = `${capture}`;
const globalCaptures = [];
if (piping) {
const chain = buildHelperChain(input, piping);
globalCaptures.push(...chain.captures);
input = chain.output;
}
input = `_encode(${input})`;
const [captureTarget] = capture.split(".");
const isLocalCapture = hasLocalCapture(scope, captureTarget);
if (!isLocalCapture) {
globalCaptures.push(captureTarget);
}
return {
output: ` + ${input}`,
globalCaptures,
localCaptures: [isLocalCapture ? captureTarget : ""].filter(Boolean),
};
},
};
const stringPipingExpressionParser = {
match: /^{((["']).*?\2)( *\| *[a-z0-9_.]+)+}$/i,
process(expression: string, scope: Scope): ExpressionParserResult {
const matches = validateExpressionMatches(
scope,
expression,
expression.match(this.match),
);
const [, capture, , piping] = matches;
let input = `${capture}`;
const globalCaptures = [];
if (piping) {
const chain = buildHelperChain(input, piping);
globalCaptures.push(...chain.captures);
input = chain.output;
}
input = `_encode(${input})`;
return {
output: ` + ${input}`,
globalCaptures,
localCaptures: [].filter(Boolean),
};
},
};
const ifExpressionParser = {
match: /^{if ([a-zA-z0-9._]+)((?: *\| *[a-zA-z0-9_]+)+)?}$/,
process(expression: string, scope: Scope): ExpressionParserResult {
const matches = validateExpressionMatches(
scope,
expression,
expression.match(this.match),
);
const [, capture, piping] = matches;
let input = `${capture}`;
const globalCaptures: string[] = [];
scope.blocks.push("if");
if (piping) {
const chain = buildHelperChain(input, piping);
input = chain.output;
globalCaptures.push(...chain.captures);
}
const [captureTarget] = capture.split(".");
const isLocalCapture = hasLocalCapture(scope, captureTarget);
if (!isLocalCapture) {
globalCaptures.push(captureTarget);
}
return {
output: ` + (${input} ? ( ""`,
globalCaptures,
localCaptures: [],
};
},
};
const ifClosingExpressionParser = {
match: /^{\/if}$/,
process(_expression: string, scope: Scope): ExpressionParserResult {
validateClosingBlock(scope, "if");
return {
output: `) : "")`,
globalCaptures: [],
localCaptures: [],
};
},
};
const whenExpressionParser = {
match:
/^{when ([a-zA-z0-9._]+)=([a-zA-z0-9._]+|'[^\t\r\n']+'|"[^\t\r\n']+")}$/,
process(expression: string, scope: Scope): ExpressionParserResult {
const matches = validateExpressionMatches(
scope,
expression,
expression.match(this.match),
);
const [, capture, value] = matches;
const globalCaptures: string[] = [];
scope.blocks.push("when");
const [captureTarget] = capture.split(".");
const isLocalCapture = hasLocalCapture(scope, captureTarget);
if (!isLocalCapture) {
globalCaptures.push(captureTarget);
}
return {
output: ` + (${capture} === ${value} ? ( ""`,
globalCaptures,
localCaptures: [],
};
},
};
const whenClosingExpressionParser = {
match: /^{\/when}$/,
process(_expression: string, scope: Scope): ExpressionParserResult {
validateClosingBlock(scope, "when");
return {
output: `) : "")`,
globalCaptures: [],
localCaptures: [],
};
},
};
const unlessExpressionParser = {
match: /^{unless ([a-zA-z0-9._]+)((?: *\| *[a-zA-z0-9_]+)+)?}$/,
process(expression: string, scope: Scope): ExpressionParserResult {
const matches = validateExpressionMatches(
scope,
expression,
expression.match(this.match),
);
const [, capture, piping] = matches;
let input = `${capture}`;
const globalCaptures: string[] = [];
scope.blocks.push("unless");
if (piping) {
const chain = buildHelperChain(input, piping);
input = chain.output;
globalCaptures.push(...chain.captures);
}
const [captureTarget] = capture.split(".");
const isLocalCapture = hasLocalCapture(scope, captureTarget);
if (!isLocalCapture) {
globalCaptures.push(captureTarget);
}
return {
output: ` + (!${input} ? ( ""`,
globalCaptures,
localCaptures: [],
};
},
};
const unlessClosingExpressionParser = {
match: /^{\/unless}$/,
process(_expression: string, scope: Scope): ExpressionParserResult {
validateClosingBlock(scope, "unless");
return {
output: `) : "")`,
globalCaptures: [],
localCaptures: [],
};
},
};
const eachArrayExpressionParser = {
match:
/^{each ([a-zA-z0-9_]+)(?:, *([a-zA-z0-9_]+))? +in +([a-zA-z0-9_.]+)}$/,
process(expression: string, scope: Scope): ExpressionParserResult {
const matches = validateExpressionMatches(
scope,
expression,
expression.match(this.match),
);
const [, iteratee, index, iterable] = matches;
scope.blocks.push("each");
const isLocalCapture = hasLocalCapture(scope, iterable);
return {
output: ` + (${iterable}).map((${iteratee}, ${
index ?? "_index"
}) => { return ""`,
globalCaptures: [!isLocalCapture ? iterable : ""].filter(Boolean),
localCaptures: [isLocalCapture ? iterable : ""].filter(Boolean),
};
},
};
const eachDictionaryExpressionParser = {
match:
/^{each ([a-zA-z0-9_]+) *=> *([a-zA-z0-9_]+)(?:, *([a-z0-9_]+))? +in +([a-zA-z0-9_.]+)}$/,
process(expression: string, scope: Scope): ExpressionParserResult {
const matches = validateExpressionMatches(
scope,
expression,
expression.match(this.match),
);
const [, key, value, index, iterable] = matches;
scope.blocks.push("each");
const isLocalCapture = hasLocalCapture(scope, iterable);
return {
output: ` + (Object.keys(${iterable}).map((_key) => [_key, ${iterable}[_key]])).map(([${key}, ${value}], ${
index ?? "_index"
}) => { return ""`,
globalCaptures: [!isLocalCapture ? iterable : ""].filter(Boolean),
localCaptures: [isLocalCapture ? iterable : ""].filter(Boolean),
};
},
};
const eachClosingExpressionParser = {
match: /^{\/each}$/,
process(_expression: string, scope: Scope): ExpressionParserResult {
validateClosingBlock(scope, "each");
return {
output: `; }).join("")`,
globalCaptures: [],
localCaptures: [],
popBlock: true,
};
},
};
const functionCallExpressionParser = {
match: /^{([a-z0-9._]+)( +[a-z0-9_]+=('.*?'|".*?"|[a-z0-9_.]+))+}$/i,
process(expression: string, scope: Scope): ExpressionParserResult {
const matches = validateExpressionMatches(
scope,
expression,
expression.match(this.match),
);
let [, capture, rawAttrs] = matches;
rawAttrs = rawAttrs.trim();
const globalCaptures = [];
const regex = /([a-z0-9_]+)=(".*?"|'.*?'|[a-z0-9_.]+)/;
let result = regex.exec(rawAttrs);
const attrs: string[] = [];
while (result) {
const [, key, value] = result;
attrs.push(key === value ? key : `${key}: ${value}`);
if (!value.match(/^["']/)) {
const [valueTarget] = value.split(".");
const isLocalCapture = hasLocalCapture(scope, valueTarget);
if (!isLocalCapture) {
globalCaptures.push(valueTarget);
}
}
rawAttrs = rawAttrs.substring(key.length).trim();
result = regex.exec(rawAttrs);
}
const input = `_encode(${capture}({${attrs.join(", ")}}))`;
const [captureTarget] = capture.split(".");
const isLocalCapture = hasLocalCapture(scope, captureTarget);
if (!isLocalCapture) {
globalCaptures.push(captureTarget);
}
return {
output: ` + ${input}`,
globalCaptures,
localCaptures: [isLocalCapture ? captureTarget : ""].filter(Boolean),
};
},
};
/**
* List of expression parsers.
* @type {ExpressionParser[]}
*/
export const expressionParsers: ExpressionParser[] = [
variableExpressionParser,
whenExpressionParser,
whenClosingExpressionParser,
ifExpressionParser,
ifClosingExpressionParser,
unlessExpressionParser,
unlessClosingExpressionParser,
eachArrayExpressionParser,
eachDictionaryExpressionParser,
eachClosingExpressionParser,
stringPipingExpressionParser,
functionCallExpressionParser,
];
const compileExpression = (
expression: string,
scope: Scope,
location: Location,
): ExpressionParserResult => {
const parser = validateKnownExpressionParser(
expression,
location,
expressionParsers.find((exp) => exp.match.test(expression)),
);
return parser.process(expression, scope);
};
/**
* Convert a template tree generated by `parse` into a function body.
*
* @param {string[]} tree The template tree.
* @return {CompileToStringResult} The result.
*/
export const compileToString = (tree: string[]): CompileToStringResult => {
let fnStr = `""`;
const scope: Scope = {
globalCaptures: new Set<string>(),
localCaptures: [],
blocks: [],
buffer: "",
};
const localScopes: string[][] = [];
tree.forEach((node) => {
const location = extractLocation(scope);
scope.buffer += node;
if (node.startsWith("{") && node.endsWith("}")) {
const {
output,
globalCaptures: newGlobalCaptures,
localCaptures: newLocalCaptures,
popBlock,
} = compileExpression(node, scope, location);
newGlobalCaptures.forEach((capture) =>
scope.globalCaptures.add(capture.split(".")[0]),
);
if (popBlock) {
localScopes.pop();
} else {
localScopes.push(newLocalCaptures);
}
fnStr += output;
} else {
node = node
.replace(/\n/gm, "\\n")
.replace(/\r/gm, "\\r")
.replace(/\t/gm, "\\t")
.replace(/"/gm, '\\"');
fnStr += ` + "${node}"`;
}
});
return {
output: `return (${fnStr});`,
captures: Array.from<string>(scope.globalCaptures.values()),
};
};
/**
* Compile a template to a function string.
*
* @param {string} name The function name.
* @param {string} template The template that will be parsed.
* @param {boolean} includeEscapeHelper When `true`, the `_escape` helper will
* be embedded into the function.
* @return {string} The function representation.
*/
export const compileToFunctionString = (
name: string,
template: string,
includeEscapeHelper = true,
): string => {
let { output, captures } = compileToString(parse(template));
if (includeEscapeHelper) {
output = `${encodeHelper}\n${output}`;
}
return `function ${name}({${captures.join(", ")}}) { ${output} }`;
};
/**
* Compile a template to a function object.
* This allows parsing and executing templates in runtime.
* Notice that the resulting function wil be anonymous.
*
* @param {string} template The template that will be parsed.
* @param {boolean} includeEscapeHelper When `true`, the `_escape` helper will
* be embedded into the function.
* @return {function} The function representation.
*/
export const compile = (template: string, includeEscapeHelper = true) => {
let { output, captures } = compileToString(parse(template));
if (includeEscapeHelper) {
output = `${encodeHelper}\n${output}`;
}
try {
return new Function(`{${captures.join(", ")}}`, output);
} catch (originalError) {
const error = new InvalidTemplateError(
"The template generated invalid JavaScript code.",
);
error.detail = { template, output, captures };
throw error;
}
};
| 24.56899 | 113 | 0.61012 | 512 | 30 | 1 | 59 | 99 | 17 | 10 | 0 | 69 | 9 | 0 | 12.166667 | 4,597 | 0.01936 | 0.021536 | 0.003698 | 0.001958 | 0 | 0 | 0.334951 | 0.291019 | type Scope = {
globalCaptures;
localCaptures;
blocks;
buffer;
};
type Location = { line; column };
type ExpressionParserResult = {
output;
globalCaptures;
localCaptures;
popBlock?;
};
type ExpressionParser = {
match;
process(expression, scope);
};
type CompileToStringResult = {
/**
* The function body.
* @type {string}
*/
output;
/**
* The list of variables that must be provided to the template function.
* @type {string[]}
*/
captures;
};
class UnmatchedBlockError extends Error {
public detail = { line: 1, column: 1, expected: "", actual: "" };
}
class InvalidTemplateError extends Error {
public detail = { template: "", output: "", captures: [] };
}
class UnknownExpressionError extends Error {
public detail = { expression: "", line: 1, column: 1 };
}
class GenericExpressionError extends Error {
public detail = { expression: "", line: 1, column: 1 };
}
export const encodeHelper = `
const _encode = (unsafe) =>
String(unsafe).replace(
/(?![0-9A-Za-z ])[\\u0000-\\u00FF]/g,
(c) => "&#" + c.charCodeAt(0).toString().padStart(4, "0") + ";"
);
`;
/**
* Decode HTML entities into their character equivalent.
* This is supposed to help with testing, not to bypass escaped values in
* templates.
*
* @param {string} input The encoded string.
* @return {string} The decoded string.
*/
export const decode = (input) =>
input.replace(/(&#(\d+);)/g, (_entity, _match, code) =>
String.fromCharCode(parseInt(code, 10)),
);
/**
* Generate the tree for a template string.
*
* @param {string} template The template string.
* @return {string[]} The template parsed into a tree. Each expression will be
* isolated into its own array item.
*/
export /* Example usages of 'parse' are shown below:
compileToString(parse(template));
*/
const parse = (template) => {
let result = /{(.*?)}/g.exec(template);
const tree = [];
let position;
while (result) {
position = result.index;
if (position !== 0) {
tree.push(template.substring(0, position));
template = template.slice(position);
}
tree.push(result[0]);
template = template.slice(result[0].length);
result = /{(.*?)}/g.exec(template);
}
if (template) {
tree.push(template);
}
return tree;
};
/* Example usages of 'buildHelperChain' are shown below:
buildHelperChain(input, piping);
*/
const buildHelperChain = (
input,
rawHelpers,
) => {
const helpers = rawHelpers.replace(/^ \| /, "").split(/ \| /);
const output = helpers.reduce(
(buffer, helper) => `${helper}(${buffer})`,
input,
);
return {
output,
captures: helpers,
};
};
/* Example usages of 'extractLocation' are shown below:
extractLocation(scope);
*/
const extractLocation = (scope) => {
const lines = scope.buffer.split(/\r?\n/);
const line = Math.max(1, lines.length);
const column = Math.max(1, (lines.pop() ?? "").length);
return { line, column };
};
/* Example usages of 'hasLocalCapture' are shown below:
hasLocalCapture(scope, captureTarget);
hasLocalCapture(scope, iterable);
hasLocalCapture(scope, valueTarget);
*/
const hasLocalCapture = (scope, capture) =>
scope.localCaptures
.flatMap((captures) => Array.from(captures.values()))
.includes(capture);
/* Example usages of 'validateKnownExpressionParser' are shown below:
validateKnownExpressionParser(expression, location, expressionParsers.find((exp) => exp.match.test(expression)));
*/
const validateKnownExpressionParser = (
expression,
location,
parser,
) => {
if (parser) {
return parser;
}
const { line, column } = location;
const error = new UnknownExpressionError(
`Unknown expression: ${expression} (line: ${line}, column: ${column})`,
);
error.detail = { line, column, expression };
throw error;
};
/* Example usages of 'validateExpressionMatches' are shown below:
validateExpressionMatches(scope, expression, expression.match(this.match));
*/
const validateExpressionMatches = (
scope,
expression,
matches,
) => {
if (matches) {
return matches;
}
const error = new GenericExpressionError(
`Cannot run expression parser without matches: ${expression}`,
);
let { line, column } = extractLocation(scope);
column -= expression.length;
error.detail = { line, column, expression };
throw error;
};
/* Example usages of 'validateClosingBlock' are shown below:
validateClosingBlock(scope, "if");
validateClosingBlock(scope, "when");
validateClosingBlock(scope, "unless");
validateClosingBlock(scope, "each");
*/
const validateClosingBlock = (
scope,
currentBlock,
) => {
const expectedBlock = scope.blocks.pop() ?? "unknown";
if (expectedBlock === currentBlock) {
return;
}
let { line, column } = extractLocation(scope);
column -= currentBlock.length + 2;
const error = new UnmatchedBlockError(
`Expected {/${expectedBlock}}, got {/${currentBlock}} (line: ${line}, column: ${column})`,
);
error.detail = {
line,
column,
expected: expectedBlock,
actual: currentBlock,
};
throw error;
};
const variableExpressionParser = {
match: /^{([a-z0-9._]+)((?: *\| *[a-z0-9_]+)+)?}$/i,
process(expression, scope) {
const matches = validateExpressionMatches(
scope,
expression,
expression.match(this.match),
);
const [, capture, piping] = matches;
let input = `${capture}`;
const globalCaptures = [];
if (piping) {
const chain = buildHelperChain(input, piping);
globalCaptures.push(...chain.captures);
input = chain.output;
}
input = `_encode(${input})`;
const [captureTarget] = capture.split(".");
const isLocalCapture = hasLocalCapture(scope, captureTarget);
if (!isLocalCapture) {
globalCaptures.push(captureTarget);
}
return {
output: ` + ${input}`,
globalCaptures,
localCaptures: [isLocalCapture ? captureTarget : ""].filter(Boolean),
};
},
};
const stringPipingExpressionParser = {
match: /^{((["']).*?\2)( *\| *[a-z0-9_.]+)+}$/i,
process(expression, scope) {
const matches = validateExpressionMatches(
scope,
expression,
expression.match(this.match),
);
const [, capture, , piping] = matches;
let input = `${capture}`;
const globalCaptures = [];
if (piping) {
const chain = buildHelperChain(input, piping);
globalCaptures.push(...chain.captures);
input = chain.output;
}
input = `_encode(${input})`;
return {
output: ` + ${input}`,
globalCaptures,
localCaptures: [].filter(Boolean),
};
},
};
const ifExpressionParser = {
match: /^{if ([a-zA-z0-9._]+)((?: *\| *[a-zA-z0-9_]+)+)?}$/,
process(expression, scope) {
const matches = validateExpressionMatches(
scope,
expression,
expression.match(this.match),
);
const [, capture, piping] = matches;
let input = `${capture}`;
const globalCaptures = [];
scope.blocks.push("if");
if (piping) {
const chain = buildHelperChain(input, piping);
input = chain.output;
globalCaptures.push(...chain.captures);
}
const [captureTarget] = capture.split(".");
const isLocalCapture = hasLocalCapture(scope, captureTarget);
if (!isLocalCapture) {
globalCaptures.push(captureTarget);
}
return {
output: ` + (${input} ? ( ""`,
globalCaptures,
localCaptures: [],
};
},
};
const ifClosingExpressionParser = {
match: /^{\/if}$/,
process(_expression, scope) {
validateClosingBlock(scope, "if");
return {
output: `) : "")`,
globalCaptures: [],
localCaptures: [],
};
},
};
const whenExpressionParser = {
match:
/^{when ([a-zA-z0-9._]+)=([a-zA-z0-9._]+|'[^\t\r\n']+'|"[^\t\r\n']+")}$/,
process(expression, scope) {
const matches = validateExpressionMatches(
scope,
expression,
expression.match(this.match),
);
const [, capture, value] = matches;
const globalCaptures = [];
scope.blocks.push("when");
const [captureTarget] = capture.split(".");
const isLocalCapture = hasLocalCapture(scope, captureTarget);
if (!isLocalCapture) {
globalCaptures.push(captureTarget);
}
return {
output: ` + (${capture} === ${value} ? ( ""`,
globalCaptures,
localCaptures: [],
};
},
};
const whenClosingExpressionParser = {
match: /^{\/when}$/,
process(_expression, scope) {
validateClosingBlock(scope, "when");
return {
output: `) : "")`,
globalCaptures: [],
localCaptures: [],
};
},
};
const unlessExpressionParser = {
match: /^{unless ([a-zA-z0-9._]+)((?: *\| *[a-zA-z0-9_]+)+)?}$/,
process(expression, scope) {
const matches = validateExpressionMatches(
scope,
expression,
expression.match(this.match),
);
const [, capture, piping] = matches;
let input = `${capture}`;
const globalCaptures = [];
scope.blocks.push("unless");
if (piping) {
const chain = buildHelperChain(input, piping);
input = chain.output;
globalCaptures.push(...chain.captures);
}
const [captureTarget] = capture.split(".");
const isLocalCapture = hasLocalCapture(scope, captureTarget);
if (!isLocalCapture) {
globalCaptures.push(captureTarget);
}
return {
output: ` + (!${input} ? ( ""`,
globalCaptures,
localCaptures: [],
};
},
};
const unlessClosingExpressionParser = {
match: /^{\/unless}$/,
process(_expression, scope) {
validateClosingBlock(scope, "unless");
return {
output: `) : "")`,
globalCaptures: [],
localCaptures: [],
};
},
};
const eachArrayExpressionParser = {
match:
/^{each ([a-zA-z0-9_]+)(?:, *([a-zA-z0-9_]+))? +in +([a-zA-z0-9_.]+)}$/,
process(expression, scope) {
const matches = validateExpressionMatches(
scope,
expression,
expression.match(this.match),
);
const [, iteratee, index, iterable] = matches;
scope.blocks.push("each");
const isLocalCapture = hasLocalCapture(scope, iterable);
return {
output: ` + (${iterable}).map((${iteratee}, ${
index ?? "_index"
}) => { return ""`,
globalCaptures: [!isLocalCapture ? iterable : ""].filter(Boolean),
localCaptures: [isLocalCapture ? iterable : ""].filter(Boolean),
};
},
};
const eachDictionaryExpressionParser = {
match:
/^{each ([a-zA-z0-9_]+) *=> *([a-zA-z0-9_]+)(?:, *([a-z0-9_]+))? +in +([a-zA-z0-9_.]+)}$/,
process(expression, scope) {
const matches = validateExpressionMatches(
scope,
expression,
expression.match(this.match),
);
const [, key, value, index, iterable] = matches;
scope.blocks.push("each");
const isLocalCapture = hasLocalCapture(scope, iterable);
return {
output: ` + (Object.keys(${iterable}).map((_key) => [_key, ${iterable}[_key]])).map(([${key}, ${value}], ${
index ?? "_index"
}) => { return ""`,
globalCaptures: [!isLocalCapture ? iterable : ""].filter(Boolean),
localCaptures: [isLocalCapture ? iterable : ""].filter(Boolean),
};
},
};
const eachClosingExpressionParser = {
match: /^{\/each}$/,
process(_expression, scope) {
validateClosingBlock(scope, "each");
return {
output: `; }).join("")`,
globalCaptures: [],
localCaptures: [],
popBlock: true,
};
},
};
const functionCallExpressionParser = {
match: /^{([a-z0-9._]+)( +[a-z0-9_]+=('.*?'|".*?"|[a-z0-9_.]+))+}$/i,
process(expression, scope) {
const matches = validateExpressionMatches(
scope,
expression,
expression.match(this.match),
);
let [, capture, rawAttrs] = matches;
rawAttrs = rawAttrs.trim();
const globalCaptures = [];
const regex = /([a-z0-9_]+)=(".*?"|'.*?'|[a-z0-9_.]+)/;
let result = regex.exec(rawAttrs);
const attrs = [];
while (result) {
const [, key, value] = result;
attrs.push(key === value ? key : `${key}: ${value}`);
if (!value.match(/^["']/)) {
const [valueTarget] = value.split(".");
const isLocalCapture = hasLocalCapture(scope, valueTarget);
if (!isLocalCapture) {
globalCaptures.push(valueTarget);
}
}
rawAttrs = rawAttrs.substring(key.length).trim();
result = regex.exec(rawAttrs);
}
const input = `_encode(${capture}({${attrs.join(", ")}}))`;
const [captureTarget] = capture.split(".");
const isLocalCapture = hasLocalCapture(scope, captureTarget);
if (!isLocalCapture) {
globalCaptures.push(captureTarget);
}
return {
output: ` + ${input}`,
globalCaptures,
localCaptures: [isLocalCapture ? captureTarget : ""].filter(Boolean),
};
},
};
/**
* List of expression parsers.
* @type {ExpressionParser[]}
*/
export const expressionParsers = [
variableExpressionParser,
whenExpressionParser,
whenClosingExpressionParser,
ifExpressionParser,
ifClosingExpressionParser,
unlessExpressionParser,
unlessClosingExpressionParser,
eachArrayExpressionParser,
eachDictionaryExpressionParser,
eachClosingExpressionParser,
stringPipingExpressionParser,
functionCallExpressionParser,
];
/* Example usages of 'compileExpression' are shown below:
compileExpression(node, scope, location);
*/
const compileExpression = (
expression,
scope,
location,
) => {
const parser = validateKnownExpressionParser(
expression,
location,
expressionParsers.find((exp) => exp.match.test(expression)),
);
return parser.process(expression, scope);
};
/**
* Convert a template tree generated by `parse` into a function body.
*
* @param {string[]} tree The template tree.
* @return {CompileToStringResult} The result.
*/
export /* Example usages of 'compileToString' are shown below:
compileToString(parse(template));
*/
const compileToString = (tree) => {
let fnStr = `""`;
const scope = {
globalCaptures: new Set<string>(),
localCaptures: [],
blocks: [],
buffer: "",
};
const localScopes = [];
tree.forEach((node) => {
const location = extractLocation(scope);
scope.buffer += node;
if (node.startsWith("{") && node.endsWith("}")) {
const {
output,
globalCaptures: newGlobalCaptures,
localCaptures: newLocalCaptures,
popBlock,
} = compileExpression(node, scope, location);
newGlobalCaptures.forEach((capture) =>
scope.globalCaptures.add(capture.split(".")[0]),
);
if (popBlock) {
localScopes.pop();
} else {
localScopes.push(newLocalCaptures);
}
fnStr += output;
} else {
node = node
.replace(/\n/gm, "\\n")
.replace(/\r/gm, "\\r")
.replace(/\t/gm, "\\t")
.replace(/"/gm, '\\"');
fnStr += ` + "${node}"`;
}
});
return {
output: `return (${fnStr});`,
captures: Array.from<string>(scope.globalCaptures.values()),
};
};
/**
* Compile a template to a function string.
*
* @param {string} name The function name.
* @param {string} template The template that will be parsed.
* @param {boolean} includeEscapeHelper When `true`, the `_escape` helper will
* be embedded into the function.
* @return {string} The function representation.
*/
export const compileToFunctionString = (
name,
template,
includeEscapeHelper = true,
) => {
let { output, captures } = compileToString(parse(template));
if (includeEscapeHelper) {
output = `${encodeHelper}\n${output}`;
}
return `function ${name}({${captures.join(", ")}}) { ${output} }`;
};
/**
* Compile a template to a function object.
* This allows parsing and executing templates in runtime.
* Notice that the resulting function wil be anonymous.
*
* @param {string} template The template that will be parsed.
* @param {boolean} includeEscapeHelper When `true`, the `_escape` helper will
* be embedded into the function.
* @return {function} The function representation.
*/
export const compile = (template, includeEscapeHelper = true) => {
let { output, captures } = compileToString(parse(template));
if (includeEscapeHelper) {
output = `${encodeHelper}\n${output}`;
}
try {
return new Function(`{${captures.join(", ")}}`, output);
} catch (originalError) {
const error = new InvalidTemplateError(
"The template generated invalid JavaScript code.",
);
error.detail = { template, output, captures };
throw error;
}
};
|
c13e148d1ede67fc0ecec30bf3b92331a2e53c26 | 2,822 | ts | TypeScript | packages/system/src/utils/formatData.ts | lqsong/admin-vue3-micro-qiankun | c992f2d7ae52c3ab54cf0a59d6ed614360c5908d | [
"MIT"
] | 9 | 2022-02-21T04:30:51.000Z | 2022-03-07T05:34:43.000Z | packages/system/src/utils/formatData.ts | lqsong/admin-vue3-micro-qiankun | c992f2d7ae52c3ab54cf0a59d6ed614360c5908d | [
"MIT"
] | 3 | 2022-02-28T14:38:17.000Z | 2022-03-03T00:52:01.000Z | packages/system/src/utils/formatData.ts | lqsong/admin-vue3-micro-qiankun | c992f2d7ae52c3ab54cf0a59d6ed614360c5908d | [
"MIT"
] | 2 | 2022-03-07T06:23:46.000Z | 2022-03-29T02:18:13.000Z | /**
* 数据格式化
* @author LiQingSong
*/
export interface Array2dToStringReturn {
idStr: string;
idsStr: string;
}
export interface LevelData {
id: number;
pid: number;
name: string;
}
export interface EleUiLevelData {
value: string | number;
label: string | number;
children: EleUiLevelData[] | null;
}
/**
* 二维数组 返回对应的 字符串 , 链接
* @param val number[][] 下拉框的值 格式 [1,[1,2],[1,3]]
* @returns Array2dToStringReturn
* @author LiQingSong
*/
export function Array2dToString(val: number[][]): Array2dToStringReturn {
const obj: Array2dToStringReturn = {
idStr: '',
idsStr: ''
};
if (!val) {
return obj;
}
const array: number[][] = val;
const arrLen: number = array.length;
const idArr: number[] = [];
const idsArr: string[] = [];
for (let index = 0; index < arrLen; index++) {
const element: number[] = array[index];
const eleLen: number = element.length;
if (eleLen > 0) {
idArr.push(element[eleLen - 1]);
idsArr.push(element.join('-'));
}
}
obj['idStr'] = idArr.join(',');
obj['idsStr'] = idsArr.join(',');
return obj;
}
/**
* 字符串 转 二维数组
* @param val String 下拉框的值 格式 1,1-2,1-3,1-2-4
* @returns number[][]
* @author LiQingSong
*/
export function StringToArray2d(val: string): number[][] {
if (!val) {
return [];
}
const array: string[] = val.split(',');
const arrLen: number = array.length;
const arr: number[][] = [];
for (let index = 0; index < arrLen; index++) {
const element: string = array[index];
const eleArr: string[] = element.split('-');
const eArr: number[] = eleArr.map(item => {
return Number(item);
});
arr.push(eArr);
}
return arr;
}
/**
* 格式化 element-ui 层级数据
* @param data T[] 需要格式化的数据
* @param value string data 对应的 value 字段名
* @param label string data 对应的 label 字段名
* @param pid string data 对应的 pid 字段名
* @param pidVal string| number 起始 pid 值
* @returns T[] | null
* @author LiQingSong
*/
export function formatEleUiLevelData<T extends LevelData>(data: T[], value: string, label: string, pid: string, pidVal: string | number): EleUiLevelData[] | null {
const len: number = data.length;
if (len < 1) {
return null;
}
const newData: EleUiLevelData [] = [];
for (let index = 0; index < len; index++) {
const element: T = data[index];
if (element[pid] === pidVal) {
newData.push({
value: element[value],
label: element[label],
children: formatEleUiLevelData(data, value, label, pid, element[value])
});
}
}
return newData.length > 0 ? newData : null;
} | 24.53913 | 164 | 0.561304 | 73 | 4 | 0 | 8 | 19 | 8 | 1 | 0 | 30 | 3 | 0 | 13.5 | 849 | 0.014134 | 0.022379 | 0.009423 | 0.003534 | 0 | 0 | 0.769231 | 0.281232 | /**
* 数据格式化
* @author LiQingSong
*/
export interface Array2dToStringReturn {
idStr;
idsStr;
}
export interface LevelData {
id;
pid;
name;
}
export interface EleUiLevelData {
value;
label;
children;
}
/**
* 二维数组 返回对应的 字符串 , 链接
* @param val number[][] 下拉框的值 格式 [1,[1,2],[1,3]]
* @returns Array2dToStringReturn
* @author LiQingSong
*/
export function Array2dToString(val) {
const obj = {
idStr: '',
idsStr: ''
};
if (!val) {
return obj;
}
const array = val;
const arrLen = array.length;
const idArr = [];
const idsArr = [];
for (let index = 0; index < arrLen; index++) {
const element = array[index];
const eleLen = element.length;
if (eleLen > 0) {
idArr.push(element[eleLen - 1]);
idsArr.push(element.join('-'));
}
}
obj['idStr'] = idArr.join(',');
obj['idsStr'] = idsArr.join(',');
return obj;
}
/**
* 字符串 转 二维数组
* @param val String 下拉框的值 格式 1,1-2,1-3,1-2-4
* @returns number[][]
* @author LiQingSong
*/
export function StringToArray2d(val) {
if (!val) {
return [];
}
const array = val.split(',');
const arrLen = array.length;
const arr = [];
for (let index = 0; index < arrLen; index++) {
const element = array[index];
const eleArr = element.split('-');
const eArr = eleArr.map(item => {
return Number(item);
});
arr.push(eArr);
}
return arr;
}
/**
* 格式化 element-ui 层级数据
* @param data T[] 需要格式化的数据
* @param value string data 对应的 value 字段名
* @param label string data 对应的 label 字段名
* @param pid string data 对应的 pid 字段名
* @param pidVal string| number 起始 pid 值
* @returns T[] | null
* @author LiQingSong
*/
export /* Example usages of 'formatEleUiLevelData' are shown below:
formatEleUiLevelData(data, value, label, pid, element[value]);
*/
function formatEleUiLevelData<T extends LevelData>(data, value, label, pid, pidVal) {
const len = data.length;
if (len < 1) {
return null;
}
const newData = [];
for (let index = 0; index < len; index++) {
const element = data[index];
if (element[pid] === pidVal) {
newData.push({
value: element[value],
label: element[label],
children: formatEleUiLevelData(data, value, label, pid, element[value])
});
}
}
return newData.length > 0 ? newData : null;
} |
c169b5de951cbe6b41a13721727aee470ecce5b9 | 3,301 | ts | TypeScript | src/index.ts | getoslash/server-timify | ed79038078faeac2823b29caf2103570c398cd1f | [
"MIT"
] | null | null | null | src/index.ts | getoslash/server-timify | ed79038078faeac2823b29caf2103570c398cd1f | [
"MIT"
] | null | null | null | src/index.ts | getoslash/server-timify | ed79038078faeac2823b29caf2103570c398cd1f | [
"MIT"
] | 2 | 2022-02-07T14:53:35.000Z | 2022-02-10T12:18:26.000Z | interface ServerTiming {
/** The name attribute is required, and gives a short name to the server-specified metric. */
name: string
/** (Optional) The duration attribute is a double (like `0.0`) that contains the server-specified metric duration. Usually milliseconds. */
duration?: number
/** (Optional) The description describes the server-specified metric. */
description?: string
}
export type ServerTimings = Array<ServerTiming>
/**
* Parse a given [`Server-Timing`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server-Timing) header string value into corresponding timing components.
*
* @example
* ```
* parse('missedCache')
* // [{ name: "missedCache" }]
* parse('cpu;dur=2.4')
* // [{ name: "cpu", duration: 2.4 }]
* parse('cache;desc="Cache Read";dur=23.2')
* // [{ name: "cache", description: "Cache Read", duration: 23.2 }]
* parse('db;dur=53, app;dur=47.2')
* // [{ name: "db", duration: 53 }, { name: "app", duration: 47.2 }]
* ```
* @param timingHeader Header value (as string) to parse.
* @returns {ServerTimings} Timing components as an object.
*/
export const parse = (timingHeader: string): ServerTimings => {
if (!timingHeader) return []
if (typeof timingHeader !== 'string') return []
const timings: ServerTimings = []
// If only a single metric is sent, and that too with only the name, quickly parse + return it.
if (!timingHeader.includes(',') && !timingHeader.includes(';'))
return [
{
name: timingHeader.slice(),
},
]
const metrics = timingHeader
.slice()
.split(',')
.map((_) => _.trim())
metrics.forEach((metric) => {
const timing: ServerTiming = {
name: '',
}
metric
.split(';')
.map((_) => _.trim())
.forEach((parts) => {
if (!parts.includes('=')) {
timing.name = parts
}
if (parts.startsWith('desc='))
// Clean up leading and trailing single/double quotes.
timing.description = parts
.split('=')[1]
.trim()
.replace(/^"(.+(?="$))"$/, '$1')
else if (parts.startsWith('dur='))
timing.duration = Number(parts.split('=')[1].trim())
})
timings.push(timing)
})
return timings
}
/**
* Stringify a given {@link ServerTimings} object into a [`Server-Timing`](https://www.w3.org/TR/server-timing/#the-server-timing-header-field) header string value.
*
* @example
* ```
* stringify([{ name: "missedCache" }])
* // missedCache
* stringify([{ name: "cpu", duration: 2.4 }])
* // cpu;dur=2.4
* stringify([{ name: "cache", description: "Cache Read", duration: 23.2 }])
* // cache;desc="Cache Read";dur=23.2
* stringify([{ name: "db", duration: 53 }, { name: "app", duration: 47.2 }])
* // db;dur=53, app;dur=47.2
* ```
* @param {ServerTimings} timings Timings object to stringify.
* @returns Server-Timings header value as string.
*/
export const stringify = (timings: ServerTimings): string => {
if (!Array.isArray(timings)) return ''
return timings
.map((timing) => {
let metric = `${timing.name}`
if (timing.duration) metric = `${metric};dur=${timing.duration}`
if (timing.description) metric = `${metric};desc="${timing.description}"`
return metric
})
.join(', ')
}
| 33.01 | 165 | 0.60618 | 54 | 7 | 0 | 7 | 6 | 3 | 0 | 0 | 5 | 2 | 1 | 11.285714 | 937 | 0.014941 | 0.006403 | 0.003202 | 0.002134 | 0.001067 | 0 | 0.217391 | 0.228933 | interface ServerTiming {
/** The name attribute is required, and gives a short name to the server-specified metric. */
name
/** (Optional) The duration attribute is a double (like `0.0`) that contains the server-specified metric duration. Usually milliseconds. */
duration?
/** (Optional) The description describes the server-specified metric. */
description?
}
export type ServerTimings = Array<ServerTiming>
/**
* Parse a given [`Server-Timing`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server-Timing) header string value into corresponding timing components.
*
* @example
* ```
* parse('missedCache')
* // [{ name: "missedCache" }]
* parse('cpu;dur=2.4')
* // [{ name: "cpu", duration: 2.4 }]
* parse('cache;desc="Cache Read";dur=23.2')
* // [{ name: "cache", description: "Cache Read", duration: 23.2 }]
* parse('db;dur=53, app;dur=47.2')
* // [{ name: "db", duration: 53 }, { name: "app", duration: 47.2 }]
* ```
* @param timingHeader Header value (as string) to parse.
* @returns {ServerTimings} Timing components as an object.
*/
export const parse = (timingHeader) => {
if (!timingHeader) return []
if (typeof timingHeader !== 'string') return []
const timings = []
// If only a single metric is sent, and that too with only the name, quickly parse + return it.
if (!timingHeader.includes(',') && !timingHeader.includes(';'))
return [
{
name: timingHeader.slice(),
},
]
const metrics = timingHeader
.slice()
.split(',')
.map((_) => _.trim())
metrics.forEach((metric) => {
const timing = {
name: '',
}
metric
.split(';')
.map((_) => _.trim())
.forEach((parts) => {
if (!parts.includes('=')) {
timing.name = parts
}
if (parts.startsWith('desc='))
// Clean up leading and trailing single/double quotes.
timing.description = parts
.split('=')[1]
.trim()
.replace(/^"(.+(?="$))"$/, '$1')
else if (parts.startsWith('dur='))
timing.duration = Number(parts.split('=')[1].trim())
})
timings.push(timing)
})
return timings
}
/**
* Stringify a given {@link ServerTimings} object into a [`Server-Timing`](https://www.w3.org/TR/server-timing/#the-server-timing-header-field) header string value.
*
* @example
* ```
* stringify([{ name: "missedCache" }])
* // missedCache
* stringify([{ name: "cpu", duration: 2.4 }])
* // cpu;dur=2.4
* stringify([{ name: "cache", description: "Cache Read", duration: 23.2 }])
* // cache;desc="Cache Read";dur=23.2
* stringify([{ name: "db", duration: 53 }, { name: "app", duration: 47.2 }])
* // db;dur=53, app;dur=47.2
* ```
* @param {ServerTimings} timings Timings object to stringify.
* @returns Server-Timings header value as string.
*/
export const stringify = (timings) => {
if (!Array.isArray(timings)) return ''
return timings
.map((timing) => {
let metric = `${timing.name}`
if (timing.duration) metric = `${metric};dur=${timing.duration}`
if (timing.description) metric = `${metric};desc="${timing.description}"`
return metric
})
.join(', ')
}
|
c17b22bb7a2c6db894fed161f71c4847d2454d7b | 1,018 | ts | TypeScript | src/utils/createAccountTransasctionsFilter.ts | web3-systems/react-multichain | 7cb6f5099c725caf87d75dc18d2fbe012d9e10d5 | [
"MIT"
] | 4 | 2022-02-02T11:30:07.000Z | 2022-03-17T00:00:00.000Z | src/utils/createAccountTransasctionsFilter.ts | web3-systems/react-multichain | 7cb6f5099c725caf87d75dc18d2fbe012d9e10d5 | [
"MIT"
] | 3 | 2022-02-21T09:16:23.000Z | 2022-03-21T09:47:36.000Z | src/utils/createAccountTransasctionsFilter.ts | web3-systems/react-multichain | 7cb6f5099c725caf87d75dc18d2fbe012d9e10d5 | [
"MIT"
] | null | null | null | function createAccountTransasctionsFilter(
address: string,
type: 'from' | 'to' | 'self' | 'all'
) {
switch (type) {
case 'from':
return {
from: {
$eq: address,
},
};
case 'to':
return {
$and: [
{
to: {
$eq: address,
},
},
{
from: {
$ne: address,
},
},
],
};
case 'self':
return {
$and: [
{
to: {
$eq: address,
},
},
{
from: {
$eq: address,
},
},
],
};
case 'all':
default:
return {
$or: [
{
from: {
$contains: address,
},
},
{
to: {
$contains: address,
},
},
],
};
}
}
export default createAccountTransasctionsFilter;
| 16.419355 | 48 | 0.284872 | 60 | 1 | 0 | 2 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 54 | 230 | 0.013043 | 0 | 0 | 0 | 0 | 0 | 0.333333 | 0.200332 | /* Example usages of 'createAccountTransasctionsFilter' are shown below:
;
*/
function createAccountTransasctionsFilter(
address,
type
) {
switch (type) {
case 'from':
return {
from: {
$eq: address,
},
};
case 'to':
return {
$and: [
{
to: {
$eq: address,
},
},
{
from: {
$ne: address,
},
},
],
};
case 'self':
return {
$and: [
{
to: {
$eq: address,
},
},
{
from: {
$eq: address,
},
},
],
};
case 'all':
default:
return {
$or: [
{
from: {
$contains: address,
},
},
{
to: {
$contains: address,
},
},
],
};
}
}
export default createAccountTransasctionsFilter;
|
c1bbadb59f727f57a49ab5115ce2e5e6dbb3a04f | 3,589 | ts | TypeScript | src/shared/provider/error-provider.ts | arifwidianto08/ngulik-nestjs-graphql | 1068f1ee454ee34ba12e43f0e90d519507c81928 | [
"MIT"
] | 1 | 2022-03-13T17:06:27.000Z | 2022-03-13T17:06:27.000Z | src/shared/provider/error-provider.ts | arifwidianto08/ngulik-nestjs-graphql | 1068f1ee454ee34ba12e43f0e90d519507c81928 | [
"MIT"
] | null | null | null | src/shared/provider/error-provider.ts | arifwidianto08/ngulik-nestjs-graphql | 1068f1ee454ee34ba12e43f0e90d519507c81928 | [
"MIT"
] | null | null | null | export enum ErrorCodeEnum {
BAD_REQUEST_ERROR = "BAD_REQUEST_ERROR",
VALIDATION_ERROR = "VALIDATION_ERROR",
INTERNAL_SERVER_ERROR = "INTERNAL_SERVER_ERROR",
NOT_FOUND_ERROR = "NOT_FOUND_ERROR",
TOKEN_INVALID = "INVALID_TOKEN",
FORBIDDEN_ERROR = "FORBIDDEN_ERROR",
UNAUTHORIZED_ERROR = "UNAUTHORIZED_ERROR",
}
export interface CustomError {
meta: {
errors?: any[];
message?: string | string[];
statusCode?: number;
errorCode?: ErrorCodeEnum;
fields?: any;
};
}
export class BadRequestError implements CustomError {
meta: {
errors: any[];
message: string;
statusCode: number;
errorCode: ErrorCodeEnum;
};
constructor(message: string, meta?: CustomError["meta"]) {
this.meta = {
message: message || "Bad Request",
errors: [message],
statusCode: (meta && meta?.statusCode) || 400,
errorCode: (meta && meta?.errorCode) || ErrorCodeEnum.BAD_REQUEST_ERROR,
};
}
}
export class InternalServerError implements CustomError {
meta: {
errors: any[];
message: string;
statusCode: number;
errorCode: ErrorCodeEnum;
};
constructor(message?: string, meta?: CustomError["meta"]) {
this.meta = {
message: message || "Internal Server Error",
errors: [message],
statusCode: (meta && meta?.statusCode) || 500,
errorCode:
(meta && meta?.errorCode) || ErrorCodeEnum.INTERNAL_SERVER_ERROR,
};
}
}
export class NotFoundError implements CustomError {
meta: {
errors: any[];
message: string;
statusCode: number;
errorCode: ErrorCodeEnum;
};
constructor(message?: string, meta?: CustomError["meta"]) {
this.meta = {
message: message || "Document Not Found!",
errors: [message],
statusCode: (meta && meta?.statusCode) || 404,
errorCode: (meta && meta?.errorCode) || ErrorCodeEnum.NOT_FOUND_ERROR,
};
}
}
export class ValidationError implements CustomError {
meta: {
errors: any[];
message: string | string[];
statusCode: number;
errorCode: ErrorCodeEnum;
};
constructor(message?: string | string[], meta?: CustomError["meta"]) {
if (Array.isArray(message)) {
this.meta = {
message: message[0] || "Validation error",
errors: message || ["Validation error"],
statusCode: (meta && meta?.statusCode) || 422,
errorCode: (meta && meta?.errorCode) || ErrorCodeEnum.VALIDATION_ERROR,
};
} else {
this.meta = {
message: message || "Validation error",
errors: [message || "Validation error"],
statusCode: (meta && meta?.statusCode) || 422,
errorCode: (meta && meta?.errorCode) || ErrorCodeEnum.VALIDATION_ERROR,
};
}
}
}
export class UnauthorizedError implements CustomError {
meta: {
errors: any[];
message: string;
statusCode: number;
errorCode: ErrorCodeEnum;
};
constructor(message?: string, meta?: CustomError["meta"]) {
this.meta = {
message: message || "Authorization Error",
errors: [message || "Authorization Error"],
statusCode: (meta && meta?.statusCode) || 401,
errorCode: (meta && meta?.errorCode) || ErrorCodeEnum.UNAUTHORIZED_ERROR,
};
}
}
export class ForbiddenError implements CustomError {
meta: {
errors: any[];
message: string;
statusCode: number;
errorCode: ErrorCodeEnum;
};
constructor(message?: string, meta?: CustomError["meta"]) {
this.meta = {
message:
message ||
`You don't have permission to access this route / on this server!`,
errors: [
message ||
`You don't have permission to access this route / on this server!`,
],
statusCode: (meta && meta?.statusCode) || 403,
errorCode: (meta && meta?.errorCode) || ErrorCodeEnum.FORBIDDEN_ERROR,
};
}
}
| 26.19708 | 76 | 0.673447 | 129 | 6 | 0 | 12 | 0 | 7 | 0 | 8 | 23 | 7 | 0 | 8.5 | 1,057 | 0.017029 | 0 | 0.006623 | 0.006623 | 0 | 0.32 | 0.92 | 0.214296 | export enum ErrorCodeEnum {
BAD_REQUEST_ERROR = "BAD_REQUEST_ERROR",
VALIDATION_ERROR = "VALIDATION_ERROR",
INTERNAL_SERVER_ERROR = "INTERNAL_SERVER_ERROR",
NOT_FOUND_ERROR = "NOT_FOUND_ERROR",
TOKEN_INVALID = "INVALID_TOKEN",
FORBIDDEN_ERROR = "FORBIDDEN_ERROR",
UNAUTHORIZED_ERROR = "UNAUTHORIZED_ERROR",
}
export interface CustomError {
meta;
}
export class BadRequestError implements CustomError {
meta;
constructor(message, meta?) {
this.meta = {
message: message || "Bad Request",
errors: [message],
statusCode: (meta && meta?.statusCode) || 400,
errorCode: (meta && meta?.errorCode) || ErrorCodeEnum.BAD_REQUEST_ERROR,
};
}
}
export class InternalServerError implements CustomError {
meta;
constructor(message?, meta?) {
this.meta = {
message: message || "Internal Server Error",
errors: [message],
statusCode: (meta && meta?.statusCode) || 500,
errorCode:
(meta && meta?.errorCode) || ErrorCodeEnum.INTERNAL_SERVER_ERROR,
};
}
}
export class NotFoundError implements CustomError {
meta;
constructor(message?, meta?) {
this.meta = {
message: message || "Document Not Found!",
errors: [message],
statusCode: (meta && meta?.statusCode) || 404,
errorCode: (meta && meta?.errorCode) || ErrorCodeEnum.NOT_FOUND_ERROR,
};
}
}
export class ValidationError implements CustomError {
meta;
constructor(message?, meta?) {
if (Array.isArray(message)) {
this.meta = {
message: message[0] || "Validation error",
errors: message || ["Validation error"],
statusCode: (meta && meta?.statusCode) || 422,
errorCode: (meta && meta?.errorCode) || ErrorCodeEnum.VALIDATION_ERROR,
};
} else {
this.meta = {
message: message || "Validation error",
errors: [message || "Validation error"],
statusCode: (meta && meta?.statusCode) || 422,
errorCode: (meta && meta?.errorCode) || ErrorCodeEnum.VALIDATION_ERROR,
};
}
}
}
export class UnauthorizedError implements CustomError {
meta;
constructor(message?, meta?) {
this.meta = {
message: message || "Authorization Error",
errors: [message || "Authorization Error"],
statusCode: (meta && meta?.statusCode) || 401,
errorCode: (meta && meta?.errorCode) || ErrorCodeEnum.UNAUTHORIZED_ERROR,
};
}
}
export class ForbiddenError implements CustomError {
meta;
constructor(message?, meta?) {
this.meta = {
message:
message ||
`You don't have permission to access this route / on this server!`,
errors: [
message ||
`You don't have permission to access this route / on this server!`,
],
statusCode: (meta && meta?.statusCode) || 403,
errorCode: (meta && meta?.errorCode) || ErrorCodeEnum.FORBIDDEN_ERROR,
};
}
}
|
c1f912156e972b57a9a62ef27f1aeb4f25480629 | 2,216 | ts | TypeScript | src/v0/stableswapMath.ts | Algofiorg/algofi-amm-js-sdk | 377690b8ea97993900b34a92f113ea63e47f4dd0 | [
"MIT"
] | 3 | 2022-03-18T13:08:36.000Z | 2022-03-28T19:59:21.000Z | src/v0/stableswapMath.ts | Algofiorg/algofi-amm-js-sdk | 377690b8ea97993900b34a92f113ea63e47f4dd0 | [
"MIT"
] | null | null | null | src/v0/stableswapMath.ts | Algofiorg/algofi-amm-js-sdk | 377690b8ea97993900b34a92f113ea63e47f4dd0 | [
"MIT"
] | 1 | 2022-01-26T03:27:48.000Z | 2022-01-26T03:27:48.000Z | const A_PRECISION = BigInt(1000000)
export function getD(tokenAmounts: Array<number>, amplificationFactor: number) : [number, number] {
let N_COINS = tokenAmounts.length
let S = BigInt(0)
let Dprev = BigInt(0)
for (var _x of Array.from(tokenAmounts)) {
S += BigInt(_x)
}
if (S == BigInt(0)) {
return [0, 0]
}
let D = S
let Ann = BigInt(amplificationFactor * Math.pow(N_COINS, N_COINS))
for (var _i = 0; _i < 255; _i++) {
var D_P = D
for (var _x of Array.from(tokenAmounts)) {
D_P = D_P * D / (BigInt(_x) * BigInt(N_COINS))
}
Dprev = D
D = (
(Ann * S / A_PRECISION + D_P * BigInt(N_COINS))
* D
/ ((Ann - A_PRECISION) * D / A_PRECISION + BigInt(N_COINS + 1) * D_P)
)
if (D > Dprev) {
if (D - Dprev <= BigInt(1)) {
return [Number(D), _i]
}
} else {
if (Dprev - D <= BigInt(1)) {
return [Number(D), _i]
}
}
}
}
export function getY(
i: number, j: number, x: number, tokenAmounts: Array<number>, D: number, amplificationFactor: number
): [number, number]
{
let N_COINS = tokenAmounts.length
let Ann = BigInt(amplificationFactor * Math.pow(N_COINS, N_COINS))
let c = BigInt(D)
let S = BigInt(0)
let _x = BigInt(0)
let y_prev = BigInt(0)
for (var _i = 0; _i < N_COINS; _i++) {
if (_i == i) {
_x = BigInt(x)
} else if (_i != j) {
_x = BigInt(tokenAmounts[_i])
} else {
continue
}
S += _x
c = c * BigInt(D) / (BigInt(_x) * BigInt(N_COINS))
}
c = c * BigInt(D) * A_PRECISION / (Ann * BigInt(N_COINS))
let b = S + BigInt(D) * A_PRECISION / Ann
let y = BigInt(D)
for (var _i = 0; _i < 255; _i++) {
y_prev = y
y = (y * y + c) / (BigInt(2) * y + b - BigInt(D))
if (y > y_prev) {
if (y - y_prev <= BigInt(1)) {
return [Number(y), _i]
}
} else {
if (y_prev - y <= BigInt(1)) {
return [Number(y), _i]
}
}
}
} | 27.7 | 104 | 0.473375 | 73 | 2 | 0 | 8 | 18 | 0 | 0 | 0 | 12 | 0 | 0 | 32.5 | 767 | 0.013038 | 0.023468 | 0 | 0 | 0 | 0 | 0.428571 | 0.276791 | const A_PRECISION = BigInt(1000000)
export function getD(tokenAmounts, amplificationFactor) {
let N_COINS = tokenAmounts.length
let S = BigInt(0)
let Dprev = BigInt(0)
for (var _x of Array.from(tokenAmounts)) {
S += BigInt(_x)
}
if (S == BigInt(0)) {
return [0, 0]
}
let D = S
let Ann = BigInt(amplificationFactor * Math.pow(N_COINS, N_COINS))
for (var _i = 0; _i < 255; _i++) {
var D_P = D
for (var _x of Array.from(tokenAmounts)) {
D_P = D_P * D / (BigInt(_x) * BigInt(N_COINS))
}
Dprev = D
D = (
(Ann * S / A_PRECISION + D_P * BigInt(N_COINS))
* D
/ ((Ann - A_PRECISION) * D / A_PRECISION + BigInt(N_COINS + 1) * D_P)
)
if (D > Dprev) {
if (D - Dprev <= BigInt(1)) {
return [Number(D), _i]
}
} else {
if (Dprev - D <= BigInt(1)) {
return [Number(D), _i]
}
}
}
}
export function getY(
i, j, x, tokenAmounts, D, amplificationFactor
)
{
let N_COINS = tokenAmounts.length
let Ann = BigInt(amplificationFactor * Math.pow(N_COINS, N_COINS))
let c = BigInt(D)
let S = BigInt(0)
let _x = BigInt(0)
let y_prev = BigInt(0)
for (var _i = 0; _i < N_COINS; _i++) {
if (_i == i) {
_x = BigInt(x)
} else if (_i != j) {
_x = BigInt(tokenAmounts[_i])
} else {
continue
}
S += _x
c = c * BigInt(D) / (BigInt(_x) * BigInt(N_COINS))
}
c = c * BigInt(D) * A_PRECISION / (Ann * BigInt(N_COINS))
let b = S + BigInt(D) * A_PRECISION / Ann
let y = BigInt(D)
for (var _i = 0; _i < 255; _i++) {
y_prev = y
y = (y * y + c) / (BigInt(2) * y + b - BigInt(D))
if (y > y_prev) {
if (y - y_prev <= BigInt(1)) {
return [Number(y), _i]
}
} else {
if (y_prev - y <= BigInt(1)) {
return [Number(y), _i]
}
}
}
} |
1b331bdc9d2cf28333633b3e7615cbede1015619 | 4,481 | ts | TypeScript | src/algebra/equations.ts | donatto-minaya/ax-calculator | 1b015e2e58796b76bd40fa3055b8709e51137a08 | [
"Apache-2.0"
] | 3 | 2022-01-04T20:01:33.000Z | 2022-02-24T03:27:24.000Z | src/algebra/equations.ts | donatto22/ax-calculator | 1b015e2e58796b76bd40fa3055b8709e51137a08 | [
"Apache-2.0"
] | null | null | null | src/algebra/equations.ts | donatto22/ax-calculator | 1b015e2e58796b76bd40fa3055b8709e51137a08 | [
"Apache-2.0"
] | 1 | 2022-02-15T23:35:52.000Z | 2022-02-15T23:35:52.000Z | export const Equations = {
/**
Example -> f1: x² + 7x + 6 = 0
Example -> f2: 3x² - 27 = 0
@description The parameters vary according to the formula
@param a - For f1 -> 1, For f2 -> 3
@param b - For f1 -> 7, For f2 -> -27
@param c - For f1 -> 6, Do not place anything
**/
secondDegree: function (a: number, b: number, c: number) {
if(typeof(c) == 'undefined') {
let x: string | number, internal: string | number = (b * -1) / a
if(!Number.isInteger(internal)) {
var top = b * - 1
var bottom = a
//Si la raíz cuadrada es un numero entero
if(Number.isInteger(Math.sqrt(b * - 1))) {
top = Math.sqrt(b * - 1)
}
//Si la raíz cuadrada es un numero entero
if(Number.isInteger(Math.sqrt(a))) {
bottom = Math.sqrt(a)
}
internal = String(top) + "/" + bottom
x = `±√${internal}`
}
else {
if(internal < 0) {
if(Number.isInteger(Math.sqrt(internal * -1))) {
internal = Math.sqrt(internal * -1)
x = `±${internal}𝓲`
}
else {
x = "𝓲√" + (internal * -1)
}
}
else {
x = Math.sqrt(internal);
}
}
return x;
}
else {
let internal: string | number = (b*b) - (4 * a * c)
let interna2: string | number = Math.sqrt(internal)
let x1: string | number, x2: string | number
if (!Number.isInteger(interna2)) {
interna2 = "√" + internal;
}
if (internal < 0) {
interna2 = `𝓲√${String(-1 * internal)}`
}
if (typeof(interna2) == 'string') {
x1 = String(-1 * b) + "/" + String(2 * a) + " + " + interna2 + "/" + String(2 * a)
x2 = String(-1 * b) + "/" + String(2 * a) + " - " + interna2 + "/" + String(2 * a)
return {
x1, x2
}
}
else {
x1 = (((-1 * b) + interna2) / (2 * a)).toFixed(2)
x2 = (((-1 * b) - interna2) / (2 * a)).toFixed(2)
}
if (Number.parseInt(x1) < 1) {
let top = ((-1 * b) + Math.sqrt((b*b) - (4 * a * c)));
let bottom = 2 * a;
for (let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if(Number.parseInt(x1) < 0) {
x1 = "-" + String(top + "/" + bottom);
}
else {
x1 = String(top + "/" + bottom)
}
break;
}
}
}
}
if (Number.parseInt(x2) < 1) {
var top = ((-1 * b) - Math.sqrt((b*b) - (4 * a * c)));
var bottom = 2 * a;
for (let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if (top < 0) {
x2 = "-" + String(top + "/" + bottom);
}
else {
x2 = String(top + "/" + bottom)
}
break;
}
}
}
}
return { x1, x2 }
}
}
} | 32.23741 | 98 | 0.289667 | 99 | 1 | 0 | 3 | 15 | 0 | 0 | 0 | 15 | 0 | 2 | 95 | 1,052 | 0.003802 | 0.014259 | 0 | 0 | 0.001901 | 0 | 0.789474 | 0.224619 | export const Equations = {
/**
Example -> f1: x² + 7x + 6 = 0
Example -> f2: 3x² - 27 = 0
@description The parameters vary according to the formula
@param a - For f1 -> 1, For f2 -> 3
@param b - For f1 -> 7, For f2 -> -27
@param c - For f1 -> 6, Do not place anything
**/
secondDegree: function (a, b, c) {
if(typeof(c) == 'undefined') {
let x, internal = (b * -1) / a
if(!Number.isInteger(internal)) {
var top = b * - 1
var bottom = a
//Si la raíz cuadrada es un numero entero
if(Number.isInteger(Math.sqrt(b * - 1))) {
top = Math.sqrt(b * - 1)
}
//Si la raíz cuadrada es un numero entero
if(Number.isInteger(Math.sqrt(a))) {
bottom = Math.sqrt(a)
}
internal = String(top) + "/" + bottom
x = `±√${internal}`
}
else {
if(internal < 0) {
if(Number.isInteger(Math.sqrt(internal * -1))) {
internal = Math.sqrt(internal * -1)
x = `±${internal}𝓲`
}
else {
x = "𝓲√" + (internal * -1)
}
}
else {
x = Math.sqrt(internal);
}
}
return x;
}
else {
let internal = (b*b) - (4 * a * c)
let interna2 = Math.sqrt(internal)
let x1, x2
if (!Number.isInteger(interna2)) {
interna2 = "√" + internal;
}
if (internal < 0) {
interna2 = `𝓲√${String(-1 * internal)}`
}
if (typeof(interna2) == 'string') {
x1 = String(-1 * b) + "/" + String(2 * a) + " + " + interna2 + "/" + String(2 * a)
x2 = String(-1 * b) + "/" + String(2 * a) + " - " + interna2 + "/" + String(2 * a)
return {
x1, x2
}
}
else {
x1 = (((-1 * b) + interna2) / (2 * a)).toFixed(2)
x2 = (((-1 * b) - interna2) / (2 * a)).toFixed(2)
}
if (Number.parseInt(x1) < 1) {
let top = ((-1 * b) + Math.sqrt((b*b) - (4 * a * c)));
let bottom = 2 * a;
for (let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if(Number.parseInt(x1) < 0) {
x1 = "-" + String(top + "/" + bottom);
}
else {
x1 = String(top + "/" + bottom)
}
break;
}
}
}
}
if (Number.parseInt(x2) < 1) {
var top = ((-1 * b) - Math.sqrt((b*b) - (4 * a * c)));
var bottom = 2 * a;
for (let i = 2; i < 13; i++) {
while((top / i > 0) && ((bottom / i) > 0)) {
if((top % i == 0) && ((bottom % i) == 0)) {
top = top / i;
bottom = bottom / i;
}
else {
if (top < 0) {
x2 = "-" + String(top + "/" + bottom);
}
else {
x2 = String(top + "/" + bottom)
}
break;
}
}
}
}
return { x1, x2 }
}
}
} |
1b62571f75f914b47e2217b4a8a44ab9cee37ff0 | 1,757 | tsx | TypeScript | lib/richdata.tsx | Uvacoder/test-designdetails | f0d4709be16d26eb3f49e62d3529709aac44f3c8 | [
"MIT"
] | 1 | 2022-01-11T08:55:29.000Z | 2022-01-11T08:55:29.000Z | lib/richdata.tsx | Uvacoder/test-designdetails | f0d4709be16d26eb3f49e62d3529709aac44f3c8 | [
"MIT"
] | null | null | null | lib/richdata.tsx | Uvacoder/test-designdetails | f0d4709be16d26eb3f49e62d3529709aac44f3c8 | [
"MIT"
] | null | null | null | // @ts-nocheck
export function getPersonType(){
return {
"@type": "Person",
"@id": site.author.id,
"name": site.author.name,
"url": site.author.url,
"jobTitle": site.author.jobTitle,
"email": site.author.email,
"sameAs": site.author.sameAs,
"birthDate": site.author.birthDate,
"address": site.author.address,
"alumniOf": site.author.alumniOf,
"image": site.author.image,
"logo": site.author.logo,
}
}
export function getBlogPostingType(props){
const personType = getPersonType(props.site)
return {
"@type": "BlogPosting",
"headline": props.title,
"datePublished": props.date,
"dateModified": props.modified,
"author": personType,
"publisher": {
"@id": props.site.website
},
"description": props.description,
"name": props.title,
"@id": props.canonical + "#richSnippet",
"isPartOf": {
"@id": props.canonical + "#webpage"
},
"image": {
"@id": props.cover
},
"inLanguage": props.site.locale,
"mainEntityOfPage": {
"@id": props.canonical + "#main-entity"
}
}
}
export function getTechArticleType(props) {
const blogPosting = getBlogPostingType(props)
blogPosting["@type"] = "TechArticle"
if (props.proficiencyLevel){
// expected 'Beginner' or 'Expert'
blogPosting["proficiencyLevel"] = props.proficiencyLevel
} else {
console.error("TechArticle type expects proficiency level of either Beginner or Expert")
}
if (props.dependencies){
blogPosting["dependencies"] = props.dependencies
}
return
}
| 28.803279 | 96 | 0.574843 | 55 | 3 | 0 | 2 | 2 | 0 | 2 | 0 | 0 | 0 | 0 | 16.333333 | 457 | 0.010941 | 0.004376 | 0 | 0 | 0 | 0 | 0 | 0.210474 | // @ts-nocheck
export /* Example usages of 'getPersonType' are shown below:
getPersonType(props.site);
*/
function getPersonType(){
return {
"@type": "Person",
"@id": site.author.id,
"name": site.author.name,
"url": site.author.url,
"jobTitle": site.author.jobTitle,
"email": site.author.email,
"sameAs": site.author.sameAs,
"birthDate": site.author.birthDate,
"address": site.author.address,
"alumniOf": site.author.alumniOf,
"image": site.author.image,
"logo": site.author.logo,
}
}
export /* Example usages of 'getBlogPostingType' are shown below:
getBlogPostingType(props);
*/
function getBlogPostingType(props){
const personType = getPersonType(props.site)
return {
"@type": "BlogPosting",
"headline": props.title,
"datePublished": props.date,
"dateModified": props.modified,
"author": personType,
"publisher": {
"@id": props.site.website
},
"description": props.description,
"name": props.title,
"@id": props.canonical + "#richSnippet",
"isPartOf": {
"@id": props.canonical + "#webpage"
},
"image": {
"@id": props.cover
},
"inLanguage": props.site.locale,
"mainEntityOfPage": {
"@id": props.canonical + "#main-entity"
}
}
}
export function getTechArticleType(props) {
const blogPosting = getBlogPostingType(props)
blogPosting["@type"] = "TechArticle"
if (props.proficiencyLevel){
// expected 'Beginner' or 'Expert'
blogPosting["proficiencyLevel"] = props.proficiencyLevel
} else {
console.error("TechArticle type expects proficiency level of either Beginner or Expert")
}
if (props.dependencies){
blogPosting["dependencies"] = props.dependencies
}
return
}
|
1bc619aa744e9c7270b977845e299bf06bd352ba | 1,687 | ts | TypeScript | src/components/Pagination/utils.ts | SunLxy/carefree-react-native | d793b2bcf02f2c7fe4b7c4d46359fbbfc725395d | [
"MIT"
] | null | null | null | src/components/Pagination/utils.ts | SunLxy/carefree-react-native | d793b2bcf02f2c7fe4b7c4d46359fbbfc725395d | [
"MIT"
] | 1 | 2022-03-31T12:04:25.000Z | 2022-03-31T12:04:25.000Z | src/components/Pagination/utils.ts | SunLxy/carefree-react-native | d793b2bcf02f2c7fe4b7c4d46359fbbfc725395d | [
"MIT"
] | null | null | null | /**
* @description: 获取分页展示数据
* @param {number} page 当前页数
* @param {number} pageSize 每页总数
* @param {number} total 总数
* @param {number} around 当前范围展示
* @return {*}
*/
export const getShowList = (
page: number,
pageSize: number,
total: number,
around: number,
) => {
const totalSize = Math.ceil(total / pageSize)
// 确保个数对的 默认 around + 1 + 2 +2 = ?
const sumCount = around + 1 + 2 + 2
// 1. 如果总数 就是 sumCount 直接返回个数值
if (sumCount >= totalSize) {
return Array.from({ length: sumCount }).map((_, inde) => inde + 1)
}
// 距离后面多少
const next = totalSize - page
// 距离前面多少
const pre = page - 1
let sum = 0
// 1. 判断 前面距离 与 around 对比
let preDot = true // 加不加 ···
if (pre <= around) {
preDot = false
sum = sum + (around - pre) + 1
}
// 2. 判断后面距离 与 around 对比
let nextDot = true // 加不加 ···
if (next <= around) {
nextDot = false
sum = sum + (around - next) + 1
}
// 如果存在余数 则进行加数
let arounds = around + sum
// 始终取当前页的前后两个 第一个数和最后一个数
const middle: (number | string)[] = [page]
let i = 0
while (i < arounds) {
i++
if (page - i > 1) {
middle.unshift(page - i)
}
if (page + i < totalSize) {
middle.push(page + i)
}
}
if (preDot) {
if (middle[0] === 2) {
middle.unshift(1)
} else {
middle.unshift(1, '···')
}
} else {
if (middle[0] !== 1) {
middle.unshift(1)
}
}
if (nextDot) {
if (middle[middle.length - 1] === totalSize - 1) {
middle.push(totalSize)
} else {
middle.push('···', totalSize)
}
} else {
if (middle[middle.length - 1] !== totalSize) {
middle.push(totalSize)
}
}
return middle
}
| 20.083333 | 70 | 0.540012 | 60 | 2 | 0 | 6 | 11 | 0 | 0 | 0 | 6 | 0 | 0 | 27 | 627 | 0.012759 | 0.017544 | 0 | 0 | 0 | 0 | 0.315789 | 0.256896 | /**
* @description: 获取分页展示数据
* @param {number} page 当前页数
* @param {number} pageSize 每页总数
* @param {number} total 总数
* @param {number} around 当前范围展示
* @return {*}
*/
export const getShowList = (
page,
pageSize,
total,
around,
) => {
const totalSize = Math.ceil(total / pageSize)
// 确保个数对的 默认 around + 1 + 2 +2 = ?
const sumCount = around + 1 + 2 + 2
// 1. 如果总数 就是 sumCount 直接返回个数值
if (sumCount >= totalSize) {
return Array.from({ length: sumCount }).map((_, inde) => inde + 1)
}
// 距离后面多少
const next = totalSize - page
// 距离前面多少
const pre = page - 1
let sum = 0
// 1. 判断 前面距离 与 around 对比
let preDot = true // 加不加 ···
if (pre <= around) {
preDot = false
sum = sum + (around - pre) + 1
}
// 2. 判断后面距离 与 around 对比
let nextDot = true // 加不加 ···
if (next <= around) {
nextDot = false
sum = sum + (around - next) + 1
}
// 如果存在余数 则进行加数
let arounds = around + sum
// 始终取当前页的前后两个 第一个数和最后一个数
const middle = [page]
let i = 0
while (i < arounds) {
i++
if (page - i > 1) {
middle.unshift(page - i)
}
if (page + i < totalSize) {
middle.push(page + i)
}
}
if (preDot) {
if (middle[0] === 2) {
middle.unshift(1)
} else {
middle.unshift(1, '···')
}
} else {
if (middle[0] !== 1) {
middle.unshift(1)
}
}
if (nextDot) {
if (middle[middle.length - 1] === totalSize - 1) {
middle.push(totalSize)
} else {
middle.push('···', totalSize)
}
} else {
if (middle[middle.length - 1] !== totalSize) {
middle.push(totalSize)
}
}
return middle
}
|
1bdf15e64741ff92173aa49927c0b9358b078f8c | 4,047 | ts | TypeScript | src/helper/binarySearchTree.ts | cinar/indicatorts | 3d38fd7ab874b069d0671f04adb7cab8d0baea25 | [
"MIT"
] | 14 | 2022-01-10T02:55:20.000Z | 2022-03-13T09:28:56.000Z | src/helper/binarySearchTree.ts | cinar/indicatorts | 3d38fd7ab874b069d0671f04adb7cab8d0baea25 | [
"MIT"
] | 24 | 2022-01-14T05:03:26.000Z | 2022-01-29T18:37:28.000Z | src/helper/binarySearchTree.ts | cinar/indicatorts | 3d38fd7ab874b069d0671f04adb7cab8d0baea25 | [
"MIT"
] | 2 | 2022-01-28T02:09:57.000Z | 2022-02-14T18:48:18.000Z | // Copyright (c) 2022 Onur Cinar. All Rights Reserved.
// https://github.com/cinar/indicatorts
/**
* Tree node.
*/
interface TreeNode {
value: number;
left: TreeNode | null;
right: TreeNode | null;
}
/**
* Tree result info object.
*/
interface TreeNodeInfo {
node: TreeNode | null;
parent: TreeNode | null;
}
/**
* Binary search tree object.
*/
export class BinarySearchTree {
private root: TreeNode | null = null;
/**
* Inserts the given value.
* @param value numeric value.
*/
insert(value: number): void {
const node: TreeNode = {
value: value,
left: null,
right: null,
};
if (this.root === null) {
this.root = node;
return;
}
let current = this.root;
let found = false;
while (!found) {
if (node.value <= current.value) {
if (current.left === null) {
current.left = node;
found = true;
} else {
current = current.left;
}
} else {
if (current.right === null) {
current.right = node;
found = true;
} else {
current = current.right;
}
}
}
}
/**
* Removes the given value.
* @param value numeric value.
* @return value removed.
*/
remove(value: number): boolean {
const info: TreeNodeInfo = {
node: this.root,
parent: null,
};
while (info.node !== null) {
if (value === info.node.value) {
this.removeNode(info);
return true;
} else {
info.parent = info.node;
if (value < info.node.value) {
info.node = info.node.left;
} else {
info.node = info.node.right;
}
}
}
return false;
}
/**
* Min value.
* @return min value.
*/
min(): number {
const minInfo = BinarySearchTree.minNode(this.root);
if (minInfo.node === null) {
throw new Error('Tree empty');
}
return minInfo.node.value;
}
/**
* Max value.
* @return max value.
*/
max(): number {
const maxInfo = BinarySearchTree.maxNode(this.root);
if (maxInfo.node === null) {
throw new Error('Tree empty');
}
return maxInfo.node?.value;
}
/**
* Removes the node info.
* @param info node info.
*/
private removeNode(info: TreeNodeInfo) {
if (info.node === null) {
return;
}
if (info.node.left !== null && info.node.right !== null) {
const minInfo = BinarySearchTree.minNode(info.node.right);
if (minInfo.parent === null) {
minInfo.parent = info.node;
}
this.removeNode(minInfo);
if (minInfo.node !== null) {
info.node.value = minInfo.node.value;
}
} else {
let child: TreeNode | null = null;
if (info.node.left !== null) {
child = info.node.left;
} else {
child = info.node.right;
}
if (info.parent === null) {
this.root = child;
} else if (info.parent.left === info.node) {
info.parent.left = child;
} else {
info.parent.right = child;
}
}
}
/**
* Min node function returns the min node and its parent.
* @param root root node.
* @return node info.
*/
private static minNode(root: TreeNode | null): TreeNodeInfo {
const info: TreeNodeInfo = {
node: null,
parent: null,
};
if (root !== null) {
info.node = root;
while (info.node.left !== null) {
info.parent = info.node;
info.node = info.node.left;
}
}
return info;
}
/**
* Max node funection returns the mac node and its parent.
* @param root root node.
* @return node info.
*/
private static maxNode(root: TreeNode | null): TreeNodeInfo {
const info: TreeNodeInfo = {
node: null,
parent: null,
};
if (root !== null) {
info.node = root;
while (info.node.right !== null) {
info.parent = info.node;
info.node = info.node.right;
}
}
return info;
}
}
| 19.838235 | 64 | 0.533234 | 133 | 7 | 0 | 5 | 10 | 6 | 3 | 0 | 7 | 3 | 0 | 15.285714 | 1,117 | 0.010743 | 0.008953 | 0.005372 | 0.002686 | 0 | 0 | 0.25 | 0.229231 | // Copyright (c) 2022 Onur Cinar. All Rights Reserved.
// https://github.com/cinar/indicatorts
/**
* Tree node.
*/
interface TreeNode {
value;
left;
right;
}
/**
* Tree result info object.
*/
interface TreeNodeInfo {
node;
parent;
}
/**
* Binary search tree object.
*/
export class BinarySearchTree {
private root = null;
/**
* Inserts the given value.
* @param value numeric value.
*/
insert(value) {
const node = {
value: value,
left: null,
right: null,
};
if (this.root === null) {
this.root = node;
return;
}
let current = this.root;
let found = false;
while (!found) {
if (node.value <= current.value) {
if (current.left === null) {
current.left = node;
found = true;
} else {
current = current.left;
}
} else {
if (current.right === null) {
current.right = node;
found = true;
} else {
current = current.right;
}
}
}
}
/**
* Removes the given value.
* @param value numeric value.
* @return value removed.
*/
remove(value) {
const info = {
node: this.root,
parent: null,
};
while (info.node !== null) {
if (value === info.node.value) {
this.removeNode(info);
return true;
} else {
info.parent = info.node;
if (value < info.node.value) {
info.node = info.node.left;
} else {
info.node = info.node.right;
}
}
}
return false;
}
/**
* Min value.
* @return min value.
*/
min() {
const minInfo = BinarySearchTree.minNode(this.root);
if (minInfo.node === null) {
throw new Error('Tree empty');
}
return minInfo.node.value;
}
/**
* Max value.
* @return max value.
*/
max() {
const maxInfo = BinarySearchTree.maxNode(this.root);
if (maxInfo.node === null) {
throw new Error('Tree empty');
}
return maxInfo.node?.value;
}
/**
* Removes the node info.
* @param info node info.
*/
private removeNode(info) {
if (info.node === null) {
return;
}
if (info.node.left !== null && info.node.right !== null) {
const minInfo = BinarySearchTree.minNode(info.node.right);
if (minInfo.parent === null) {
minInfo.parent = info.node;
}
this.removeNode(minInfo);
if (minInfo.node !== null) {
info.node.value = minInfo.node.value;
}
} else {
let child = null;
if (info.node.left !== null) {
child = info.node.left;
} else {
child = info.node.right;
}
if (info.parent === null) {
this.root = child;
} else if (info.parent.left === info.node) {
info.parent.left = child;
} else {
info.parent.right = child;
}
}
}
/**
* Min node function returns the min node and its parent.
* @param root root node.
* @return node info.
*/
private static minNode(root) {
const info = {
node: null,
parent: null,
};
if (root !== null) {
info.node = root;
while (info.node.left !== null) {
info.parent = info.node;
info.node = info.node.left;
}
}
return info;
}
/**
* Max node funection returns the mac node and its parent.
* @param root root node.
* @return node info.
*/
private static maxNode(root) {
const info = {
node: null,
parent: null,
};
if (root !== null) {
info.node = root;
while (info.node.right !== null) {
info.parent = info.node;
info.node = info.node.right;
}
}
return info;
}
}
|
1233ab57c84802ed8e7ecc09eea6e06b0e5b9431 | 3,162 | ts | TypeScript | utils/getImageURL.ts | L4ne/dc-demostore-core | d0bb159dda3d82caee934ecbf37f58926502695b | [
"Apache-2.0"
] | 1 | 2022-03-30T07:23:36.000Z | 2022-03-30T07:23:36.000Z | utils/getImageURL.ts | L4ne/dc-demostore-core | d0bb159dda3d82caee934ecbf37f58926502695b | [
"Apache-2.0"
] | null | null | null | utils/getImageURL.ts | L4ne/dc-demostore-core | d0bb159dda3d82caee934ecbf37f58926502695b | [
"Apache-2.0"
] | 4 | 2022-03-24T14:07:32.000Z | 2022-03-31T13:32:51.000Z | export type CmsImage = {
defaultHost: string;
name: string;
endpoint: string;
};
export enum ImageFormat {
WEBP = 'webp',
JPEG = 'jpeg',
PNG = 'png',
GIF = 'gif',
DEFAULT = 'default'
}
export enum ImageScaleMode {
ASPECT_RATIO = 'aspect',
CROP = 'c',
STRETCH = 's',
TOP_LEFT = 'tl',
TOP_CENTER = 'tc',
TOP_RIGHT = 'tr',
MIDDLE_LEFT = 'ml',
MIDDLE_CENTER = 'mc',
MIDDLE_RIGHT = 'mr',
BOTTOM_LEFT = 'bl',
BOTTOM_CENTER = 'bc',
BOTTOM_RIGHT = 'br'
}
export enum ImageScaleFit {
CENTER = 'center',
POINT_OF_INTEREST = 'poi'
}
export type ImageTransformations = {
format?: ImageFormat;
seoFileName?: string;
width?: number;
height?: number;
quality?: number;
poi?: { x: number, y: number };
scaleMode?: ImageScaleMode;
scaleFit?: ImageScaleFit;
aspectRatio?: string;
upscale?: boolean;
fliph?: boolean;
flipv?: boolean;
rot?: number;
hue?: number;
sat?: number;
bri?: number;
crop?: number[];
strip?: boolean;
templates?: string[];
};
export function getImageURL(image: string | CmsImage, transformations: ImageTransformations = {}): string {
const {
seoFileName,
format,
width,
height,
poi,
scaleMode,
scaleFit,
aspectRatio,
upscale,
fliph,
flipv,
rot,
hue,
sat,
bri,
crop,
templates,
strip,
quality
} = transformations;
const getImageHost = (host: string) => {
if (host === 'i1.adis.ws') {
return 'cdn.media.amplience.net';
}
return host;
}
let url = typeof image === 'string' ? image :
`https://${getImageHost(image.defaultHost)}/i/${encodeURIComponent(image.endpoint)}/${encodeURIComponent(image.name)}`;
if (seoFileName) {
url += `/${encodeURIComponent(seoFileName)}`;
}
if (format && format !== ImageFormat.DEFAULT) {
url += `.${format}`;
}
const query: string[] = [];
const params: any = {
'w': width,
'h': height,
'sm': scaleMode,
'scaleFit': scaleFit,
'aspect': aspectRatio,
'upscale': upscale,
'fliph': fliph,
'flipv': flipv,
'rotate': rot,
'hue': hue,
'sat': sat,
'bri': bri,
'strip': strip,
'qlt': quality
};
for (let param of Object.keys(params)) {
const value = params[param];
if (value !== undefined && value !== null && value != 0) {
query.push(`${param}=${value}`);
}
}
if (poi && poi.x !== -1 && poi.y !== -1) {
query.push(`poi=${poi.x},${poi.y},0.01,0.01`);
}
if (crop && crop.length === 4 && crop.filter(x => x !== 0).length > 0) {
query.push(`crop=${crop[0]},${crop[1]},${crop[2]},${crop[3]}`);
}
if (templates) {
for (let template of templates) {
query.push(`$${template}$`);
}
}
if (query.length > 0) {
url += `?${query.join('&')}`;
}
return url;
} | 20.532468 | 127 | 0.507906 | 126 | 3 | 0 | 4 | 6 | 22 | 1 | 1 | 24 | 2 | 1 | 26 | 894 | 0.00783 | 0.006711 | 0.024609 | 0.002237 | 0.001119 | 0.028571 | 0.685714 | 0.21272 | export type CmsImage = {
defaultHost;
name;
endpoint;
};
export enum ImageFormat {
WEBP = 'webp',
JPEG = 'jpeg',
PNG = 'png',
GIF = 'gif',
DEFAULT = 'default'
}
export enum ImageScaleMode {
ASPECT_RATIO = 'aspect',
CROP = 'c',
STRETCH = 's',
TOP_LEFT = 'tl',
TOP_CENTER = 'tc',
TOP_RIGHT = 'tr',
MIDDLE_LEFT = 'ml',
MIDDLE_CENTER = 'mc',
MIDDLE_RIGHT = 'mr',
BOTTOM_LEFT = 'bl',
BOTTOM_CENTER = 'bc',
BOTTOM_RIGHT = 'br'
}
export enum ImageScaleFit {
CENTER = 'center',
POINT_OF_INTEREST = 'poi'
}
export type ImageTransformations = {
format?;
seoFileName?;
width?;
height?;
quality?;
poi?;
scaleMode?;
scaleFit?;
aspectRatio?;
upscale?;
fliph?;
flipv?;
rot?;
hue?;
sat?;
bri?;
crop?;
strip?;
templates?;
};
export function getImageURL(image, transformations = {}) {
const {
seoFileName,
format,
width,
height,
poi,
scaleMode,
scaleFit,
aspectRatio,
upscale,
fliph,
flipv,
rot,
hue,
sat,
bri,
crop,
templates,
strip,
quality
} = transformations;
/* Example usages of 'getImageHost' are shown below:
getImageHost(image.defaultHost);
*/
const getImageHost = (host) => {
if (host === 'i1.adis.ws') {
return 'cdn.media.amplience.net';
}
return host;
}
let url = typeof image === 'string' ? image :
`https://${getImageHost(image.defaultHost)}/i/${encodeURIComponent(image.endpoint)}/${encodeURIComponent(image.name)}`;
if (seoFileName) {
url += `/${encodeURIComponent(seoFileName)}`;
}
if (format && format !== ImageFormat.DEFAULT) {
url += `.${format}`;
}
const query = [];
const params = {
'w': width,
'h': height,
'sm': scaleMode,
'scaleFit': scaleFit,
'aspect': aspectRatio,
'upscale': upscale,
'fliph': fliph,
'flipv': flipv,
'rotate': rot,
'hue': hue,
'sat': sat,
'bri': bri,
'strip': strip,
'qlt': quality
};
for (let param of Object.keys(params)) {
const value = params[param];
if (value !== undefined && value !== null && value != 0) {
query.push(`${param}=${value}`);
}
}
if (poi && poi.x !== -1 && poi.y !== -1) {
query.push(`poi=${poi.x},${poi.y},0.01,0.01`);
}
if (crop && crop.length === 4 && crop.filter(x => x !== 0).length > 0) {
query.push(`crop=${crop[0]},${crop[1]},${crop[2]},${crop[3]}`);
}
if (templates) {
for (let template of templates) {
query.push(`$${template}$`);
}
}
if (query.length > 0) {
url += `?${query.join('&')}`;
}
return url;
} |
965e83a1049aa861ae1352eb63a9125c0484c287 | 7,581 | ts | TypeScript | sdk/communication/communication-common/src/identifierModels.ts | WeiJun428/azure-sdk-for-js | e825fade0eafebf20a5128ef8466acc0d2bcc496 | [
"MIT"
] | 1 | 2022-01-12T08:35:43.000Z | 2022-01-12T08:35:43.000Z | sdk/communication/communication-common/src/identifierModels.ts | WeiJun428/azure-sdk-for-js | e825fade0eafebf20a5128ef8466acc0d2bcc496 | [
"MIT"
] | null | null | null | sdk/communication/communication-common/src/identifierModels.ts | WeiJun428/azure-sdk-for-js | e825fade0eafebf20a5128ef8466acc0d2bcc496 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
* Identifies a communication participant.
*/
export type CommunicationIdentifier =
| CommunicationUserIdentifier
| PhoneNumberIdentifier
| MicrosoftTeamsUserIdentifier
| UnknownIdentifier;
/**
* An Azure Communication user.
*/
export interface CommunicationUserIdentifier {
/**
* Id of the CommunicationUser as returned from the Communication Service.
*/
communicationUserId: string;
}
/**
* A phone number.
*/
export interface PhoneNumberIdentifier {
/**
* Optional raw id of the phone number.
*/
rawId?: string;
/**
* The phone number in E.164 format.
*/
phoneNumber: string;
}
/**
* A Microsoft Teams user.
*/
export interface MicrosoftTeamsUserIdentifier {
/**
* Optional raw id of the Microsoft Teams user.
*/
rawId?: string;
/**
* Id of the Microsoft Teams user. If the user isn't anonymous, the id is the AAD object id of the user.
*/
microsoftTeamsUserId: string;
/**
* True if the user is anonymous, for example when joining a meeting with a share link. If missing, the user is not anonymous.
*/
isAnonymous?: boolean;
/**
* The cloud that the Microsoft Teams user belongs to. If missing, the cloud is "public".
*/
cloud?: "public" | "dod" | "gcch";
}
/**
* An unknown identifier that doesn't fit any of the other identifier types.
*/
export interface UnknownIdentifier {
/**
* Id of the UnknownIdentifier.
*/
id: string;
}
/**
* Tests an Identifier to determine whether it implements CommunicationUserIdentifier.
*
* @param identifier - The assumed CommunicationUserIdentifier to be tested.
*/
export const isCommunicationUserIdentifier = (
identifier: CommunicationIdentifier
): identifier is CommunicationUserIdentifier => {
return typeof (identifier as any).communicationUserId === "string";
};
/**
* Tests an Identifier to determine whether it implements PhoneNumberIdentifier.
*
* @param identifier - The assumed PhoneNumberIdentifier to be tested.
*/
export const isPhoneNumberIdentifier = (
identifier: CommunicationIdentifier
): identifier is PhoneNumberIdentifier => {
return typeof (identifier as any).phoneNumber === "string";
};
/**
* Tests an Identifier to determine whether it implements MicrosoftTeamsUserIdentifier.
*
* @param identifier - The assumed available to be tested.
*/
export const isMicrosoftTeamsUserIdentifier = (
identifier: CommunicationIdentifier
): identifier is MicrosoftTeamsUserIdentifier => {
return typeof (identifier as any).microsoftTeamsUserId === "string";
};
/**
* Tests an Identifier to determine whether it implements UnknownIdentifier.
*
* @param identifier - The assumed UnknownIdentifier to be tested.
*/
export const isUnknownIdentifier = (
identifier: CommunicationIdentifier
): identifier is UnknownIdentifier => {
return typeof (identifier as any).id === "string";
};
/**
* The CommunicationIdentifierKind is a discriminated union that adds a property `kind` to an Identifier.
*/
export type CommunicationIdentifierKind =
| CommunicationUserKind
| PhoneNumberKind
| MicrosoftTeamsUserKind
| UnknownIdentifierKind;
/**
* IdentifierKind for a CommunicationUserIdentifier.
*/
export interface CommunicationUserKind extends CommunicationUserIdentifier {
/**
* The identifier kind.
*/
kind: "communicationUser";
}
/**
* IdentifierKind for a PhoneNumberIdentifier.
*/
export interface PhoneNumberKind extends PhoneNumberIdentifier {
/**
* The identifier kind.
*/
kind: "phoneNumber";
}
/**
* IdentifierKind for a MicrosoftTeamsUserIdentifier.
*/
export interface MicrosoftTeamsUserKind extends MicrosoftTeamsUserIdentifier {
/**
* The identifier kind.
*/
kind: "microsoftTeamsUser";
}
/**
* IdentifierKind for UnknownIdentifier.
*/
export interface UnknownIdentifierKind extends UnknownIdentifier {
/**
* The identifier kind.
*/
kind: "unknown";
}
/**
* Returns the CommunicationIdentifierKind for a given CommunicationIdentifier. Returns undefined if the kind couldn't be inferred.
*
* @param identifier - The identifier whose kind is to be inferred.
*/
export const getIdentifierKind = (
identifier: CommunicationIdentifier
): CommunicationIdentifierKind => {
if (isCommunicationUserIdentifier(identifier)) {
return { ...identifier, kind: "communicationUser" };
}
if (isPhoneNumberIdentifier(identifier)) {
return { ...identifier, kind: "phoneNumber" };
}
if (isMicrosoftTeamsUserIdentifier(identifier)) {
return { ...identifier, kind: "microsoftTeamsUser" };
}
return { ...identifier, kind: "unknown" };
};
/**
* Returns the rawId for a given CommunicationIdentifier. You can use the rawId for encoding the identifier and then use it as a key in a database.
*
* @param identifier - The identifier to be translated to its rawId.
*/
export const getIdentifierRawId = (identifier: CommunicationIdentifier): string => {
const identifierKind = getIdentifierKind(identifier);
switch (identifierKind.kind) {
case "communicationUser":
return identifierKind.communicationUserId;
case "microsoftTeamsUser": {
const { microsoftTeamsUserId, rawId, cloud, isAnonymous } = identifierKind;
if (rawId) return rawId;
if (isAnonymous) return `8:teamsvisitor:${microsoftTeamsUserId}`;
switch (cloud) {
case "dod":
return `8:dod:${microsoftTeamsUserId}`;
case "gcch":
return `8:gcch:${microsoftTeamsUserId}`;
case "public":
return `8:orgid:${microsoftTeamsUserId}`;
}
return `8:orgid:${microsoftTeamsUserId}`;
}
case "phoneNumber": {
const { phoneNumber, rawId } = identifierKind;
if (rawId) return rawId;
// strip the leading +. We just assume correct E.164 format here because validation should only happen server-side, not client-side.
return `4:${phoneNumber.replace(/^\+/, "")}`;
}
case "unknown": {
return identifierKind.id;
}
}
};
/**
* Creates a CommunicationIdentifierKind from a given rawId. When storing rawIds use this function to restore the identifier that was encoded in the rawId.
*
* @param rawId - The rawId to be translated to its identifier representation.
*/
export const createIdentifierFromRawId = (rawId: string): CommunicationIdentifierKind => {
if (rawId.startsWith("4:")) {
return { kind: "phoneNumber", phoneNumber: `+${rawId.substring("4:".length)}` };
}
const segments = rawId.split(":");
if (segments.length < 3) return { kind: "unknown", id: rawId };
const prefix = `${segments[0]}:${segments[1]}:`;
const suffix = rawId.substring(prefix.length);
switch (prefix) {
case "8:teamsvisitor:":
return { kind: "microsoftTeamsUser", microsoftTeamsUserId: suffix, isAnonymous: true };
case "8:orgid:":
return {
kind: "microsoftTeamsUser",
microsoftTeamsUserId: suffix,
isAnonymous: false,
cloud: "public",
};
case "8:dod:":
return {
kind: "microsoftTeamsUser",
microsoftTeamsUserId: suffix,
isAnonymous: false,
cloud: "dod",
};
case "8:gcch:":
return {
kind: "microsoftTeamsUser",
microsoftTeamsUserId: suffix,
isAnonymous: false,
cloud: "gcch",
};
case "8:acs:":
case "8:spool:":
case "8:dod-acs:":
case "8:gcch-acs:":
return { kind: "communicationUser", communicationUserId: rawId };
}
return { kind: "unknown", id: rawId };
};
| 28.182156 | 155 | 0.692521 | 141 | 7 | 0 | 7 | 13 | 12 | 4 | 4 | 9 | 10 | 8 | 11.285714 | 1,800 | 0.007778 | 0.007222 | 0.006667 | 0.005556 | 0.004444 | 0.102564 | 0.230769 | 0.219227 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
/**
* Identifies a communication participant.
*/
export type CommunicationIdentifier =
| CommunicationUserIdentifier
| PhoneNumberIdentifier
| MicrosoftTeamsUserIdentifier
| UnknownIdentifier;
/**
* An Azure Communication user.
*/
export interface CommunicationUserIdentifier {
/**
* Id of the CommunicationUser as returned from the Communication Service.
*/
communicationUserId;
}
/**
* A phone number.
*/
export interface PhoneNumberIdentifier {
/**
* Optional raw id of the phone number.
*/
rawId?;
/**
* The phone number in E.164 format.
*/
phoneNumber;
}
/**
* A Microsoft Teams user.
*/
export interface MicrosoftTeamsUserIdentifier {
/**
* Optional raw id of the Microsoft Teams user.
*/
rawId?;
/**
* Id of the Microsoft Teams user. If the user isn't anonymous, the id is the AAD object id of the user.
*/
microsoftTeamsUserId;
/**
* True if the user is anonymous, for example when joining a meeting with a share link. If missing, the user is not anonymous.
*/
isAnonymous?;
/**
* The cloud that the Microsoft Teams user belongs to. If missing, the cloud is "public".
*/
cloud?;
}
/**
* An unknown identifier that doesn't fit any of the other identifier types.
*/
export interface UnknownIdentifier {
/**
* Id of the UnknownIdentifier.
*/
id;
}
/**
* Tests an Identifier to determine whether it implements CommunicationUserIdentifier.
*
* @param identifier - The assumed CommunicationUserIdentifier to be tested.
*/
export /* Example usages of 'isCommunicationUserIdentifier' are shown below:
isCommunicationUserIdentifier(identifier);
*/
const isCommunicationUserIdentifier = (
identifier
): identifier is CommunicationUserIdentifier => {
return typeof (identifier as any).communicationUserId === "string";
};
/**
* Tests an Identifier to determine whether it implements PhoneNumberIdentifier.
*
* @param identifier - The assumed PhoneNumberIdentifier to be tested.
*/
export /* Example usages of 'isPhoneNumberIdentifier' are shown below:
isPhoneNumberIdentifier(identifier);
*/
const isPhoneNumberIdentifier = (
identifier
): identifier is PhoneNumberIdentifier => {
return typeof (identifier as any).phoneNumber === "string";
};
/**
* Tests an Identifier to determine whether it implements MicrosoftTeamsUserIdentifier.
*
* @param identifier - The assumed available to be tested.
*/
export /* Example usages of 'isMicrosoftTeamsUserIdentifier' are shown below:
isMicrosoftTeamsUserIdentifier(identifier);
*/
const isMicrosoftTeamsUserIdentifier = (
identifier
): identifier is MicrosoftTeamsUserIdentifier => {
return typeof (identifier as any).microsoftTeamsUserId === "string";
};
/**
* Tests an Identifier to determine whether it implements UnknownIdentifier.
*
* @param identifier - The assumed UnknownIdentifier to be tested.
*/
export const isUnknownIdentifier = (
identifier
): identifier is UnknownIdentifier => {
return typeof (identifier as any).id === "string";
};
/**
* The CommunicationIdentifierKind is a discriminated union that adds a property `kind` to an Identifier.
*/
export type CommunicationIdentifierKind =
| CommunicationUserKind
| PhoneNumberKind
| MicrosoftTeamsUserKind
| UnknownIdentifierKind;
/**
* IdentifierKind for a CommunicationUserIdentifier.
*/
export interface CommunicationUserKind extends CommunicationUserIdentifier {
/**
* The identifier kind.
*/
kind;
}
/**
* IdentifierKind for a PhoneNumberIdentifier.
*/
export interface PhoneNumberKind extends PhoneNumberIdentifier {
/**
* The identifier kind.
*/
kind;
}
/**
* IdentifierKind for a MicrosoftTeamsUserIdentifier.
*/
export interface MicrosoftTeamsUserKind extends MicrosoftTeamsUserIdentifier {
/**
* The identifier kind.
*/
kind;
}
/**
* IdentifierKind for UnknownIdentifier.
*/
export interface UnknownIdentifierKind extends UnknownIdentifier {
/**
* The identifier kind.
*/
kind;
}
/**
* Returns the CommunicationIdentifierKind for a given CommunicationIdentifier. Returns undefined if the kind couldn't be inferred.
*
* @param identifier - The identifier whose kind is to be inferred.
*/
export /* Example usages of 'getIdentifierKind' are shown below:
getIdentifierKind(identifier);
*/
const getIdentifierKind = (
identifier
) => {
if (isCommunicationUserIdentifier(identifier)) {
return { ...identifier, kind: "communicationUser" };
}
if (isPhoneNumberIdentifier(identifier)) {
return { ...identifier, kind: "phoneNumber" };
}
if (isMicrosoftTeamsUserIdentifier(identifier)) {
return { ...identifier, kind: "microsoftTeamsUser" };
}
return { ...identifier, kind: "unknown" };
};
/**
* Returns the rawId for a given CommunicationIdentifier. You can use the rawId for encoding the identifier and then use it as a key in a database.
*
* @param identifier - The identifier to be translated to its rawId.
*/
export const getIdentifierRawId = (identifier) => {
const identifierKind = getIdentifierKind(identifier);
switch (identifierKind.kind) {
case "communicationUser":
return identifierKind.communicationUserId;
case "microsoftTeamsUser": {
const { microsoftTeamsUserId, rawId, cloud, isAnonymous } = identifierKind;
if (rawId) return rawId;
if (isAnonymous) return `8:teamsvisitor:${microsoftTeamsUserId}`;
switch (cloud) {
case "dod":
return `8:dod:${microsoftTeamsUserId}`;
case "gcch":
return `8:gcch:${microsoftTeamsUserId}`;
case "public":
return `8:orgid:${microsoftTeamsUserId}`;
}
return `8:orgid:${microsoftTeamsUserId}`;
}
case "phoneNumber": {
const { phoneNumber, rawId } = identifierKind;
if (rawId) return rawId;
// strip the leading +. We just assume correct E.164 format here because validation should only happen server-side, not client-side.
return `4:${phoneNumber.replace(/^\+/, "")}`;
}
case "unknown": {
return identifierKind.id;
}
}
};
/**
* Creates a CommunicationIdentifierKind from a given rawId. When storing rawIds use this function to restore the identifier that was encoded in the rawId.
*
* @param rawId - The rawId to be translated to its identifier representation.
*/
export const createIdentifierFromRawId = (rawId) => {
if (rawId.startsWith("4:")) {
return { kind: "phoneNumber", phoneNumber: `+${rawId.substring("4:".length)}` };
}
const segments = rawId.split(":");
if (segments.length < 3) return { kind: "unknown", id: rawId };
const prefix = `${segments[0]}:${segments[1]}:`;
const suffix = rawId.substring(prefix.length);
switch (prefix) {
case "8:teamsvisitor:":
return { kind: "microsoftTeamsUser", microsoftTeamsUserId: suffix, isAnonymous: true };
case "8:orgid:":
return {
kind: "microsoftTeamsUser",
microsoftTeamsUserId: suffix,
isAnonymous: false,
cloud: "public",
};
case "8:dod:":
return {
kind: "microsoftTeamsUser",
microsoftTeamsUserId: suffix,
isAnonymous: false,
cloud: "dod",
};
case "8:gcch:":
return {
kind: "microsoftTeamsUser",
microsoftTeamsUserId: suffix,
isAnonymous: false,
cloud: "gcch",
};
case "8:acs:":
case "8:spool:":
case "8:dod-acs:":
case "8:gcch-acs:":
return { kind: "communicationUser", communicationUserId: rawId };
}
return { kind: "unknown", id: rawId };
};
|
9676fd45b51b50a681254a6cc83cc97852355b0e | 3,729 | ts | TypeScript | packages/finder/src/uri.ts | jamesbohacek/schema-finder | f94f89d297a9ed48791f96fb7639eced6b8b1481 | [
"Unlicense"
] | null | null | null | packages/finder/src/uri.ts | jamesbohacek/schema-finder | f94f89d297a9ed48791f96fb7639eced6b8b1481 | [
"Unlicense"
] | 10 | 2021-12-31T08:48:36.000Z | 2022-01-10T13:44:55.000Z | packages/finder/src/uri.ts | jamesbohacek/schema-finder | f94f89d297a9ed48791f96fb7639eced6b8b1481 | [
"Unlicense"
] | null | null | null | /// https://datatracker.ietf.org/doc/html/rfc3986#section-3
///
/// URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
///
/// hier-part = "//" authority path-abempty
/// / path-absolute
/// / path-rootless
/// / path-empty
///
/// path-abempty = *( "/" segment )
/// path-absolute = "/" [ segment-nz *( "/" segment ) ]
/// path-rootless = segment-nz *( "/" segment )
/// path-empty = 0<pchar>
interface UriRef {
scheme?: string;
path: string;
authority?: string;
query?: string;
fragment?: string;
}
/**
* @see https://www.rfc-editor.org/rfc/rfc3986#appendix-B
* `://` separates scheme from authority
* `/` separates authority from path
* `?` separates path from query
* `#` separates query from fragment
*/
const uriRegex = /^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/i;
// ^^^^^^^^ ^^^^^^^ ^^^^^^ ^^^^^ ^^
// scheme authority path query fragment
/**
* Breaks down a URI into its components
* @example
* r = parseUri("http://www.ics.uci.edu/pub/ietf/uri/#Related")
* r.scheme == "http"
* r.authority == "www.ics.uci.edu"
* r.path == "/pub/ietf/uri/"
* r.query == undefined
* r.fragment == "Related"
*/
function parseUri(uri: string): UriRef {
const [, , scheme, , authority, path = "", , query, , fragment] =
uri.match(uriRegex) ?? [];
return {
scheme,
authority,
path,
query,
fragment: fragment || undefined,
};
}
/**
* Creates a target URI from a reference URI and a Base URI
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.2
* @param r Reference URI
* @param b Base URI
*/
function getTarget(r: UriRef, b: UriRef): UriRef {
if (r.scheme) return {...r, path: removeDots(r.path)};
if (r.authority) return {...r, path: removeDots(r.path), scheme: b.scheme};
if (!r.path.length) {
if (r.query) return {...b, query: r.query, fragment: r.fragment};
return {...b, fragment: r.fragment};
}
return {
...b,
path: removeDots(
r.path.startsWith("/") ? r.path : mergePaths(r.path, b.path)
),
query: r.query,
fragment: r.fragment,
};
}
/**
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.3
*/
function mergePaths(a: string, b: string): string {
if (!b.length) return "/" + a;
return b.split("/").slice(0, -1).join("/") + `/${a}`;
}
/**
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4
* FIXME: this implementation is shit and doesn't cover all abnormal test cases
*/
function removeDots(path: string): string {
const segs = path.split("/");
const result: string[] = [];
for (const s of segs) {
if (s === ".") continue;
else if (s === "..") result.pop();
else result.push(s);
}
// If the path ends with either `.` or `..` we would be missing the closing /
if (path.endsWith(".")) result.push("");
if (path.startsWith("/") && result[0]) return "/" + result.join("/");
return result.join("/");
}
/**
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.3
*/
function composeUri({
scheme,
authority,
path,
query,
fragment,
}: UriRef): string {
let result = "";
if (undefined !== scheme) result += `${scheme}:`;
if (undefined !== authority) result += `//${authority}`;
// There always has to be a path, even if empty
result += path;
if (undefined !== query) result += `?${query}`;
if (undefined !== fragment) result += `#${fragment}`;
return result;
}
export function mergeUris(base: string, ref: string): string {
const baseUri = parseUri(base);
const refUri = parseUri(ref);
return composeUri(getTarget(refUri, baseUri));
}
| 27.419118 | 80 | 0.573076 | 71 | 6 | 0 | 9 | 7 | 5 | 5 | 0 | 16 | 1 | 0 | 7.5 | 1,162 | 0.012909 | 0.006024 | 0.004303 | 0.000861 | 0 | 0 | 0.592593 | 0.22182 | /// https://datatracker.ietf.org/doc/html/rfc3986#section-3
///
/// URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
///
/// hier-part = "//" authority path-abempty
/// / path-absolute
/// / path-rootless
/// / path-empty
///
/// path-abempty = *( "/" segment )
/// path-absolute = "/" [ segment-nz *( "/" segment ) ]
/// path-rootless = segment-nz *( "/" segment )
/// path-empty = 0<pchar>
interface UriRef {
scheme?;
path;
authority?;
query?;
fragment?;
}
/**
* @see https://www.rfc-editor.org/rfc/rfc3986#appendix-B
* `://` separates scheme from authority
* `/` separates authority from path
* `?` separates path from query
* `#` separates query from fragment
*/
const uriRegex = /^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/i;
// ^^^^^^^^ ^^^^^^^ ^^^^^^ ^^^^^ ^^
// scheme authority path query fragment
/**
* Breaks down a URI into its components
* @example
* r = parseUri("http://www.ics.uci.edu/pub/ietf/uri/#Related")
* r.scheme == "http"
* r.authority == "www.ics.uci.edu"
* r.path == "/pub/ietf/uri/"
* r.query == undefined
* r.fragment == "Related"
*/
/* Example usages of 'parseUri' are shown below:
parseUri(base);
parseUri(ref);
*/
function parseUri(uri) {
const [, , scheme, , authority, path = "", , query, , fragment] =
uri.match(uriRegex) ?? [];
return {
scheme,
authority,
path,
query,
fragment: fragment || undefined,
};
}
/**
* Creates a target URI from a reference URI and a Base URI
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.2
* @param r Reference URI
* @param b Base URI
*/
/* Example usages of 'getTarget' are shown below:
composeUri(getTarget(refUri, baseUri));
*/
function getTarget(r, b) {
if (r.scheme) return {...r, path: removeDots(r.path)};
if (r.authority) return {...r, path: removeDots(r.path), scheme: b.scheme};
if (!r.path.length) {
if (r.query) return {...b, query: r.query, fragment: r.fragment};
return {...b, fragment: r.fragment};
}
return {
...b,
path: removeDots(
r.path.startsWith("/") ? r.path : mergePaths(r.path, b.path)
),
query: r.query,
fragment: r.fragment,
};
}
/**
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.3
*/
/* Example usages of 'mergePaths' are shown below:
removeDots(r.path.startsWith("/") ? r.path : mergePaths(r.path, b.path));
*/
function mergePaths(a, b) {
if (!b.length) return "/" + a;
return b.split("/").slice(0, -1).join("/") + `/${a}`;
}
/**
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4
* FIXME: this implementation is shit and doesn't cover all abnormal test cases
*/
/* Example usages of 'removeDots' are shown below:
removeDots(r.path);
removeDots(r.path.startsWith("/") ? r.path : mergePaths(r.path, b.path));
*/
function removeDots(path) {
const segs = path.split("/");
const result = [];
for (const s of segs) {
if (s === ".") continue;
else if (s === "..") result.pop();
else result.push(s);
}
// If the path ends with either `.` or `..` we would be missing the closing /
if (path.endsWith(".")) result.push("");
if (path.startsWith("/") && result[0]) return "/" + result.join("/");
return result.join("/");
}
/**
* @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.3
*/
/* Example usages of 'composeUri' are shown below:
composeUri(getTarget(refUri, baseUri));
*/
function composeUri({
scheme,
authority,
path,
query,
fragment,
}) {
let result = "";
if (undefined !== scheme) result += `${scheme}:`;
if (undefined !== authority) result += `//${authority}`;
// There always has to be a path, even if empty
result += path;
if (undefined !== query) result += `?${query}`;
if (undefined !== fragment) result += `#${fragment}`;
return result;
}
export function mergeUris(base, ref) {
const baseUri = parseUri(base);
const refUri = parseUri(ref);
return composeUri(getTarget(refUri, baseUri));
}
|
96a1903a2d01371c6441176db2536512440eefc3 | 2,432 | ts | TypeScript | lib/typescript/render/services/mediaAttachments.ts | vruksheco/airy-ek | f5d12515739bc16484b9026506464975652978a9 | [
"Apache-2.0"
] | 1 | 2022-01-22T09:39:10.000Z | 2022-01-22T09:39:10.000Z | lib/typescript/render/services/mediaAttachments.ts | LJCoopz/airy | 893e8d5dc8e724cd788df80454a7557e35bdd0b9 | [
"Apache-2.0"
] | null | null | null | lib/typescript/render/services/mediaAttachments.ts | LJCoopz/airy | 893e8d5dc8e724cd788df80454a7557e35bdd0b9 | [
"Apache-2.0"
] | null | null | null | export const attachmentsExtensions = {
//facebook
facebookImageExtensions: ['jpeg', 'jpg', 'gif', 'png', 'webp'],
facebookVideoExtensions: ['mp4', 'mov', 'wmv'],
facebookAudioExtensions: ['mp3', 'ogg', 'wav'],
facebookFileExtensions: [
'pdf',
'cvc',
'doc',
'docx',
'rtf',
'tex',
'txt',
'wpd',
'psd',
'svg',
'ico',
'json',
'md',
'mdx',
'tsx',
'jsx',
'js',
'ts',
'css',
'scss',
'html',
'bmp',
'tiff',
'tif',
],
//instagram
instagramImageExtensions: ['jpeg', 'jpg', 'png', 'ico', 'bmp'],
//twilio.whatsapp
twilioWhatsappImageExtensions: ['jpeg', 'jpg', 'png'],
twilioWhatsappVideoExtensions: ['mp4'],
twilioWhatsappAudioExtensions: ['mp3', 'ogg', 'amr'],
twilioWhatsappFileExtensions: ['pdf', 'vcf'],
//google
googleImageExtensions: ['jpeg', 'jpg', 'png'],
//chatplugin
chatpluginImageExtensions: ['jpeg', 'jpg', 'gif', 'png', 'webp', 'heic'],
chatpluginVideoExtensions: ['mp4', 'mov', 'wmv'],
chatpluginAudioExtensions: ['mp3', 'ogg', 'wav'],
chatpluginFileExtensions: [
'pdf',
'cvc',
'doc',
'docx',
'rtf',
'tex',
'txt',
'wpd',
'psd',
'svg',
'ico',
'json',
'md',
'mdx',
'tsx',
'jsx',
'js',
'ts',
'css',
'scss',
'html',
'bmp',
'tiff',
'tif',
],
};
export const getAttachmentType = (fileName: string, source: string) => {
const fileNameArr = fileName.split('.');
const fileNameExtension = fileNameArr[fileNameArr.length - 1].toLowerCase();
if (source === 'twilio.whatsapp') source = 'twilioWhatsapp';
const imageFiles = attachmentsExtensions[source + 'ImageExtensions'];
const videoFiles = attachmentsExtensions[source + 'VideoExtensions'];
const audioFiles = attachmentsExtensions[source + 'AudioExtensions'];
const docsFiles = attachmentsExtensions[source + 'FileExtensions'];
if (imageFiles && imageFiles.includes(fileNameExtension)) {
return 'image';
}
if (videoFiles && videoFiles.includes(fileNameExtension)) {
return 'video';
}
if (audioFiles && audioFiles.includes(fileNameExtension)) {
return 'audio';
}
if (docsFiles && docsFiles.includes(fileNameExtension)) {
return 'file';
}
};
export const getFileName = (fileUrl: string) => {
const fileUrlArr = fileUrl.split('/');
return fileUrlArr[fileUrlArr.length - 1].split('?')[0];
};
| 22.109091 | 78 | 0.595395 | 91 | 2 | 0 | 3 | 10 | 0 | 0 | 0 | 3 | 0 | 0 | 10.5 | 703 | 0.007112 | 0.014225 | 0 | 0 | 0 | 0 | 0.2 | 0.232901 | export const attachmentsExtensions = {
//facebook
facebookImageExtensions: ['jpeg', 'jpg', 'gif', 'png', 'webp'],
facebookVideoExtensions: ['mp4', 'mov', 'wmv'],
facebookAudioExtensions: ['mp3', 'ogg', 'wav'],
facebookFileExtensions: [
'pdf',
'cvc',
'doc',
'docx',
'rtf',
'tex',
'txt',
'wpd',
'psd',
'svg',
'ico',
'json',
'md',
'mdx',
'tsx',
'jsx',
'js',
'ts',
'css',
'scss',
'html',
'bmp',
'tiff',
'tif',
],
//instagram
instagramImageExtensions: ['jpeg', 'jpg', 'png', 'ico', 'bmp'],
//twilio.whatsapp
twilioWhatsappImageExtensions: ['jpeg', 'jpg', 'png'],
twilioWhatsappVideoExtensions: ['mp4'],
twilioWhatsappAudioExtensions: ['mp3', 'ogg', 'amr'],
twilioWhatsappFileExtensions: ['pdf', 'vcf'],
//google
googleImageExtensions: ['jpeg', 'jpg', 'png'],
//chatplugin
chatpluginImageExtensions: ['jpeg', 'jpg', 'gif', 'png', 'webp', 'heic'],
chatpluginVideoExtensions: ['mp4', 'mov', 'wmv'],
chatpluginAudioExtensions: ['mp3', 'ogg', 'wav'],
chatpluginFileExtensions: [
'pdf',
'cvc',
'doc',
'docx',
'rtf',
'tex',
'txt',
'wpd',
'psd',
'svg',
'ico',
'json',
'md',
'mdx',
'tsx',
'jsx',
'js',
'ts',
'css',
'scss',
'html',
'bmp',
'tiff',
'tif',
],
};
export const getAttachmentType = (fileName, source) => {
const fileNameArr = fileName.split('.');
const fileNameExtension = fileNameArr[fileNameArr.length - 1].toLowerCase();
if (source === 'twilio.whatsapp') source = 'twilioWhatsapp';
const imageFiles = attachmentsExtensions[source + 'ImageExtensions'];
const videoFiles = attachmentsExtensions[source + 'VideoExtensions'];
const audioFiles = attachmentsExtensions[source + 'AudioExtensions'];
const docsFiles = attachmentsExtensions[source + 'FileExtensions'];
if (imageFiles && imageFiles.includes(fileNameExtension)) {
return 'image';
}
if (videoFiles && videoFiles.includes(fileNameExtension)) {
return 'video';
}
if (audioFiles && audioFiles.includes(fileNameExtension)) {
return 'audio';
}
if (docsFiles && docsFiles.includes(fileNameExtension)) {
return 'file';
}
};
export const getFileName = (fileUrl) => {
const fileUrlArr = fileUrl.split('/');
return fileUrlArr[fileUrlArr.length - 1].split('?')[0];
};
|
8e5ec89f51cc9bd6c31d1587266359af6eeafeb3 | 2,167 | ts | TypeScript | src/GridGenerator.ts | ThijsDeR/Brogrammer-Game | 8a2280925f19f39cd8fa5a5261e87ba6a8e539a9 | [
"MIT"
] | null | null | null | src/GridGenerator.ts | ThijsDeR/Brogrammer-Game | 8a2280925f19f39cd8fa5a5261e87ba6a8e539a9 | [
"MIT"
] | 1 | 2022-01-24T09:29:48.000Z | 2022-01-24T09:29:48.000Z | src/GridGenerator.ts | ThijsDeR/Brogrammer-Game | 8a2280925f19f39cd8fa5a5261e87ba6a8e539a9 | [
"MIT"
] | null | null | null | export default abstract class GridGenerator {
/**
* @param xPos The X position of the grid
* @param yPos The Y position of the grid
* @param itemAmount The amount of items in the grid
* @param height The height of the grid
* @param itemWidth The width of the items in the grid
* @param itemHeight The height of the items in the grid
* @param paddingX The X padding of the grid
* @param paddingY The Y padding of the grid
* @returns The positions of the grid
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
public static generateGrid(
xPos: number,
yPos: number,
itemAmount: number,
height: number,
itemWidth: number,
itemHeight: number,
paddingX: number,
paddingY: number,
) {
const positions: { x: number, y: number }[] = [];
const xPositions: number[] = [];
let amountPerRow = 0;
let itemsHeight = (itemHeight + paddingY);
const i = 0;
let onNextRow = false;
while (i < itemAmount && !onNextRow) {
amountPerRow += 1;
if (itemsHeight > height) {
onNextRow = true;
} else {
itemsHeight += (itemHeight + paddingY);
}
}
let rowAmount = Math.floor(itemAmount / amountPerRow);
if (itemAmount % amountPerRow !== 0) rowAmount += 1;
if (rowAmount % 2 === 0) {
for (let a = rowAmount / 2; a > 0; a--) {
xPositions.push(xPos - (itemWidth * a) - (paddingX * a) + (itemWidth / 2));
}
for (let b = 0; b < (rowAmount / 2); b++) {
xPositions.push(xPos + (itemWidth * (b + 1)) + (paddingX * (b + 1)) - (itemWidth / 2));
}
} else {
for (let c = (rowAmount - 1) / 2; c > 0; c--) {
xPositions.push(xPos - (itemWidth * c) - (paddingX * c));
}
xPositions.push(xPos);
for (let d = 0; d < (rowAmount - 1) / 2; d++) {
xPositions.push(xPos + (itemWidth * (d + 1)) + (paddingX * (d + 1)));
}
}
xPositions.forEach((xPosition) => {
for (let e = 0; e < amountPerRow; e++) {
positions.push({ x: xPosition, y: yPos + ((itemHeight + paddingY) * e) });
}
});
return positions;
}
}
| 32.343284 | 95 | 0.573143 | 51 | 2 | 0 | 9 | 12 | 0 | 0 | 0 | 11 | 1 | 0 | 20.5 | 656 | 0.016768 | 0.018293 | 0 | 0.001524 | 0 | 0 | 0.478261 | 0.27095 | export default abstract class GridGenerator {
/**
* @param xPos The X position of the grid
* @param yPos The Y position of the grid
* @param itemAmount The amount of items in the grid
* @param height The height of the grid
* @param itemWidth The width of the items in the grid
* @param itemHeight The height of the items in the grid
* @param paddingX The X padding of the grid
* @param paddingY The Y padding of the grid
* @returns The positions of the grid
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
public static generateGrid(
xPos,
yPos,
itemAmount,
height,
itemWidth,
itemHeight,
paddingX,
paddingY,
) {
const positions = [];
const xPositions = [];
let amountPerRow = 0;
let itemsHeight = (itemHeight + paddingY);
const i = 0;
let onNextRow = false;
while (i < itemAmount && !onNextRow) {
amountPerRow += 1;
if (itemsHeight > height) {
onNextRow = true;
} else {
itemsHeight += (itemHeight + paddingY);
}
}
let rowAmount = Math.floor(itemAmount / amountPerRow);
if (itemAmount % amountPerRow !== 0) rowAmount += 1;
if (rowAmount % 2 === 0) {
for (let a = rowAmount / 2; a > 0; a--) {
xPositions.push(xPos - (itemWidth * a) - (paddingX * a) + (itemWidth / 2));
}
for (let b = 0; b < (rowAmount / 2); b++) {
xPositions.push(xPos + (itemWidth * (b + 1)) + (paddingX * (b + 1)) - (itemWidth / 2));
}
} else {
for (let c = (rowAmount - 1) / 2; c > 0; c--) {
xPositions.push(xPos - (itemWidth * c) - (paddingX * c));
}
xPositions.push(xPos);
for (let d = 0; d < (rowAmount - 1) / 2; d++) {
xPositions.push(xPos + (itemWidth * (d + 1)) + (paddingX * (d + 1)));
}
}
xPositions.forEach((xPosition) => {
for (let e = 0; e < amountPerRow; e++) {
positions.push({ x: xPosition, y: yPos + ((itemHeight + paddingY) * e) });
}
});
return positions;
}
}
|
8e941c32f2aa945858b578d2e75fccf65654ea59 | 5,699 | ts | TypeScript | jsbridge/src/libs/crypto.ts | corcd/GdyJsBridge | 8745497503fbfb10d1cc726578be71d00837a76b | [
"MIT"
] | null | null | null | jsbridge/src/libs/crypto.ts | corcd/GdyJsBridge | 8745497503fbfb10d1cc726578be71d00837a76b | [
"MIT"
] | null | null | null | jsbridge/src/libs/crypto.ts | corcd/GdyJsBridge | 8745497503fbfb10d1cc726578be71d00837a76b | [
"MIT"
] | 1 | 2022-03-25T08:23:02.000Z | 2022-03-25T08:23:02.000Z | /*
* @Author: Whzcorcd
* @Date: 2020-11-20 14:09:39
* @LastEditors: Whzcorcd
* @LastEditTime: 2020-11-23 09:44:28
* @Description: file content
*/
// @ts-nocheck
const CryptoJS =
CryptoJS ||
(function (e, m) {
var p = {},
j = (p.lib = {}),
l = function () {},
f = (j.Base = {
extend: function (a) {
l.prototype = this
var c = new l()
a && c.mixIn(a)
c.hasOwnProperty('init') ||
(c.init = function () {
c.$super.init.apply(this, arguments)
})
c.init.prototype = c
c.$super = this
return c
},
create: function () {
var a = this.extend()
a.init.apply(a, arguments)
return a
},
init: function () {},
mixIn: function (a) {
for (var c in a) a.hasOwnProperty(c) && (this[c] = a[c])
a.hasOwnProperty('toString') && (this.toString = a.toString)
},
clone: function () {
return this.init.prototype.extend(this)
},
}),
n = (j.WordArray = f.extend({
init: function (a, c) {
a = this.words = a || []
this.sigBytes = c != m ? c : 4 * a.length
},
toString: function (a) {
return (a || h).stringify(this)
},
concat: function (a) {
var c = this.words,
q = a.words,
d = this.sigBytes
a = a.sigBytes
this.clamp()
if (d % 4)
for (var b = 0; b < a; b++)
c[(d + b) >>> 2] |=
((q[b >>> 2] >>> (24 - 8 * (b % 4))) & 255) <<
(24 - 8 * ((d + b) % 4))
else if (65535 < q.length)
for (b = 0; b < a; b += 4) c[(d + b) >>> 2] = q[b >>> 2]
else c.push.apply(c, q)
this.sigBytes += a
return this
},
clamp: function () {
var a = this.words,
c = this.sigBytes
a[c >>> 2] &= 4294967295 << (32 - 8 * (c % 4))
a.length = e.ceil(c / 4)
},
clone: function () {
var a = f.clone.call(this)
a.words = this.words.slice(0)
return a
},
random: function (a) {
for (var c = [], b = 0; b < a; b += 4)
c.push((4294967296 * e.random()) | 0)
return new n.init(c, a)
},
})),
b = (p.enc = {}),
h = (b.Hex = {
stringify: function (a) {
var c = a.words
a = a.sigBytes
for (var b = [], d = 0; d < a; d++) {
var f = (c[d >>> 2] >>> (24 - 8 * (d % 4))) & 255
b.push((f >>> 4).toString(16))
b.push((f & 15).toString(16))
}
return b.join('')
},
parse: function (a) {
for (var c = a.length, b = [], d = 0; d < c; d += 2)
b[d >>> 3] |= parseInt(a.substr(d, 2), 16) << (24 - 4 * (d % 8))
return new n.init(b, c / 2)
},
}),
g = (b.Latin1 = {
stringify: function (a) {
var c = a.words
a = a.sigBytes
for (var b = [], d = 0; d < a; d++)
b.push(
String.fromCharCode((c[d >>> 2] >>> (24 - 8 * (d % 4))) & 255)
)
return b.join('')
},
parse: function (a) {
for (var c = a.length, b = [], d = 0; d < c; d++)
b[d >>> 2] |= (a.charCodeAt(d) & 255) << (24 - 8 * (d % 4))
return new n.init(b, c)
},
}),
r = (b.Utf8 = {
stringify: function (a) {
try {
return decodeURIComponent(escape(g.stringify(a)))
} catch (c) {
throw Error('Malformed UTF-8 data')
}
},
parse: function (a) {
return g.parse(unescape(encodeURIComponent(a)))
},
}),
k = (j.BufferedBlockAlgorithm = f.extend({
reset: function () {
this._data = new n.init()
this._nDataBytes = 0
},
_append: function (a) {
'string' == typeof a && (a = r.parse(a))
this._data.concat(a)
this._nDataBytes += a.sigBytes
},
_process: function (a) {
var c = this._data,
b = c.words,
d = c.sigBytes,
f = this.blockSize,
ht = d / (4 * f),
h = a ? e.ceil(ht) : e.max((ht | 0) - this._minBufferSize, 0)
a = h * f
d = e.min(4 * a, d)
if (a) {
for (var g = 0; g < a; g += f) this._doProcessBlock(b, g)
g = b.splice(0, a)
c.sigBytes -= d
}
return new n.init(g, d)
},
clone: function () {
var a = f.clone.call(this)
a._data = this._data.clone()
return a
},
_minBufferSize: 0,
}))
j.Hasher = k.extend({
cfg: f.extend(),
init: function (a) {
this.cfg = this.cfg.extend(a)
this.reset()
},
reset: function () {
k.reset.call(this)
this._doReset()
},
update: function (a) {
this._append(a)
this._process()
return this
},
finalize: function (a) {
a && this._append(a)
return this._doFinalize()
},
blockSize: 16,
_createHelper: function (a) {
return function (c, b) {
return new a.init(b).finalize(c)
}
},
_createHmacHelper: function (a) {
return function (b, f) {
return new s.HMAC.init(a, f).finalize(b)
}
},
})
var s = (p.algo = {})
return p
})(Math)
export default CryptoJS
| 28.495 | 76 | 0.405861 | 189 | 32 | 0 | 26 | 44 | 0 | 0 | 0 | 0 | 0 | 1 | 9.21875 | 1,782 | 0.032548 | 0.024691 | 0 | 0 | 0.000561 | 0 | 0 | 0.326815 | /*
* @Author: Whzcorcd
* @Date: 2020-11-20 14:09:39
* @LastEditors: Whzcorcd
* @LastEditTime: 2020-11-23 09:44:28
* @Description: file content
*/
// @ts-nocheck
const CryptoJS =
CryptoJS ||
(function (e, m) {
/* Example usages of 'p' are shown below:
var p = {};
p.lib = {};
p.enc = {};
p.algo = {};
return p;
*/
var p = {},
j = (p.lib = {}),
l = function () {},
f = (j.Base = {
extend: function (a) {
l.prototype = this
var c = new l()
a && c.mixIn(a)
c.hasOwnProperty('init') ||
(c.init = function () {
c.$super.init.apply(this, arguments)
})
c.init.prototype = c
c.$super = this
return c
},
create: function () {
var a = this.extend()
a.init.apply(a, arguments)
return a
},
init: function () {},
mixIn: function (a) {
for (var c in a) a.hasOwnProperty(c) && (this[c] = a[c])
a.hasOwnProperty('toString') && (this.toString = a.toString)
},
clone: function () {
return this.init.prototype.extend(this)
},
}),
n = (j.WordArray = f.extend({
init: function (a, c) {
a = this.words = a || []
this.sigBytes = c != m ? c : 4 * a.length
},
toString: function (a) {
return (a || h).stringify(this)
},
concat: function (a) {
var c = this.words,
q = a.words,
d = this.sigBytes
a = a.sigBytes
this.clamp()
if (d % 4)
for (var b = 0; b < a; b++)
c[(d + b) >>> 2] |=
((q[b >>> 2] >>> (24 - 8 * (b % 4))) & 255) <<
(24 - 8 * ((d + b) % 4))
else if (65535 < q.length)
for (b = 0; b < a; b += 4) c[(d + b) >>> 2] = q[b >>> 2]
else c.push.apply(c, q)
this.sigBytes += a
return this
},
clamp: function () {
var a = this.words,
c = this.sigBytes
a[c >>> 2] &= 4294967295 << (32 - 8 * (c % 4))
a.length = e.ceil(c / 4)
},
clone: function () {
var a = f.clone.call(this)
a.words = this.words.slice(0)
return a
},
random: function (a) {
for (var c = [], b = 0; b < a; b += 4)
c.push((4294967296 * e.random()) | 0)
return new n.init(c, a)
},
})),
b = (p.enc = {}),
h = (b.Hex = {
stringify: function (a) {
var c = a.words
a = a.sigBytes
for (var b = [], d = 0; d < a; d++) {
var f = (c[d >>> 2] >>> (24 - 8 * (d % 4))) & 255
b.push((f >>> 4).toString(16))
b.push((f & 15).toString(16))
}
return b.join('')
},
parse: function (a) {
for (var c = a.length, b = [], d = 0; d < c; d += 2)
b[d >>> 3] |= parseInt(a.substr(d, 2), 16) << (24 - 4 * (d % 8))
return new n.init(b, c / 2)
},
}),
g = (b.Latin1 = {
stringify: function (a) {
var c = a.words
a = a.sigBytes
for (var b = [], d = 0; d < a; d++)
b.push(
String.fromCharCode((c[d >>> 2] >>> (24 - 8 * (d % 4))) & 255)
)
return b.join('')
},
parse: function (a) {
for (var c = a.length, b = [], d = 0; d < c; d++)
b[d >>> 2] |= (a.charCodeAt(d) & 255) << (24 - 8 * (d % 4))
return new n.init(b, c)
},
}),
r = (b.Utf8 = {
stringify: function (a) {
try {
return decodeURIComponent(escape(g.stringify(a)))
} catch (c) {
throw Error('Malformed UTF-8 data')
}
},
parse: function (a) {
return g.parse(unescape(encodeURIComponent(a)))
},
}),
k = (j.BufferedBlockAlgorithm = f.extend({
reset: function () {
this._data = new n.init()
this._nDataBytes = 0
},
_append: function (a) {
'string' == typeof a && (a = r.parse(a))
this._data.concat(a)
this._nDataBytes += a.sigBytes
},
_process: function (a) {
var c = this._data,
b = c.words,
d = c.sigBytes,
f = this.blockSize,
ht = d / (4 * f),
h = a ? e.ceil(ht) : e.max((ht | 0) - this._minBufferSize, 0)
a = h * f
d = e.min(4 * a, d)
if (a) {
for (var g = 0; g < a; g += f) this._doProcessBlock(b, g)
g = b.splice(0, a)
c.sigBytes -= d
}
return new n.init(g, d)
},
clone: function () {
var a = f.clone.call(this)
a._data = this._data.clone()
return a
},
_minBufferSize: 0,
}))
j.Hasher = k.extend({
cfg: f.extend(),
init: function (a) {
this.cfg = this.cfg.extend(a)
this.reset()
},
reset: function () {
k.reset.call(this)
this._doReset()
},
update: function (a) {
this._append(a)
this._process()
return this
},
finalize: function (a) {
a && this._append(a)
return this._doFinalize()
},
blockSize: 16,
_createHelper: function (a) {
return function (c, b) {
return new a.init(b).finalize(c)
}
},
_createHmacHelper: function (a) {
return function (b, f) {
return new s.HMAC.init(a, f).finalize(b)
}
},
})
var s = (p.algo = {})
return p
})(Math)
export default CryptoJS
|
aa0b04568df03138dc24e8c7c363decf2bd5ba4f | 5,854 | ts | TypeScript | src/pipe.ts | jituanlin/curried-es-fns | 3db746b674ce961e81d9389729dec078a86cdb93 | [
"MIT"
] | 1 | 2022-02-11T09:03:52.000Z | 2022-02-11T09:03:52.000Z | src/pipe.ts | jituanlin/curried-es-fns | 3db746b674ce961e81d9389729dec078a86cdb93 | [
"MIT"
] | null | null | null | src/pipe.ts | jituanlin/curried-es-fns | 3db746b674ce961e81d9389729dec078a86cdb93 | [
"MIT"
] | null | null | null | export type Arrow<A extends any[] = any, B = any> = (...args: A) => B
export function pipe<A>(a: A): A
export function pipe<A, B>(a: A, ab: (a: A) => B): B
export function pipe<A, B, C>(a: A, ab: (a: A) => B, bc: (b: B) => C): C
export function pipe<A, B, C, D>(a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D): D
export function pipe<A, B, C, D, E>(a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => D, de: (d: D) => E): E
export function pipe<A, B, C, D, E, F>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F
): F
export function pipe<A, B, C, D, E, F, G>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G
): G
export function pipe<A, B, C, D, E, F, G, H>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H
): H
export function pipe<A, B, C, D, E, F, G, H, I>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I
): I
export function pipe<A, B, C, D, E, F, G, H, I, J>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J
): J
export function pipe<A, B, C, D, E, F, G, H, I, J, K>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K
): K
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
kl: (k: K) => L
): L
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
kl: (k: K) => L,
lm: (l: L) => M
): M
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
kl: (k: K) => L,
lm: (l: L) => M,
mn: (m: M) => N
): N
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
kl: (k: K) => L,
lm: (l: L) => M,
mn: (m: M) => N,
no: (n: N) => O
): O
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
kl: (k: K) => L,
lm: (l: L) => M,
mn: (m: M) => N,
no: (n: N) => O,
op: (o: O) => P
): P
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
kl: (k: K) => L,
lm: (l: L) => M,
mn: (m: M) => N,
no: (n: N) => O,
op: (o: O) => P,
pq: (p: P) => Q
): Q
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
kl: (k: K) => L,
lm: (l: L) => M,
mn: (m: M) => N,
no: (n: N) => O,
op: (o: O) => P,
pq: (p: P) => Q,
qr: (q: Q) => R
): R
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
kl: (k: K) => L,
lm: (l: L) => M,
mn: (m: M) => N,
no: (n: N) => O,
op: (o: O) => P,
pq: (p: P) => Q,
qr: (q: Q) => R,
rs: (r: R) => S
): S
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T>(
a: A,
ab: (a: A) => B,
bc: (b: B) => C,
cd: (c: C) => D,
de: (d: D) => E,
ef: (e: E) => F,
fg: (f: F) => G,
gh: (g: G) => H,
hi: (h: H) => I,
ij: (i: I) => J,
jk: (j: J) => K,
kl: (k: K) => L,
lm: (l: L) => M,
mn: (m: M) => N,
no: (n: N) => O,
op: (o: O) => P,
pq: (p: P) => Q,
qr: (q: Q) => R,
rs: (r: R) => S,
st: (s: S) => T
): T
export function pipe(
a: unknown,
ab?: Arrow,
bc?: Arrow,
cd?: Arrow,
de?: Arrow,
ef?: Arrow,
fg?: Arrow,
gh?: Arrow,
hi?: Arrow
): unknown {
switch (arguments.length) {
case 1:
return a
case 2:
return ab!(a)
case 3:
return bc!(ab!(a))
case 4:
return cd!(bc!(ab!(a)))
case 5:
return de!(cd!(bc!(ab!(a))))
case 6:
return ef!(de!(cd!(bc!(ab!(a)))))
case 7:
return fg!(ef!(de!(cd!(bc!(ab!(a))))))
case 8:
return gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))))
case 9:
return hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a))))))))
default:
// eslint-disable-next-line prefer-rest-params,no-case-declarations
let ret = arguments[0]
for (let i = 1; i < arguments.length; i++) {
// eslint-disable-next-line prefer-rest-params
ret = arguments[i](ret)
}
return ret
}
}
| 21.057554 | 112 | 0.354288 | 269 | 1 | 20 | 219 | 2 | 0 | 0 | 3 | 2 | 1 | 0 | 26 | 3,103 | 0.070899 | 0.000645 | 0 | 0.000322 | 0 | 0.012397 | 0.008264 | 0.338484 | export type Arrow<A extends any[] = any, B = any> = (...args) => B
export function pipe<A>(a)
export function pipe<A, B>(a, ab)
export function pipe<A, B, C>(a, ab, bc)
export function pipe<A, B, C, D>(a, ab, bc, cd)
export function pipe<A, B, C, D, E>(a, ab, bc, cd, de)
export function pipe<A, B, C, D, E, F>(
a,
ab,
bc,
cd,
de,
ef
)
export function pipe<A, B, C, D, E, F, G>(
a,
ab,
bc,
cd,
de,
ef,
fg
)
export function pipe<A, B, C, D, E, F, G, H>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh
)
export function pipe<A, B, C, D, E, F, G, H, I>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi
)
export function pipe<A, B, C, D, E, F, G, H, I, J>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij
)
export function pipe<A, B, C, D, E, F, G, H, I, J, K>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk
)
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
kl
)
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
kl,
lm
)
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
kl,
lm,
mn
)
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
kl,
lm,
mn,
no
)
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
kl,
lm,
mn,
no,
op
)
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
kl,
lm,
mn,
no,
op,
pq
)
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
kl,
lm,
mn,
no,
op,
pq,
qr
)
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
kl,
lm,
mn,
no,
op,
pq,
qr,
rs
)
export function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T>(
a,
ab,
bc,
cd,
de,
ef,
fg,
gh,
hi,
ij,
jk,
kl,
lm,
mn,
no,
op,
pq,
qr,
rs,
st
)
export function pipe(
a,
ab?,
bc?,
cd?,
de?,
ef?,
fg?,
gh?,
hi?
) {
switch (arguments.length) {
case 1:
return a
case 2:
return ab!(a)
case 3:
return bc!(ab!(a))
case 4:
return cd!(bc!(ab!(a)))
case 5:
return de!(cd!(bc!(ab!(a))))
case 6:
return ef!(de!(cd!(bc!(ab!(a)))))
case 7:
return fg!(ef!(de!(cd!(bc!(ab!(a))))))
case 8:
return gh!(fg!(ef!(de!(cd!(bc!(ab!(a)))))))
case 9:
return hi!(gh!(fg!(ef!(de!(cd!(bc!(ab!(a))))))))
default:
// eslint-disable-next-line prefer-rest-params,no-case-declarations
let ret = arguments[0]
for (let i = 1; i < arguments.length; i++) {
// eslint-disable-next-line prefer-rest-params
ret = arguments[i](ret)
}
return ret
}
}
|
aa293bb57031973f2f85bef57e390d735ba5a167 | 2,794 | ts | TypeScript | packages/unigraph-dev-explorer/src/examples/notes/noteQuery.ts | Ryunaq/unigraph-dev | e17d8f25ae209572229eb341e231305d3dbf492b | [
"MIT"
] | 1 | 2022-03-02T23:23:04.000Z | 2022-03-02T23:23:04.000Z | packages/unigraph-dev-explorer/src/examples/notes/noteQuery.ts | Ryunaq/unigraph-dev | e17d8f25ae209572229eb341e231305d3dbf492b | [
"MIT"
] | null | null | null | packages/unigraph-dev-explorer/src/examples/notes/noteQuery.ts | Ryunaq/unigraph-dev | e17d8f25ae209572229eb341e231305d3dbf492b | [
"MIT"
] | null | null | null | const MAX_DEPTH = 8;
const getQuery: (depth: number) => string = (depth: number) => {
if (depth >= MAX_DEPTH) return '{ uid _hide type {uid <unigraph.id>} }';
return `{
_updatedAt
uid
_hide
<~_value> {
type { <unigraph.id> }
<unigraph.origin> @filter(NOT eq(_hide, true)) {
type { <unigraph.id> }
uid
}
}
<unigraph.origin> @filter(NOT eq(_hide, true)) {
type { <unigraph.id> }
uid
}
type {
uid
<unigraph.id>
}
_value {
uid
text {
uid
_value {
_value {
<dgraph.type>
uid type { uid <unigraph.id> }
<_value.%>
}
uid type { uid <unigraph.id> }
}
}
name {
<_value.%>
}
content {
uid
_value {
uid
type { uid <unigraph.id> }
}
}
children {
uid
<_displayAs>
<_value[> {
uid
<_index> { uid <_value.#i> }
<_key>
<_value> @filter(uid_in(type, $unigraph.id{$/schema/subentity})) {
_hide
_value ${getQuery(depth + 1)}
uid
type { uid <unigraph.id> }
}
<_value> @filter(uid_in(type, $unigraph.id{$/schema/interface/semantic})) {
_hide
_value { uid type { uid <unigraph.id> } _stub: math(1) _value {
name { <_value.%> }
}}
uid
type { uid <unigraph.id> }
}
}
}
}
}`;
};
export const noteQueryDetailed = (uid: string, depth = 0) => `(func: uid(${uid})) ${getQuery(depth + 1)}`;
export const journalQueryDetailed = (uid: string, depth = 0) => `(func: uid(${uid})) {
_updatedAt
uid
_hide
type {
<unigraph.id>
}
_value {
note {
_value ${getQuery(depth + 1)}
}
}
}`;
export const noteQuery = (uid: string) => `(func: uid(${uid})) ${getQuery(MAX_DEPTH - 1)}`;
export const journalQuery = (uid: string) => `(func: uid(${uid})) {
_updatedAt
uid
_hide
type {
<unigraph.id>
}
_value {
note {
_value ${getQuery(MAX_DEPTH - 1)}
}
}
}`;
| 27.392157 | 106 | 0.365068 | 99 | 5 | 0 | 7 | 6 | 0 | 1 | 0 | 7 | 0 | 0 | 19.2 | 650 | 0.018462 | 0.009231 | 0 | 0 | 0 | 0 | 0.388889 | 0.243203 | const MAX_DEPTH = 8;
/* Example usages of 'getQuery' are shown below:
getQuery(depth + 1);
getQuery(MAX_DEPTH - 1);
*/
const getQuery = (depth) => {
if (depth >= MAX_DEPTH) return '{ uid _hide type {uid <unigraph.id>} }';
return `{
_updatedAt
uid
_hide
<~_value> {
type { <unigraph.id> }
<unigraph.origin> @filter(NOT eq(_hide, true)) {
type { <unigraph.id> }
uid
}
}
<unigraph.origin> @filter(NOT eq(_hide, true)) {
type { <unigraph.id> }
uid
}
type {
uid
<unigraph.id>
}
_value {
uid
text {
uid
_value {
_value {
<dgraph.type>
uid type { uid <unigraph.id> }
<_value.%>
}
uid type { uid <unigraph.id> }
}
}
name {
<_value.%>
}
content {
uid
_value {
uid
type { uid <unigraph.id> }
}
}
children {
uid
<_displayAs>
<_value[> {
uid
<_index> { uid <_value.#i> }
<_key>
<_value> @filter(uid_in(type, $unigraph.id{$/schema/subentity})) {
_hide
_value ${getQuery(depth + 1)}
uid
type { uid <unigraph.id> }
}
<_value> @filter(uid_in(type, $unigraph.id{$/schema/interface/semantic})) {
_hide
_value { uid type { uid <unigraph.id> } _stub: math(1) _value {
name { <_value.%> }
}}
uid
type { uid <unigraph.id> }
}
}
}
}
}`;
};
export const noteQueryDetailed = (uid, depth = 0) => `(func: uid(${uid})) ${getQuery(depth + 1)}`;
export const journalQueryDetailed = (uid, depth = 0) => `(func: uid(${uid})) {
_updatedAt
uid
_hide
type {
<unigraph.id>
}
_value {
note {
_value ${getQuery(depth + 1)}
}
}
}`;
export const noteQuery = (uid) => `(func: uid(${uid})) ${getQuery(MAX_DEPTH - 1)}`;
export const journalQuery = (uid) => `(func: uid(${uid})) {
_updatedAt
uid
_hide
type {
<unigraph.id>
}
_value {
note {
_value ${getQuery(MAX_DEPTH - 1)}
}
}
}`;
|
aa4b8365d89e03d5261a60ef082cbf826d4497c7 | 2,130 | ts | TypeScript | src/app/models/ontology-model-status.model.ts | os-climate/sostrades-webgui | 029dc7f13850997fb756991e98c2b6d4d837de51 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2022-03-16T08:25:41.000Z | 2022-03-16T08:25:41.000Z | src/app/models/ontology-model-status.model.ts | os-climate/sostrades-webgui | 029dc7f13850997fb756991e98c2b6d4d837de51 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | src/app/models/ontology-model-status.model.ts | os-climate/sostrades-webgui | 029dc7f13850997fb756991e98c2b6d4d837de51 | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | export class OntologyModelStatus {
constructor(
public id: string,
public name: string,
public definition: string,
public type: string,
public source: string,
public lastModificationDate: string,
public validatedBy: string,
public validated: string,
public codeRepository: string,
public icon: string,
public version: string,
public category: string,
public processesUsingModel: number,
public processesUsingModelList: {},
public inputsParametersQuantity: number,
public outputsParametersQuantity: number) {
}
public static Create(jsonData: any): OntologyModelStatus {
const result: OntologyModelStatus = new OntologyModelStatus(
jsonData[ModelStatusAttributes.ID],
jsonData[ModelStatusAttributes.NAME],
jsonData[ModelStatusAttributes.DEFINITION],
jsonData[ModelStatusAttributes.TYPE],
jsonData[ModelStatusAttributes.SOURCE],
jsonData[ModelStatusAttributes.LASTMODIFICATIONDATE],
jsonData[ModelStatusAttributes.VALIDATEDBY],
jsonData[ModelStatusAttributes.VALIDATED],
jsonData[ModelStatusAttributes.CODEREPOSITORY],
jsonData[ModelStatusAttributes.ICON],
jsonData[ModelStatusAttributes.VERSION],
jsonData[ModelStatusAttributes.CATEGORY],
jsonData[ModelStatusAttributes.PROCESSUSINGMODEL],
jsonData[ModelStatusAttributes.PROCESSUSINGMODELLIST],
jsonData[ModelStatusAttributes.INPUTSPARAMETERSQUANTITY],
jsonData[ModelStatusAttributes.OUTPUTSPARAMETERSQUANTITY]);
return result;
}
}
export enum ModelStatusAttributes {
ID = 'id',
NAME = 'name',
DEFINITION = 'definition',
TYPE = 'type',
SOURCE = 'source',
LASTMODIFICATIONDATE = 'last_modification_date',
VALIDATEDBY = 'validated_by',
VALIDATED = 'validated',
CODEREPOSITORY = 'code_repository',
ICON = 'icon',
VERSION = 'version',
CATEGORY = 'category',
PROCESSUSINGMODEL = 'processes_using_model',
PROCESSUSINGMODELLIST = 'processes_using_model_list',
INPUTSPARAMETERSQUANTITY = 'inputs_parameters_quantity',
OUTPUTSPARAMETERSQUANTITY = 'outputs_parameters_quantity'
}
| 33.809524 | 65 | 0.750704 | 58 | 2 | 0 | 17 | 1 | 0 | 0 | 1 | 15 | 1 | 0 | 9 | 480 | 0.039583 | 0.002083 | 0 | 0.002083 | 0 | 0.05 | 0.75 | 0.27109 | export class OntologyModelStatus {
constructor(
public id,
public name,
public definition,
public type,
public source,
public lastModificationDate,
public validatedBy,
public validated,
public codeRepository,
public icon,
public version,
public category,
public processesUsingModel,
public processesUsingModelList,
public inputsParametersQuantity,
public outputsParametersQuantity) {
}
public static Create(jsonData) {
const result = new OntologyModelStatus(
jsonData[ModelStatusAttributes.ID],
jsonData[ModelStatusAttributes.NAME],
jsonData[ModelStatusAttributes.DEFINITION],
jsonData[ModelStatusAttributes.TYPE],
jsonData[ModelStatusAttributes.SOURCE],
jsonData[ModelStatusAttributes.LASTMODIFICATIONDATE],
jsonData[ModelStatusAttributes.VALIDATEDBY],
jsonData[ModelStatusAttributes.VALIDATED],
jsonData[ModelStatusAttributes.CODEREPOSITORY],
jsonData[ModelStatusAttributes.ICON],
jsonData[ModelStatusAttributes.VERSION],
jsonData[ModelStatusAttributes.CATEGORY],
jsonData[ModelStatusAttributes.PROCESSUSINGMODEL],
jsonData[ModelStatusAttributes.PROCESSUSINGMODELLIST],
jsonData[ModelStatusAttributes.INPUTSPARAMETERSQUANTITY],
jsonData[ModelStatusAttributes.OUTPUTSPARAMETERSQUANTITY]);
return result;
}
}
export enum ModelStatusAttributes {
ID = 'id',
NAME = 'name',
DEFINITION = 'definition',
TYPE = 'type',
SOURCE = 'source',
LASTMODIFICATIONDATE = 'last_modification_date',
VALIDATEDBY = 'validated_by',
VALIDATED = 'validated',
CODEREPOSITORY = 'code_repository',
ICON = 'icon',
VERSION = 'version',
CATEGORY = 'category',
PROCESSUSINGMODEL = 'processes_using_model',
PROCESSUSINGMODELLIST = 'processes_using_model_list',
INPUTSPARAMETERSQUANTITY = 'inputs_parameters_quantity',
OUTPUTSPARAMETERSQUANTITY = 'outputs_parameters_quantity'
}
|
aaaa847c5b03faf0d8852f9852ddb5e36a641035 | 3,997 | ts | TypeScript | src/view/components/sidebar/inspect/parseProps.ts | bz2/preact-devtools | f80772da09c732656ee049ea4c5689790af43613 | [
"MIT"
] | null | null | null | src/view/components/sidebar/inspect/parseProps.ts | bz2/preact-devtools | f80772da09c732656ee049ea4c5689790af43613 | [
"MIT"
] | 3 | 2022-02-14T04:01:31.000Z | 2022-02-27T12:33:50.000Z | src/view/components/sidebar/inspect/parseProps.ts | isabella232/preact-devtools | 678e3a6c627538c9269e33f0f69bfa6c7c4c94e6 | [
"MIT"
] | null | null | null | export type PropDataType =
| "boolean"
| "string"
| "number"
| "array"
| "map"
| "set"
| "object"
| "null"
| "undefined"
| "function"
| "bigint"
| "vnode"
| "blob"
| "symbol";
export interface PropData {
id: string;
name: string;
type: PropDataType;
value: any;
editable: boolean;
depth: number;
meta: any;
children: string[];
}
export function parseProps(
data: any,
path: string,
limit: number,
depth = 0,
name = path,
out = new Map<string, PropData>(),
): Map<string, PropData> {
if (depth >= limit) {
out.set(path, {
depth,
name,
id: path,
type: "string",
editable: false,
value: "…",
children: [],
meta: null,
});
return out;
}
if (Array.isArray(data)) {
const children: string[] = [];
out.set(path, {
depth,
name,
id: path,
type: "array",
editable: false,
value: data,
children,
meta: null,
});
data.forEach((item, i) => {
const childPath = `${path}.${i}`;
children.push(childPath);
parseProps(item, childPath, limit, depth + 1, "" + i, out);
});
} else if (data instanceof Set) {
// TODO: We're dealing with serialized data here, not a Set object
out.set(path, {
depth,
name,
id: path,
type: "set",
editable: false,
value: "Set",
children: [],
meta: null,
});
} else if (typeof data === "object") {
if (data === null) {
out.set(path, {
depth,
name,
id: path,
type: "null",
editable: false,
value: data,
children: [],
meta: null,
});
} else {
const maybeCustom = Object.keys(data).length === 2;
// Functions are encoded as objects
if (
maybeCustom &&
typeof data.name === "string" &&
data.type === "function"
) {
out.set(path, {
depth,
name,
id: path,
type: "function",
editable: false,
value: data,
children: [],
meta: null,
});
} else if (
// Same for vnodes
maybeCustom &&
typeof data.name === "string" &&
data.type === "vnode"
) {
out.set(path, {
depth,
name,
id: path,
type: "vnode",
editable: false,
value: data,
children: [],
meta: null,
});
} else if (
// Same for Set
maybeCustom &&
typeof data.name === "string" &&
data.type === "set"
) {
out.set(path, {
depth,
name,
id: path,
type: "set",
editable: false,
value: data,
children: [],
meta: null,
});
} else if (
// Same for Map
maybeCustom &&
typeof data.name === "string" &&
data.type === "map"
) {
out.set(path, {
depth,
name,
id: path,
type: "map",
editable: false,
value: data,
children: [],
meta: null,
});
} else if (
// Same for Blobs
maybeCustom &&
typeof data.name === "string" &&
data.type === "blob"
) {
out.set(path, {
depth,
name,
id: path,
type: "blob",
editable: false,
value: data,
children: [],
meta: null,
});
} else if (
// Same for Symbols
maybeCustom &&
typeof data.name === "string" &&
data.type === "symbol"
) {
out.set(path, {
depth,
name,
id: path,
type: "symbol",
editable: false,
value: data,
children: [],
meta: null,
});
} else {
const node: PropData = {
depth,
name,
id: path,
type: "object",
editable: false,
value: data,
children: [],
meta: null,
};
out.set(path, node);
Object.keys(data).forEach(key => {
const nextPath = `${path}.${key}`;
node.children.push(nextPath);
parseProps(data[key], nextPath, limit, depth + 1, key, out);
});
out.set(path, node);
}
}
} else {
const type = typeof data;
out.set(path, {
depth,
name,
id: path,
type: type as any,
editable: type !== "undefined" && data !== "[[Circular]]",
value: data,
children: [],
meta: null,
});
}
return out;
}
| 17.60793 | 68 | 0.515387 | 213 | 3 | 0 | 9 | 6 | 8 | 1 | 4 | 10 | 2 | 10 | 61.666667 | 1,424 | 0.008427 | 0.004213 | 0.005618 | 0.001404 | 0.007022 | 0.153846 | 0.384615 | 0.202283 | export type PropDataType =
| "boolean"
| "string"
| "number"
| "array"
| "map"
| "set"
| "object"
| "null"
| "undefined"
| "function"
| "bigint"
| "vnode"
| "blob"
| "symbol";
export interface PropData {
id;
name;
type;
value;
editable;
depth;
meta;
children;
}
export /* Example usages of 'parseProps' are shown below:
parseProps(item, childPath, limit, depth + 1, "" + i, out);
parseProps(data[key], nextPath, limit, depth + 1, key, out);
*/
function parseProps(
data,
path,
limit,
depth = 0,
name = path,
out = new Map<string, PropData>(),
) {
if (depth >= limit) {
out.set(path, {
depth,
name,
id: path,
type: "string",
editable: false,
value: "…",
children: [],
meta: null,
});
return out;
}
if (Array.isArray(data)) {
const children = [];
out.set(path, {
depth,
name,
id: path,
type: "array",
editable: false,
value: data,
children,
meta: null,
});
data.forEach((item, i) => {
const childPath = `${path}.${i}`;
children.push(childPath);
parseProps(item, childPath, limit, depth + 1, "" + i, out);
});
} else if (data instanceof Set) {
// TODO: We're dealing with serialized data here, not a Set object
out.set(path, {
depth,
name,
id: path,
type: "set",
editable: false,
value: "Set",
children: [],
meta: null,
});
} else if (typeof data === "object") {
if (data === null) {
out.set(path, {
depth,
name,
id: path,
type: "null",
editable: false,
value: data,
children: [],
meta: null,
});
} else {
const maybeCustom = Object.keys(data).length === 2;
// Functions are encoded as objects
if (
maybeCustom &&
typeof data.name === "string" &&
data.type === "function"
) {
out.set(path, {
depth,
name,
id: path,
type: "function",
editable: false,
value: data,
children: [],
meta: null,
});
} else if (
// Same for vnodes
maybeCustom &&
typeof data.name === "string" &&
data.type === "vnode"
) {
out.set(path, {
depth,
name,
id: path,
type: "vnode",
editable: false,
value: data,
children: [],
meta: null,
});
} else if (
// Same for Set
maybeCustom &&
typeof data.name === "string" &&
data.type === "set"
) {
out.set(path, {
depth,
name,
id: path,
type: "set",
editable: false,
value: data,
children: [],
meta: null,
});
} else if (
// Same for Map
maybeCustom &&
typeof data.name === "string" &&
data.type === "map"
) {
out.set(path, {
depth,
name,
id: path,
type: "map",
editable: false,
value: data,
children: [],
meta: null,
});
} else if (
// Same for Blobs
maybeCustom &&
typeof data.name === "string" &&
data.type === "blob"
) {
out.set(path, {
depth,
name,
id: path,
type: "blob",
editable: false,
value: data,
children: [],
meta: null,
});
} else if (
// Same for Symbols
maybeCustom &&
typeof data.name === "string" &&
data.type === "symbol"
) {
out.set(path, {
depth,
name,
id: path,
type: "symbol",
editable: false,
value: data,
children: [],
meta: null,
});
} else {
const node = {
depth,
name,
id: path,
type: "object",
editable: false,
value: data,
children: [],
meta: null,
};
out.set(path, node);
Object.keys(data).forEach(key => {
const nextPath = `${path}.${key}`;
node.children.push(nextPath);
parseProps(data[key], nextPath, limit, depth + 1, key, out);
});
out.set(path, node);
}
}
} else {
const type = typeof data;
out.set(path, {
depth,
name,
id: path,
type: type as any,
editable: type !== "undefined" && data !== "[[Circular]]",
value: data,
children: [],
meta: null,
});
}
return out;
}
|
aaefbb78dd0623b290d8909d776a71929372ed56 | 2,475 | ts | TypeScript | packages/migrate/src/index.ts | SerenityNotes/serenity-tools | 14a185d3e90ef587323c61aedb6b947a6c568f68 | [
"MIT"
] | 9 | 2022-01-25T16:47:24.000Z | 2022-02-28T22:23:44.000Z | packages/migrate/src/index.ts | SerenityNotes/serenity-tools | 14a185d3e90ef587323c61aedb6b947a6c568f68 | [
"MIT"
] | 1 | 2022-01-23T08:06:53.000Z | 2022-01-23T08:06:53.000Z | packages/migrate/src/index.ts | SerenityNotes/serenity-tools | 14a185d3e90ef587323c61aedb6b947a6c568f68 | [
"MIT"
] | null | null | null | export type Migration = {
name: string;
statements: string[];
};
export type MigrateParams = {
db: any; // db is not defined to avoid type issues with different libs
migrations: Migration[];
};
const createMigrationsTable = `
CREATE TABLE IF NOT EXISTS "_migrations" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"migration_name" TEXT NOT NULL,
"created_at" DATETIME NOT NULL DEFAULT current_timestamp
);
`;
const insertMigration = `
INSERT INTO "_migrations" (migration_name) VALUES (:migration_name);
`;
const getLastMigration = `
SELECT * FROM "_migrations" ORDER BY "migration_name" DESC LIMIT 1;
`;
function migrationComparator(a, b) {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
}
export function migrate({ db, migrations }: MigrateParams) {
return new Promise<undefined>((resolve, reject) => {
try {
migrations.sort(migrationComparator);
db.transaction(
(tx) => {
tx.executeSql(createMigrationsTable, []);
tx.executeSql(getLastMigration, [], (_txn, res) => {
if (res.rows.length === 0) {
// apply all migrations
migrations.forEach((migration) => {
migration.statements.forEach((statement) => {
tx.executeSql(statement, []);
});
tx.executeSql(insertMigration, [migration.name]);
});
} else if (
migrations[migrations.length - 1].name ===
res.rows.item(0).migration_name
) {
// apply no migration
} else {
// identify and apply remaining migrations
const migrationsToApply = [];
migrations.forEach((migration) => {
if (migration.name > res.rows.item(0).migration_name) {
migrationsToApply.push(migration);
}
});
migrationsToApply.forEach((migration) => {
migration.statements.forEach((statement) => {
tx.executeSql(statement, []);
});
tx.executeSql(insertMigration, [migration.name]);
});
}
});
},
(error) => {
reject(error);
},
() => {
resolve(undefined);
}
);
} catch (error) {
reject(error);
}
});
}
| 27.808989 | 72 | 0.530101 | 77 | 12 | 0 | 14 | 4 | 4 | 0 | 1 | 2 | 2 | 0 | 13.583333 | 563 | 0.046181 | 0.007105 | 0.007105 | 0.003552 | 0 | 0.029412 | 0.058824 | 0.306552 | export type Migration = {
name;
statements;
};
export type MigrateParams = {
db; // db is not defined to avoid type issues with different libs
migrations;
};
const createMigrationsTable = `
CREATE TABLE IF NOT EXISTS "_migrations" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"migration_name" TEXT NOT NULL,
"created_at" DATETIME NOT NULL DEFAULT current_timestamp
);
`;
const insertMigration = `
INSERT INTO "_migrations" (migration_name) VALUES (:migration_name);
`;
const getLastMigration = `
SELECT * FROM "_migrations" ORDER BY "migration_name" DESC LIMIT 1;
`;
/* Example usages of 'migrationComparator' are shown below:
migrations.sort(migrationComparator);
*/
function migrationComparator(a, b) {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
}
export function migrate({ db, migrations }) {
return new Promise<undefined>((resolve, reject) => {
try {
migrations.sort(migrationComparator);
db.transaction(
(tx) => {
tx.executeSql(createMigrationsTable, []);
tx.executeSql(getLastMigration, [], (_txn, res) => {
if (res.rows.length === 0) {
// apply all migrations
migrations.forEach((migration) => {
migration.statements.forEach((statement) => {
tx.executeSql(statement, []);
});
tx.executeSql(insertMigration, [migration.name]);
});
} else if (
migrations[migrations.length - 1].name ===
res.rows.item(0).migration_name
) {
// apply no migration
} else {
// identify and apply remaining migrations
const migrationsToApply = [];
migrations.forEach((migration) => {
if (migration.name > res.rows.item(0).migration_name) {
migrationsToApply.push(migration);
}
});
migrationsToApply.forEach((migration) => {
migration.statements.forEach((statement) => {
tx.executeSql(statement, []);
});
tx.executeSql(insertMigration, [migration.name]);
});
}
});
},
(error) => {
reject(error);
},
() => {
resolve(undefined);
}
);
} catch (error) {
reject(error);
}
});
}
|
392107c4ffe18083285e0f2dfb3d55908e325eb9 | 2,341 | ts | TypeScript | solutions/day08.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | null | null | null | solutions/day08.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | 1 | 2022-02-03T11:04:17.000Z | 2022-02-03T11:04:17.000Z | solutions/day08.ts | GiyoMoon/aoc2021 | 83d7e9018ed3b628353bc9a0a37b70a1462ecd74 | [
"Unlicense"
] | null | null | null | export default class Day8 {
public solve(input: string): { part1: any, part2: any; } {
const entries = input.split('\n').map(e => {
e = e.replace(' | ', ' ');
const eArray = e.split(' ');
return eArray;
});
// part 1
let easyDigitCount = 0;
entries.forEach(e => {
e.slice(10).forEach(output => {
if (
output.length === 2 ||
output.length === 3 ||
output.length === 4 ||
output.length === 7
) {
easyDigitCount++;
}
});
});
// part 2
let totalValue = 0;
entries.forEach(e => {
const mapping = this._getMappingConfig(e);
const outputValue = this._getOutputValue(e.slice(10), mapping);
totalValue += outputValue;
});
return { part1: easyDigitCount, part2: totalValue };
}
private _getMappingConfig(entry: string[]) {
const mapping: string[] = new Array(10).fill('');
// get easy digits
entry.forEach(digit => {
if (digit.length === 2) {
mapping[1] = digit;
} else if (digit.length === 3) {
mapping[7] = digit;
} else if (digit.length === 4) {
mapping[4] = digit;
} else if (digit.length === 7) {
mapping[8] = digit;
}
});
entry.slice(0, 10).forEach(digit => {
// 0, 6 or 9
if (digit.length === 6) {
if (digit.split('').filter(s => mapping[1].includes(s)).length === 1) {
mapping[6] = digit;
} else if (digit.split('').filter(s => mapping[4].includes(s)).length === 3) {
mapping[0] = digit;
} else {
mapping[9] = digit;
}
// 2, 3 or 5
} else if (digit.length === 5) {
if (digit.split('').filter(s => mapping[4].includes(s)).length !== 3) {
mapping[2] = digit;
} else if (digit.split('').filter(s => mapping[1].includes(s)).length === 1) {
mapping[5] = digit;
} else {
mapping[3] = digit;
}
}
});
return mapping;
}
private _getOutputValue(outputs: string[], mapping: string[]) {
let output = '';
outputs.map(o => {
output += mapping.findIndex(m => {
return o.split('').filter(s => m.includes(s)).length === m.length && o.length === m.length;
});
});
return parseInt(output);
}
}
| 27.22093 | 99 | 0.495942 | 72 | 16 | 0 | 17 | 8 | 0 | 2 | 2 | 5 | 1 | 0 | 7.6875 | 675 | 0.048889 | 0.011852 | 0 | 0.001481 | 0 | 0.04878 | 0.121951 | 0.325157 | export default class Day8 {
public solve(input) {
const entries = input.split('\n').map(e => {
e = e.replace(' | ', ' ');
const eArray = e.split(' ');
return eArray;
});
// part 1
let easyDigitCount = 0;
entries.forEach(e => {
e.slice(10).forEach(output => {
if (
output.length === 2 ||
output.length === 3 ||
output.length === 4 ||
output.length === 7
) {
easyDigitCount++;
}
});
});
// part 2
let totalValue = 0;
entries.forEach(e => {
const mapping = this._getMappingConfig(e);
const outputValue = this._getOutputValue(e.slice(10), mapping);
totalValue += outputValue;
});
return { part1: easyDigitCount, part2: totalValue };
}
private _getMappingConfig(entry) {
const mapping = new Array(10).fill('');
// get easy digits
entry.forEach(digit => {
if (digit.length === 2) {
mapping[1] = digit;
} else if (digit.length === 3) {
mapping[7] = digit;
} else if (digit.length === 4) {
mapping[4] = digit;
} else if (digit.length === 7) {
mapping[8] = digit;
}
});
entry.slice(0, 10).forEach(digit => {
// 0, 6 or 9
if (digit.length === 6) {
if (digit.split('').filter(s => mapping[1].includes(s)).length === 1) {
mapping[6] = digit;
} else if (digit.split('').filter(s => mapping[4].includes(s)).length === 3) {
mapping[0] = digit;
} else {
mapping[9] = digit;
}
// 2, 3 or 5
} else if (digit.length === 5) {
if (digit.split('').filter(s => mapping[4].includes(s)).length !== 3) {
mapping[2] = digit;
} else if (digit.split('').filter(s => mapping[1].includes(s)).length === 1) {
mapping[5] = digit;
} else {
mapping[3] = digit;
}
}
});
return mapping;
}
private _getOutputValue(outputs, mapping) {
let output = '';
outputs.map(o => {
output += mapping.findIndex(m => {
return o.split('').filter(s => m.includes(s)).length === m.length && o.length === m.length;
});
});
return parseInt(output);
}
}
|
39346a3d0802560dcb3ed9e77063292191649903 | 1,644 | ts | TypeScript | src/sync/questions.ts | curvenote/curvenotejs | db2d442104d4921071f57f7d6fd1a6e1a076eebd | [
"MIT"
] | 1 | 2022-01-10T05:53:28.000Z | 2022-01-10T05:53:28.000Z | src/sync/questions.ts | curvenote/curvenotejs | db2d442104d4921071f57f7d6fd1a6e1a076eebd | [
"MIT"
] | 14 | 2022-01-07T03:16:32.000Z | 2022-03-30T16:49:02.000Z | src/sync/questions.ts | curvenote/curvenotejs | db2d442104d4921071f57f7d6fd1a6e1a076eebd | [
"MIT"
] | null | null | null | function title(opts: { title: string }) {
return {
name: 'title',
type: 'input',
message: 'What is the title of your curve.space site?',
default: opts.title,
};
}
function content(opts: { folderIsEmpty: boolean }) {
return {
name: 'content',
type: 'list',
message: 'What content would you like to use?',
choices: [
{
name: 'Import from Curvenote',
value: 'curvenote',
},
{
name: 'Use the content & notebooks in this folder',
value: 'folder',
disabled: opts.folderIsEmpty,
},
{
name: 'Show me some demo content!',
value: 'demo',
disabled: true,
},
],
};
}
function projectLink(opts?: { projectLink?: string }) {
return {
name: 'projectLink',
message: 'Link to Curvenote project:',
type: 'input',
default: opts?.projectLink || 'https://curvenote.com/@templates/curvespace',
};
}
function projectPath(path?: string) {
return {
name: 'projectPath',
message: 'Name of local folder to clone this project to?',
type: 'input',
default: path || '.',
};
}
function start(writeToc?: boolean) {
const tocMessage = writeToc ? 'write missing _toc.yml files and ' : '';
return {
name: 'start',
message: `Would you like to ${tocMessage}start the curve.space local server now?`,
type: 'confirm',
default: true,
};
}
function pull() {
return {
name: 'pull',
message: 'Would you like to pull content now?',
type: 'confirm',
default: true,
};
}
export default {
title,
content,
projectLink,
projectPath,
start,
pull,
};
| 20.810127 | 86 | 0.583942 | 72 | 6 | 0 | 5 | 1 | 0 | 0 | 0 | 5 | 0 | 0 | 8.666667 | 454 | 0.024229 | 0.002203 | 0 | 0 | 0 | 0 | 0.416667 | 0.233395 | /* Example usages of 'title' are shown below:
opts.title;
;
*/
function title(opts) {
return {
name: 'title',
type: 'input',
message: 'What is the title of your curve.space site?',
default: opts.title,
};
}
/* Example usages of 'content' are shown below:
;
*/
function content(opts) {
return {
name: 'content',
type: 'list',
message: 'What content would you like to use?',
choices: [
{
name: 'Import from Curvenote',
value: 'curvenote',
},
{
name: 'Use the content & notebooks in this folder',
value: 'folder',
disabled: opts.folderIsEmpty,
},
{
name: 'Show me some demo content!',
value: 'demo',
disabled: true,
},
],
};
}
/* Example usages of 'projectLink' are shown below:
opts?.projectLink || 'https://curvenote.com/@templates/curvespace';
;
*/
function projectLink(opts?) {
return {
name: 'projectLink',
message: 'Link to Curvenote project:',
type: 'input',
default: opts?.projectLink || 'https://curvenote.com/@templates/curvespace',
};
}
/* Example usages of 'projectPath' are shown below:
;
*/
function projectPath(path?) {
return {
name: 'projectPath',
message: 'Name of local folder to clone this project to?',
type: 'input',
default: path || '.',
};
}
/* Example usages of 'start' are shown below:
;
*/
function start(writeToc?) {
const tocMessage = writeToc ? 'write missing _toc.yml files and ' : '';
return {
name: 'start',
message: `Would you like to ${tocMessage}start the curve.space local server now?`,
type: 'confirm',
default: true,
};
}
/* Example usages of 'pull' are shown below:
;
*/
function pull() {
return {
name: 'pull',
message: 'Would you like to pull content now?',
type: 'confirm',
default: true,
};
}
export default {
title,
content,
projectLink,
projectPath,
start,
pull,
};
|
39850647fe41aa810255752b914cdd87b3e420dc | 2,295 | ts | TypeScript | src/models/License.ts | api-client/core | aa157d09b39efa77d49f2d425e7b37828abe0c5b | [
"Apache-2.0"
] | null | null | null | src/models/License.ts | api-client/core | aa157d09b39efa77d49f2d425e7b37828abe0c5b | [
"Apache-2.0"
] | 1 | 2022-02-14T00:01:04.000Z | 2022-02-14T00:04:07.000Z | src/models/License.ts | advanced-rest-client/core | 2efb946f786d8b46e7131c62e0011f6e090ddec3 | [
"Apache-2.0"
] | null | null | null | export const Kind = 'Core#License';
export interface ILicense {
kind: typeof Kind;
/**
* The URL to the license text.
* Only `url` or `content` can be used at a time.
*/
url?: string;
/**
* The name of the license.
*/
name?: string;
/**
* The content of the license.
* Only `url` or `content` can be used at a time.
*/
content?: string;
}
export class License {
kind = Kind;
/**
* The URL to the license text.
* Only `url` or `content` can be used at a time.
*/
url?: string;
/**
* The name of the license.
*/
name?: string;
/**
* The content of the license.
* Only `url` or `content` can be used at a time.
*/
content?: string;
static fromUrl(url: string, name?: string): License {
return new License({
kind: Kind,
url,
name,
});
}
static fromContent(content: string, name?: string): License {
return new License({
kind: Kind,
content,
name,
});
}
/**
* @param input The license definition used to restore the state.
*/
constructor(input?: string|ILicense) {
let init: ILicense;
if (typeof input === 'string') {
init = JSON.parse(input);
} else if (typeof input === 'object') {
init = input;
} else {
init = {
kind: Kind,
};
}
this.new(init);
}
/**
* Creates a new license clearing anything that is so far defined.
*
* Note, this throws an error when the license is not a license object.
*/
new(init: ILicense): void {
if (!License.isLicense(init)) {
throw new Error(`Not a license.`);
}
const { url, content, name } = init;
this.kind = Kind;
this.name = name;
this.content = content;
this.url = url;
}
/**
* Checks whether the input is a definition of a license.
*/
static isLicense(input: unknown): boolean {
const typed = input as ILicense;
if (typed && typed.kind === Kind) {
return true;
}
return false;
}
toJSON(): ILicense {
const result: ILicense = {
kind: Kind,
};
if (this.name) {
result.name = this.name;
}
if (this.url) {
result.url = this.url;
}
if (this.content) {
result.content = this.content;
}
return result;
}
}
| 20.131579 | 73 | 0.559477 | 72 | 6 | 0 | 7 | 5 | 8 | 2 | 0 | 14 | 2 | 3 | 7.833333 | 634 | 0.020505 | 0.007886 | 0.012618 | 0.003155 | 0.004732 | 0 | 0.538462 | 0.247981 | export const Kind = 'Core#License';
export interface ILicense {
kind;
/**
* The URL to the license text.
* Only `url` or `content` can be used at a time.
*/
url?;
/**
* The name of the license.
*/
name?;
/**
* The content of the license.
* Only `url` or `content` can be used at a time.
*/
content?;
}
export class License {
kind = Kind;
/**
* The URL to the license text.
* Only `url` or `content` can be used at a time.
*/
url?;
/**
* The name of the license.
*/
name?;
/**
* The content of the license.
* Only `url` or `content` can be used at a time.
*/
content?;
static fromUrl(url, name?) {
return new License({
kind: Kind,
url,
name,
});
}
static fromContent(content, name?) {
return new License({
kind: Kind,
content,
name,
});
}
/**
* @param input The license definition used to restore the state.
*/
constructor(input?) {
let init;
if (typeof input === 'string') {
init = JSON.parse(input);
} else if (typeof input === 'object') {
init = input;
} else {
init = {
kind: Kind,
};
}
this.new(init);
}
/**
* Creates a new license clearing anything that is so far defined.
*
* Note, this throws an error when the license is not a license object.
*/
new(init) {
if (!License.isLicense(init)) {
throw new Error(`Not a license.`);
}
const { url, content, name } = init;
this.kind = Kind;
this.name = name;
this.content = content;
this.url = url;
}
/**
* Checks whether the input is a definition of a license.
*/
static isLicense(input) {
const typed = input as ILicense;
if (typed && typed.kind === Kind) {
return true;
}
return false;
}
toJSON() {
const result = {
kind: Kind,
};
if (this.name) {
result.name = this.name;
}
if (this.url) {
result.url = this.url;
}
if (this.content) {
result.content = this.content;
}
return result;
}
}
|
39e9a546c0ecc8a1bf2625ac74a935aeae2252dc | 1,337 | ts | TypeScript | src/api/graphql/fundUpdate.graphql.ts | joker-crypto/PUP-Facuty-Workload | 3840e2833c5f50fbdbf9b13ae6214fbb81e8c157 | [
"MIT"
] | null | null | null | src/api/graphql/fundUpdate.graphql.ts | joker-crypto/PUP-Facuty-Workload | 3840e2833c5f50fbdbf9b13ae6214fbb81e8c157 | [
"MIT"
] | null | null | null | src/api/graphql/fundUpdate.graphql.ts | joker-crypto/PUP-Facuty-Workload | 3840e2833c5f50fbdbf9b13ae6214fbb81e8c157 | [
"MIT"
] | 1 | 2022-02-12T02:16:15.000Z | 2022-02-12T02:16:15.000Z | /* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable import/prefer-default-export */
export const listCustomerGQL = () => {
return `
query {
customers {
id
customerType
personal_info {
fullName
prefix
firstName
lastName
birthDate
email
}
investment_summary {
id
}
}
}
`;
};
export const getInvestmentSummaryGQL = (id: any) => {
return `
query {
investmentSummary(id: ${id}) {
id
accountsByCurrency {
currency
asOf
items {
acctNo
acctName
totalInvestmentAmt
currentFundValue
gainOrLossAmt
gainOrLossPercent
}
}
fundsByCurrency {
currency
items {
tag
currentValue
totalInitial
allocation
}
}
transactionHistory {
acctName
acctNo
status
transactionDetails{
trxnType
}
currentFundValue{
fundName
totalInitial
totalShares
currentNavpu
currentFundValue
}
}
}
}
`;
};
| 19.1 | 55 | 0.454749 | 66 | 2 | 0 | 1 | 2 | 0 | 0 | 1 | 0 | 0 | 0 | 31 | 254 | 0.011811 | 0.007874 | 0 | 0 | 0 | 0.2 | 0 | 0.220318 | /* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable import/prefer-default-export */
export const listCustomerGQL = () => {
return `
query {
customers {
id
customerType
personal_info {
fullName
prefix
firstName
lastName
birthDate
email
}
investment_summary {
id
}
}
}
`;
};
export const getInvestmentSummaryGQL = (id) => {
return `
query {
investmentSummary(id: ${id}) {
id
accountsByCurrency {
currency
asOf
items {
acctNo
acctName
totalInvestmentAmt
currentFundValue
gainOrLossAmt
gainOrLossPercent
}
}
fundsByCurrency {
currency
items {
tag
currentValue
totalInitial
allocation
}
}
transactionHistory {
acctName
acctNo
status
transactionDetails{
trxnType
}
currentFundValue{
fundName
totalInitial
totalShares
currentNavpu
currentFundValue
}
}
}
}
`;
};
|
977c0e7b84be38a2afba6a67437433820f63ef01 | 2,891 | ts | TypeScript | packages/decorator/src/util/flatted.ts | chriswjou/midway | b7a5c817d2316b93967367c34cff20a98b1ce4b7 | [
"MIT"
] | 1 | 2022-03-30T09:17:19.000Z | 2022-03-30T09:17:19.000Z | packages/decorator/src/util/flatted.ts | chriswjou/midway | b7a5c817d2316b93967367c34cff20a98b1ce4b7 | [
"MIT"
] | null | null | null | packages/decorator/src/util/flatted.ts | chriswjou/midway | b7a5c817d2316b93967367c34cff20a98b1ce4b7 | [
"MIT"
] | null | null | null | /**
* code fork from https://github.com/WebReflection/flatted/blob/main/cjs/index.js
*/
/*! (c) 2020 Andrea Giammarchi */
const { parse: $parse, stringify: $stringify } = JSON;
const { keys } = Object;
const Primitive = String; // it could be Number
const primitive = 'string'; // it could be 'number'
const ignore = {};
const object = 'object';
const noop = (_, value) => value;
const primitives = value =>
value instanceof Primitive ? Primitive(value) : value;
const Primitives = (_, value) =>
typeof value === primitive ? new Primitive(value) : value;
const revive = (input, parsed, output, $) => {
const lazy = [];
for (let ke = keys(output), { length } = ke, y = 0; y < length; y++) {
const k = ke[y];
const value = output[k];
if (value instanceof Primitive) {
const tmp = input[value as any];
if (typeof tmp === object && !parsed.has(tmp)) {
parsed.add(tmp);
output[k] = ignore;
lazy.push({ k, a: [input, parsed, tmp, $] });
} else output[k] = $.call(output, k, tmp);
} else if (output[k] !== ignore) output[k] = $.call(output, k, value);
}
for (let { length } = lazy, i = 0; i < length; i++) {
const { k, a } = lazy[i];
// eslint-disable-next-line prefer-spread
output[k] = $.call(output, k, revive.apply(null, a));
}
return output;
};
const set = (known, input, value) => {
const index = Primitive(input.push(value) - 1);
known.set(value, index);
return index;
};
export function safeParse(
text: string,
reviver?: (this: any, key: string, value: any) => any
): any {
const input = $parse(text, Primitives).map(primitives);
const value = input[0];
const $ = reviver || noop;
const tmp =
typeof value === object && value
? revive(input, new Set(), value, $)
: value;
return $.call({ '': tmp }, '', tmp);
}
export function safeStringify(
value: any,
replacer?: any,
space?: string | number
): string {
const $ =
replacer && typeof replacer === object
? (k, v) => (k === '' || -1 < replacer.indexOf(k) ? v : void 0)
: replacer || noop;
const known = new Map();
const input = [];
const output = [];
let i = +set(known, input, $.call({ '': value }, '', value));
let firstRun = !i;
while (i < input.length) {
firstRun = true;
output[i] = $stringify(input[i++], replace, space);
}
return '[' + output.join(',') + ']';
function replace(key, value) {
if (firstRun) {
firstRun = !firstRun;
return value;
}
const after = $.call(this, key, value);
switch (typeof after) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
case object:
if (after === null) return after;
// eslint-disable-next-line no-fallthrough
case primitive:
return known.get(after) || set(known, input, after);
}
return after;
}
}
| 28.343137 | 81 | 0.581114 | 83 | 9 | 0 | 21 | 33 | 0 | 2 | 7 | 5 | 0 | 8 | 8.111111 | 881 | 0.034052 | 0.037457 | 0 | 0 | 0.009081 | 0.111111 | 0.079365 | 0.369411 | /**
* code fork from https://github.com/WebReflection/flatted/blob/main/cjs/index.js
*/
/*! (c) 2020 Andrea Giammarchi */
const { parse: $parse, stringify: $stringify } = JSON;
const { keys } = Object;
const Primitive = String; // it could be Number
const primitive = 'string'; // it could be 'number'
const ignore = {};
const object = 'object';
/* Example usages of 'noop' are shown below:
reviver || noop;
replacer && typeof replacer === object
? (k, v) => (k === '' || -1 < replacer.indexOf(k) ? v : void 0)
: replacer || noop;
*/
const noop = (_, value) => value;
/* Example usages of 'primitives' are shown below:
$parse(text, Primitives).map(primitives);
*/
const primitives = value =>
value instanceof Primitive ? Primitive(value) : value;
/* Example usages of 'Primitives' are shown below:
$parse(text, Primitives).map(primitives);
*/
const Primitives = (_, value) =>
typeof value === primitive ? new Primitive(value) : value;
/* Example usages of 'revive' are shown below:
// eslint-disable-next-line prefer-spread
output[k] = $.call(output, k, revive.apply(null, a));
typeof value === object && value
? revive(input, new Set(), value, $)
: value;
*/
const revive = (input, parsed, output, $) => {
const lazy = [];
for (let ke = keys(output), { length } = ke, y = 0; y < length; y++) {
const k = ke[y];
const value = output[k];
if (value instanceof Primitive) {
const tmp = input[value as any];
if (typeof tmp === object && !parsed.has(tmp)) {
parsed.add(tmp);
output[k] = ignore;
lazy.push({ k, a: [input, parsed, tmp, $] });
} else output[k] = $.call(output, k, tmp);
} else if (output[k] !== ignore) output[k] = $.call(output, k, value);
}
for (let { length } = lazy, i = 0; i < length; i++) {
const { k, a } = lazy[i];
// eslint-disable-next-line prefer-spread
output[k] = $.call(output, k, revive.apply(null, a));
}
return output;
};
/* Example usages of 'set' are shown below:
known.set(value, index);
+set(known, input, $.call({ '': value }, '', value));
known.get(after) || set(known, input, after);
*/
const set = (known, input, value) => {
const index = Primitive(input.push(value) - 1);
known.set(value, index);
return index;
};
export function safeParse(
text,
reviver?
) {
const input = $parse(text, Primitives).map(primitives);
const value = input[0];
const $ = reviver || noop;
const tmp =
typeof value === object && value
? revive(input, new Set(), value, $)
: value;
return $.call({ '': tmp }, '', tmp);
}
export function safeStringify(
value,
replacer?,
space?
) {
const $ =
replacer && typeof replacer === object
? (k, v) => (k === '' || -1 < replacer.indexOf(k) ? v : void 0)
: replacer || noop;
const known = new Map();
const input = [];
const output = [];
let i = +set(known, input, $.call({ '': value }, '', value));
let firstRun = !i;
while (i < input.length) {
firstRun = true;
output[i] = $stringify(input[i++], replace, space);
}
return '[' + output.join(',') + ']';
/* Example usages of 'replace' are shown below:
output[i] = $stringify(input[i++], replace, space);
*/
function replace(key, value) {
if (firstRun) {
firstRun = !firstRun;
return value;
}
const after = $.call(this, key, value);
switch (typeof after) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
case object:
if (after === null) return after;
// eslint-disable-next-line no-fallthrough
case primitive:
return known.get(after) || set(known, input, after);
}
return after;
}
}
|
9782cdc0f2129029cfa84b5304c644b3dc445d67 | 4,863 | ts | TypeScript | src/core/ast.ts | beenotung/quick-erd | fe6a333df23dba6c2a852807cd845463719ad7fa | [
"BSD-2-Clause"
] | 1 | 2022-02-14T01:43:59.000Z | 2022-02-14T01:43:59.000Z | src/core/ast.ts | beenotung/quick-erd | fe6a333df23dba6c2a852807cd845463719ad7fa | [
"BSD-2-Clause"
] | null | null | null | src/core/ast.ts | beenotung/quick-erd | fe6a333df23dba6c2a852807cd845463719ad7fa | [
"BSD-2-Clause"
] | null | null | null | export function parse(input: string): ParseResult {
const parser = new Parser()
parser.parse(input)
return parser
}
export type ParseResult = {
table_list: Table[]
}
class Parser implements ParseResult {
table_list: Table[] = []
line_list: string[] = []
parse(input: string) {
input.split('\n').forEach(line => {
line = line
.trim()
.replace(/#.*/, '')
.replace(/\/\/.*/, '')
.trim()
if (!line) return
this.line_list.push(line)
})
this.table_list = []
while (this.hasTable()) {
this.table_list.push(this.parseTable())
}
}
peekLine(): string {
if (this.line_list.length === 0) {
throw new Error('no reminding line')
}
return this.line_list[0]
}
hasTable() {
while (this.line_list[0] === '') this.line_list.shift()
return this.line_list[0] && this.line_list[1]?.startsWith('-')
}
parseTable(): Table {
const name = this.parseName()
this.parseEmptyLine()
this.skipLine('-')
const field_list = parseAll(() => {
// skip empty lines
if (this.hasTable()) {
throw new Error('end of table')
}
return this.parseField()
})
return { name, field_list }
}
parseField(): Field {
const name = this.parseName()
let type = defaultFieldType
let is_null = false
let is_primary_key = false
let references: ForeignKeyReference | undefined
for (;;) {
const name = this.parseType()
if (!name) break
switch (name.toUpperCase()) {
case 'NULL':
is_null = true
continue
case 'PK':
is_primary_key = true
continue
case 'FK':
references = this.parseForeignKeyReference()
continue
default:
type = name
}
}
this.skipLine()
return {
name,
type,
is_null,
is_primary_key,
references,
}
}
skipLine(line = '') {
if (this.line_list[0]?.startsWith(line)) {
this.line_list.shift()
}
}
parseEmptyLine() {
const line = this.line_list[0]?.trim()
if (line !== '') {
throw new NonEmptyLineError(line)
}
this.line_list.shift()
}
parseName(): string {
let line = this.peekLine()
const match = line.match(/[a-zA-Z0-9_]+/)
if (!match) {
throw new ParseNameError(line)
}
const name = match[0]
line = line.replace(name, '').trim()
this.line_list[0] = line
return name
}
parseType(): string | undefined {
let line = this.peekLine()
const match = line.match(/[a-zA-Z0-9_(),"']+/)
if (!match) {
return
}
const name = match[0]
line = line.replace(name, '').trim()
this.line_list[0] = line
return name
}
parseRelationType(): RelationType {
let line = this.peekLine()
const match = line.match(/.* /)
if (!match) {
throw new ParseRelationTypeError(line)
}
const type = match[0].trim() as RelationType
line = line.replace(match[0], '').trim()
this.line_list[0] = line
return type
}
parseForeignKeyReference(): ForeignKeyReference {
const type = this.parseRelationType()
const table = this.parseName()
let line = this.peekLine()
if (!line.startsWith('.')) {
throw new ParseForeignKeyReferenceError(line)
}
line = line.substr(1)
this.line_list[0] = line
const field = this.parseName()
return { type, table, field }
}
}
class NonEmptyLineError extends Error {}
class LineError extends Error {
constructor(public line: string, message?: string) {
super(message)
}
}
class ParseNameError extends LineError {}
class ParseRelationTypeError extends LineError {}
class ParseForeignKeyReferenceError extends LineError {
constructor(public line: string) {
super(line, `expect '.', got '${line[0]}'`)
}
}
function parseAll<T>(fn: () => T): T[] {
const result_list: T[] = []
for (;;) {
try {
result_list.push(fn())
} catch (error) {
return result_list
}
}
}
export type Table = {
name: string
field_list: Field[]
}
export type Field = {
name: string
type: string
is_primary_key: boolean
is_null: boolean
references: ForeignKeyReference | undefined
}
export type ForeignKeyReference = {
type: RelationType
table: string
field: string
}
export type Relation = {
from: { table: string; field: string }
to: { table: string; field: string }
/*
- - one TO one
-< - one TO many
>- - many TO one
>-< - many TO many
-0 - one TO zero or one
0- - zero or one TO one
0-0 - zero or one TO zero or one
-0< - one TO zero or many
>0- - zero or many TO one
*/
type: RelationType
}
export type RelationType =
| '|'
| '-<'
| '>-'
| '>-<'
| '-0'
| '0-'
| '0-0'
| '-0<'
| '>0-'
const defaultFieldType = 'integer'
| 22.724299 | 66 | 0.583796 | 193 | 17 | 0 | 8 | 25 | 16 | 12 | 0 | 20 | 12 | 1 | 7.529412 | 1,387 | 0.018025 | 0.018025 | 0.011536 | 0.008652 | 0.000721 | 0 | 0.30303 | 0.287643 | export /* Example usages of 'parse' are shown below:
parser.parse(input);
*/
function parse(input) {
const parser = new Parser()
parser.parse(input)
return parser
}
export type ParseResult = {
table_list
}
class Parser implements ParseResult {
table_list = []
line_list = []
parse(input) {
input.split('\n').forEach(line => {
line = line
.trim()
.replace(/#.*/, '')
.replace(/\/\/.*/, '')
.trim()
if (!line) return
this.line_list.push(line)
})
this.table_list = []
while (this.hasTable()) {
this.table_list.push(this.parseTable())
}
}
peekLine() {
if (this.line_list.length === 0) {
throw new Error('no reminding line')
}
return this.line_list[0]
}
hasTable() {
while (this.line_list[0] === '') this.line_list.shift()
return this.line_list[0] && this.line_list[1]?.startsWith('-')
}
parseTable() {
const name = this.parseName()
this.parseEmptyLine()
this.skipLine('-')
const field_list = parseAll(() => {
// skip empty lines
if (this.hasTable()) {
throw new Error('end of table')
}
return this.parseField()
})
return { name, field_list }
}
parseField() {
const name = this.parseName()
let type = defaultFieldType
let is_null = false
let is_primary_key = false
let references
for (;;) {
const name = this.parseType()
if (!name) break
switch (name.toUpperCase()) {
case 'NULL':
is_null = true
continue
case 'PK':
is_primary_key = true
continue
case 'FK':
references = this.parseForeignKeyReference()
continue
default:
type = name
}
}
this.skipLine()
return {
name,
type,
is_null,
is_primary_key,
references,
}
}
skipLine(line = '') {
if (this.line_list[0]?.startsWith(line)) {
this.line_list.shift()
}
}
parseEmptyLine() {
const line = this.line_list[0]?.trim()
if (line !== '') {
throw new NonEmptyLineError(line)
}
this.line_list.shift()
}
parseName() {
let line = this.peekLine()
const match = line.match(/[a-zA-Z0-9_]+/)
if (!match) {
throw new ParseNameError(line)
}
const name = match[0]
line = line.replace(name, '').trim()
this.line_list[0] = line
return name
}
parseType() {
let line = this.peekLine()
const match = line.match(/[a-zA-Z0-9_(),"']+/)
if (!match) {
return
}
const name = match[0]
line = line.replace(name, '').trim()
this.line_list[0] = line
return name
}
parseRelationType() {
let line = this.peekLine()
const match = line.match(/.* /)
if (!match) {
throw new ParseRelationTypeError(line)
}
const type = match[0].trim() as RelationType
line = line.replace(match[0], '').trim()
this.line_list[0] = line
return type
}
parseForeignKeyReference() {
const type = this.parseRelationType()
const table = this.parseName()
let line = this.peekLine()
if (!line.startsWith('.')) {
throw new ParseForeignKeyReferenceError(line)
}
line = line.substr(1)
this.line_list[0] = line
const field = this.parseName()
return { type, table, field }
}
}
class NonEmptyLineError extends Error {}
class LineError extends Error {
constructor(public line, message?) {
super(message)
}
}
class ParseNameError extends LineError {}
class ParseRelationTypeError extends LineError {}
class ParseForeignKeyReferenceError extends LineError {
constructor(public line) {
super(line, `expect '.', got '${line[0]}'`)
}
}
/* Example usages of 'parseAll' are shown below:
parseAll(() => {
// skip empty lines
if (this.hasTable()) {
throw new Error('end of table');
}
return this.parseField();
});
*/
function parseAll<T>(fn) {
const result_list = []
for (;;) {
try {
result_list.push(fn())
} catch (error) {
return result_list
}
}
}
export type Table = {
name
field_list
}
export type Field = {
name
type
is_primary_key
is_null
references
}
export type ForeignKeyReference = {
type
table
field
}
export type Relation = {
from
to
/*
- - one TO one
-< - one TO many
>- - many TO one
>-< - many TO many
-0 - one TO zero or one
0- - zero or one TO one
0-0 - zero or one TO zero or one
-0< - one TO zero or many
>0- - zero or many TO one
*/
type
}
export type RelationType =
| '|'
| '-<'
| '>-'
| '>-<'
| '-0'
| '0-'
| '0-0'
| '-0<'
| '>0-'
const defaultFieldType = 'integer'
|
97a1f1c26fbe913c3cdd9f29a9b6063d2b7ed7f3 | 1,587 | ts | TypeScript | src/util/error/fileSystemError.ts | AsPulse/easify | 5210272b82a9e68a0cff58dcaa17857bae226f87 | [
"MIT"
] | null | null | null | src/util/error/fileSystemError.ts | AsPulse/easify | 5210272b82a9e68a0cff58dcaa17857bae226f87 | [
"MIT"
] | 16 | 2022-02-04T11:29:55.000Z | 2022-03-16T09:22:46.000Z | src/util/error/fileSystemError.ts | AsPulse/easify | 5210272b82a9e68a0cff58dcaa17857bae226f87 | [
"MIT"
] | 1 | 2022-03-27T18:07:08.000Z | 2022-03-27T18:07:08.000Z | interface IErrorCode {
code: string;
type: 'NoEntityError' | 'ExistsError' | 'Unknown';
}
interface ISerializableError {
errno: number;
code: string;
syscall: string;
path: string;
}
const isErrorSerializable = (
errorObject: unknown
): errorObject is ISerializableError => {
const error = errorObject as ISerializableError;
if (!('errno' in error)) return false;
if (!('code' in error)) return false;
if (!('syscall' in error)) return false;
if (!('path' in error)) return false;
if (typeof error.errno !== 'number') return false;
if (typeof error.code !== 'string') return false;
if (typeof error.syscall !== 'string') return false;
if (typeof error.path !== 'string') return false;
return true;
};
const errorTypes: IErrorCode[] = [
{ code: 'ENOENT', type: 'NoEntityError' },
{ code: 'EEXIST', type: 'ExistsError' },
];
export class FileSystemError {
errno: number | undefined;
code: IErrorCode;
syscall: string | undefined;
path: string | undefined;
constructor(code: string, errno?: number, syscall?: string, path?: string) {
this.errno = errno;
this.syscall = syscall;
this.path = path;
this.code = errorTypes.find(v => v.code === code) ?? {
code: code,
type: 'Unknown',
};
}
}
export function FileSystemErrorSerialize(
errorObject: unknown
): FileSystemError {
if (isErrorSerializable(errorObject)) {
return new FileSystemError(
errorObject.code,
errorObject.errno,
errorObject.syscall,
errorObject.path
);
} else {
return new FileSystemError('');
}
}
| 26.45 | 78 | 0.659105 | 57 | 4 | 0 | 7 | 3 | 10 | 1 | 0 | 14 | 3 | 5 | 7 | 440 | 0.025 | 0.006818 | 0.022727 | 0.006818 | 0.011364 | 0 | 0.583333 | 0.259609 | interface IErrorCode {
code;
type;
}
interface ISerializableError {
errno;
code;
syscall;
path;
}
/* Example usages of 'isErrorSerializable' are shown below:
isErrorSerializable(errorObject);
*/
const isErrorSerializable = (
errorObject
): errorObject is ISerializableError => {
const error = errorObject as ISerializableError;
if (!('errno' in error)) return false;
if (!('code' in error)) return false;
if (!('syscall' in error)) return false;
if (!('path' in error)) return false;
if (typeof error.errno !== 'number') return false;
if (typeof error.code !== 'string') return false;
if (typeof error.syscall !== 'string') return false;
if (typeof error.path !== 'string') return false;
return true;
};
const errorTypes = [
{ code: 'ENOENT', type: 'NoEntityError' },
{ code: 'EEXIST', type: 'ExistsError' },
];
export class FileSystemError {
errno;
code;
syscall;
path;
constructor(code, errno?, syscall?, path?) {
this.errno = errno;
this.syscall = syscall;
this.path = path;
this.code = errorTypes.find(v => v.code === code) ?? {
code: code,
type: 'Unknown',
};
}
}
export function FileSystemErrorSerialize(
errorObject
) {
if (isErrorSerializable(errorObject)) {
return new FileSystemError(
errorObject.code,
errorObject.errno,
errorObject.syscall,
errorObject.path
);
} else {
return new FileSystemError('');
}
}
|
a9368988bb1b28e197673caa727e9f263f8534a8 | 3,046 | ts | TypeScript | src/api/graphql/agent.graphql.ts | joker-crypto/PUP-Facuty-Workload | 3840e2833c5f50fbdbf9b13ae6214fbb81e8c157 | [
"MIT"
] | null | null | null | src/api/graphql/agent.graphql.ts | joker-crypto/PUP-Facuty-Workload | 3840e2833c5f50fbdbf9b13ae6214fbb81e8c157 | [
"MIT"
] | null | null | null | src/api/graphql/agent.graphql.ts | joker-crypto/PUP-Facuty-Workload | 3840e2833c5f50fbdbf9b13ae6214fbb81e8c157 | [
"MIT"
] | 1 | 2022-02-12T02:16:15.000Z | 2022-02-12T02:16:15.000Z | /* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable import/prefer-default-export */
export const listAgentsGQL = () => {
return `
query {
agents {
id
code
countCustomer
blocked
subordinates {
id
}
personalInfo {
id
position
email
fullName
mobile
}
}
}
`;
};
export const getAgentGQL = (id: number) => {
const date = new Date();
const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
return `
query {
agent(id: ${id}) {
id
code
personalInfo {
fullName
}
customers (sort: "name:asc") {
id
customerType
countAccounts
archived
blocked
personal_info {
id
fullName
email
mobile
}
accounts {
transactions(
sort: "postedAt:asc"
where: {
postedAt_gte: "${firstDay.toISOString().split('T')[0]}"
postedAt_lte: "${lastDay.toISOString().split('T')[0]}"
status_ne: ["ARCHIVED", "CANCELLED"]
}
) {
id
acctNo
trxnType
trxnSubType
trxnRateAmt
postedAt
exptGrossAmt
actlGrossAmt
actlShares
source
fund {
id
description
currency
}
}
}
}
}
}
`;
};
export const createAgentGQL = (data: any) => {
return `
mutation {
createAgent(
input: {
data: {
cisolLicenseNo: "${data.cisolLicenseNo}"
cisolLicenseDate: "${data.cisolLicenseDate.format('YYYY-MM-DD')}"
personalInfo: {
fullName: "${data.firstName} ${data.lastName}"
prefix: "${data.prefix}"
suffix: "${data.suffix}"
firstName: "${data.firstName}"
middleName: "${data.middleName || ''}"
lastName: "${data.lastName}"
birthdate: "${data.birthdate.format('YYYY-MM-DD')}"
gender: ${data.gender}
email: "${data.email}"
mobile: "${data.mobile}"
phone: "${data.phone || ''}"
position: ${data.position}
remarks: "${data.remarks || ''}"
}
}
}
) {
agent {
id
}
}
}
`;
};
export const archivedAgentGQL = (data: any) => {
return `
mutation {
updateAgent(
input: {
where: { id: ${data.id} }
data: {
archived: true
blocked: true
}
}
) {
agent {
id
}
}
}
`;
};
| 22.397059 | 77 | 0.420552 | 129 | 4 | 0 | 3 | 7 | 0 | 0 | 2 | 1 | 0 | 0 | 30.25 | 664 | 0.010542 | 0.010542 | 0 | 0 | 0 | 0.142857 | 0.071429 | 0.226881 | /* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable import/prefer-default-export */
export const listAgentsGQL = () => {
return `
query {
agents {
id
code
countCustomer
blocked
subordinates {
id
}
personalInfo {
id
position
email
fullName
mobile
}
}
}
`;
};
export const getAgentGQL = (id) => {
const date = new Date();
const firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
return `
query {
agent(id: ${id}) {
id
code
personalInfo {
fullName
}
customers (sort: "name:asc") {
id
customerType
countAccounts
archived
blocked
personal_info {
id
fullName
email
mobile
}
accounts {
transactions(
sort: "postedAt:asc"
where: {
postedAt_gte: "${firstDay.toISOString().split('T')[0]}"
postedAt_lte: "${lastDay.toISOString().split('T')[0]}"
status_ne: ["ARCHIVED", "CANCELLED"]
}
) {
id
acctNo
trxnType
trxnSubType
trxnRateAmt
postedAt
exptGrossAmt
actlGrossAmt
actlShares
source
fund {
id
description
currency
}
}
}
}
}
}
`;
};
export const createAgentGQL = (data) => {
return `
mutation {
createAgent(
input: {
data: {
cisolLicenseNo: "${data.cisolLicenseNo}"
cisolLicenseDate: "${data.cisolLicenseDate.format('YYYY-MM-DD')}"
personalInfo: {
fullName: "${data.firstName} ${data.lastName}"
prefix: "${data.prefix}"
suffix: "${data.suffix}"
firstName: "${data.firstName}"
middleName: "${data.middleName || ''}"
lastName: "${data.lastName}"
birthdate: "${data.birthdate.format('YYYY-MM-DD')}"
gender: ${data.gender}
email: "${data.email}"
mobile: "${data.mobile}"
phone: "${data.phone || ''}"
position: ${data.position}
remarks: "${data.remarks || ''}"
}
}
}
) {
agent {
id
}
}
}
`;
};
export const archivedAgentGQL = (data) => {
return `
mutation {
updateAgent(
input: {
where: { id: ${data.id} }
data: {
archived: true
blocked: true
}
}
) {
agent {
id
}
}
}
`;
};
|
a9377d6581cb1d4c2b1b49fa20d0a2770234f7bc | 2,776 | ts | TypeScript | src/adaptive-card.ts | qyon-brazil/ms-teams-notification | 143268a6648921425a4b878b7ffe9499936fb173 | [
"MIT"
] | null | null | null | src/adaptive-card.ts | qyon-brazil/ms-teams-notification | 143268a6648921425a4b878b7ffe9499936fb173 | [
"MIT"
] | null | null | null | src/adaptive-card.ts | qyon-brazil/ms-teams-notification | 143268a6648921425a4b878b7ffe9499936fb173 | [
"MIT"
] | 1 | 2022-03-01T17:47:28.000Z | 2022-03-01T17:47:28.000Z | export function createAdaptiveCard(
author: any,
authorName: string,
message: string,
prTitle: string,
prUrl: string,
prNum: string,
repoName: string,
branchTarget: string,
branchDest: string,
timestamp: string
): any {
let avatar_url =
'https://www.gravatar.com/avatar/05b6d8cc7c662bf81e01b39254f88a48?d=identicon'
if (author) {
if (author.avatar_url) {
avatar_url = author.avatar_url
}
}
const adaptiveCard = {
$schema: 'https://adaptivecards.io/schemas/adaptive-card.json',
type: 'AdaptiveCard',
version: '1.0',
body: [
{
type: 'Container',
items: [
{
type: 'TextBlock',
text: prTitle,
weight: 'bolder',
size: 'medium'
},
{
type: 'ColumnSet',
columns: [
{
type: 'Column',
width: 'auto',
items: [
{
type: 'Image',
url: avatar_url,
size: 'small',
style: 'person'
}
]
},
{
type: 'Column',
width: 'stretch',
items: [
{
type: 'TextBlock',
text: authorName,
weight: 'bolder',
wrap: true
},
{
type: 'TextBlock',
spacing: 'none',
text: 'Qyon - Time Gestão Fácil',
isSubtle: true,
wrap: true
}
]
}
]
}
]
},
{
type: 'Container',
items: [
{
type: 'TextBlock',
text: message,
wrap: true
},
{
type: 'FactSet',
facts: [
{
title: 'PR #:',
value: prNum
},
{
title: 'Repositório:',
value: repoName
},
{
title: 'Branch Origem:',
value: branchTarget
},
{
title: 'Branch Destino:',
value: branchDest
},
{
title: 'Data:',
value: timestamp
}
]
}
]
}
],
potentialAction: [
{
'@context': 'http://schema.org',
target: [`${prUrl}`],
'@type': 'ViewAction',
name: 'Visualizar Pull Request'
}
]
}
return adaptiveCard
}
| 23.133333 | 82 | 0.358069 | 118 | 1 | 0 | 10 | 2 | 0 | 0 | 2 | 9 | 0 | 0 | 105 | 599 | 0.018364 | 0.003339 | 0 | 0 | 0 | 0.153846 | 0.692308 | 0.221033 | export function createAdaptiveCard(
author,
authorName,
message,
prTitle,
prUrl,
prNum,
repoName,
branchTarget,
branchDest,
timestamp
) {
let avatar_url =
'https://www.gravatar.com/avatar/05b6d8cc7c662bf81e01b39254f88a48?d=identicon'
if (author) {
if (author.avatar_url) {
avatar_url = author.avatar_url
}
}
const adaptiveCard = {
$schema: 'https://adaptivecards.io/schemas/adaptive-card.json',
type: 'AdaptiveCard',
version: '1.0',
body: [
{
type: 'Container',
items: [
{
type: 'TextBlock',
text: prTitle,
weight: 'bolder',
size: 'medium'
},
{
type: 'ColumnSet',
columns: [
{
type: 'Column',
width: 'auto',
items: [
{
type: 'Image',
url: avatar_url,
size: 'small',
style: 'person'
}
]
},
{
type: 'Column',
width: 'stretch',
items: [
{
type: 'TextBlock',
text: authorName,
weight: 'bolder',
wrap: true
},
{
type: 'TextBlock',
spacing: 'none',
text: 'Qyon - Time Gestão Fácil',
isSubtle: true,
wrap: true
}
]
}
]
}
]
},
{
type: 'Container',
items: [
{
type: 'TextBlock',
text: message,
wrap: true
},
{
type: 'FactSet',
facts: [
{
title: 'PR #:',
value: prNum
},
{
title: 'Repositório:',
value: repoName
},
{
title: 'Branch Origem:',
value: branchTarget
},
{
title: 'Branch Destino:',
value: branchDest
},
{
title: 'Data:',
value: timestamp
}
]
}
]
}
],
potentialAction: [
{
'@context': 'http://schema.org',
target: [`${prUrl}`],
'@type': 'ViewAction',
name: 'Visualizar Pull Request'
}
]
}
return adaptiveCard
}
|
9c7b185eb474643e7ed1d3b11566888a9164266a | 2,529 | ts | TypeScript | source/client/components/EditRecipeModal/EditRecipeModal.reducer.ts | vladimir-skvortsov/recipe-app | c6705bc6ea80effeb3eed68cb0142f708e35acb4 | [
"Apache-2.0"
] | null | null | null | source/client/components/EditRecipeModal/EditRecipeModal.reducer.ts | vladimir-skvortsov/recipe-app | c6705bc6ea80effeb3eed68cb0142f708e35acb4 | [
"Apache-2.0"
] | 1 | 2022-01-27T16:06:47.000Z | 2022-01-27T16:06:47.000Z | source/client/components/EditRecipeModal/EditRecipeModal.reducer.ts | vladimir-skvortsov/recipe-app | c6705bc6ea80effeb3eed68cb0142f708e35acb4 | [
"Apache-2.0"
] | null | null | null | type Action =
| { type: 'setTags', tags: string[] }
| { type: 'closeTag', tag: string }
| { type: 'showInput' }
| { type: 'confirmInput', tag?: string }
| { type: 'reset' }
| { type: 'setIngredients', length: number }
| { type: 'addIngredient' }
| { type: 'removeIngredient', id: number }
| { type: 'addDirection' }
| { type: 'setDirections', length: number }
| { type: 'removeDirection', id: number }
interface State {
tags: string[]
inputVisible: boolean
ingredients: number[]
directions: number[]
}
let ingredientId = 0
let directionId = 0
export const initialState = {
tags: [],
inputVisible: false,
ingredients: [ingredientId],
directions: [directionId],
}
const reducer = (state: State, action: Action) => {
switch (action.type) {
case 'setTags':
return { ...state, tags: action.tags }
case 'closeTag':
return { ...state, tags: state.tags.filter(tag => tag !== action.tag) }
case 'reset':
return initialState
case 'showInput':
return { ...state, inputVisible: true }
case 'confirmInput':
let tag = action.tag
if (!tag) return { ...state, inputVisible: false }
tag = tag.trim()
const { tags } = state
let newTags = tags
if (tag && tags.indexOf(tag) === -1) newTags = [...tags, tag]
return { ...state, inputVisible: false, tags: newTags }
case 'setIngredients':
const ingredients = [] as number[]
new Array(action.length).fill(null).forEach(() => {
ingredientId += 1
ingredients.push(ingredientId)
})
return { ...state, ingredients }
case 'addIngredient':
ingredientId += 1
return {
...state,
ingredients: [...state.ingredients, ingredientId],
}
case 'removeIngredient':
return {
...state,
ingredients: state.ingredients.filter(index => index !== action.id),
}
case 'setDirections':
const directions = [] as number[]
new Array(action.length).fill(null).forEach(() => {
directionId += 1
directions.push(ingredientId)
})
return { ...state, directions }
case 'addDirection':
directionId += 1
return {
...state,
directions: [...state.directions, directionId],
}
case 'removeDirection':
return {
...state,
directions: state.directions.filter(index => index !== action.id),
}
default:
throw new Error('Unexpected action.')
}
}
export default reducer
| 25.039604 | 77 | 0.581653 | 85 | 6 | 0 | 5 | 9 | 4 | 0 | 0 | 13 | 2 | 2 | 10.5 | 648 | 0.016975 | 0.013889 | 0.006173 | 0.003086 | 0.003086 | 0 | 0.541667 | 0.25897 | type Action =
| { type, tags }
| { type, tag }
| { type }
| { type, tag? }
| { type }
| { type, length }
| { type }
| { type, id }
| { type }
| { type, length }
| { type, id }
interface State {
tags
inputVisible
ingredients
directions
}
let ingredientId = 0
let directionId = 0
export const initialState = {
tags: [],
inputVisible: false,
ingredients: [ingredientId],
directions: [directionId],
}
/* Example usages of 'reducer' are shown below:
;
*/
const reducer = (state, action) => {
switch (action.type) {
case 'setTags':
return { ...state, tags: action.tags }
case 'closeTag':
return { ...state, tags: state.tags.filter(tag => tag !== action.tag) }
case 'reset':
return initialState
case 'showInput':
return { ...state, inputVisible: true }
case 'confirmInput':
let tag = action.tag
if (!tag) return { ...state, inputVisible: false }
tag = tag.trim()
const { tags } = state
let newTags = tags
if (tag && tags.indexOf(tag) === -1) newTags = [...tags, tag]
return { ...state, inputVisible: false, tags: newTags }
case 'setIngredients':
const ingredients = [] as number[]
new Array(action.length).fill(null).forEach(() => {
ingredientId += 1
ingredients.push(ingredientId)
})
return { ...state, ingredients }
case 'addIngredient':
ingredientId += 1
return {
...state,
ingredients: [...state.ingredients, ingredientId],
}
case 'removeIngredient':
return {
...state,
ingredients: state.ingredients.filter(index => index !== action.id),
}
case 'setDirections':
const directions = [] as number[]
new Array(action.length).fill(null).forEach(() => {
directionId += 1
directions.push(ingredientId)
})
return { ...state, directions }
case 'addDirection':
directionId += 1
return {
...state,
directions: [...state.directions, directionId],
}
case 'removeDirection':
return {
...state,
directions: state.directions.filter(index => index !== action.id),
}
default:
throw new Error('Unexpected action.')
}
}
export default reducer
|
e77a2585e415d6254b456e714e449845e12fb7e2 | 2,358 | ts | TypeScript | src/path.ts | nuintun/react-nest-router | dc6ebde6b3e3df2b6d91b6620734ee88e9df458f | [
"MIT"
] | 3 | 2022-03-18T06:33:57.000Z | 2022-03-18T09:47:56.000Z | src/path.ts | nuintun/react-nest-router | dc6ebde6b3e3df2b6d91b6620734ee88e9df458f | [
"MIT"
] | null | null | null | src/path.ts | nuintun/react-nest-router | dc6ebde6b3e3df2b6d91b6620734ee88e9df458f | [
"MIT"
] | null | null | null | /**
* @module path
*/
/**
* @function isAbsolute
* @description Check if the path is absolute.
* @param path The path to check.
*/
export function isAbsolute(path: string): boolean {
return /^\//.test(path);
}
/**
* @function normalize
* @description Normalize the path.
* @param path The path to normalize.
*/
export function normalize(path: string) {
const segments: string[] = [];
const parts = path.replace(/\\+|\/{2,}/, '/').split('/');
for (const segment of parts) {
switch (segment) {
case '.':
break;
case '..':
const { length } = segments;
if (length && segments[length - 1] !== '..') {
segments.pop();
}
break;
default:
segments.push(segment);
break;
}
}
return segments.join('/') || '/';
}
/**
* @function join
* @description Join the path.
* @param base The base path.
* @param path The path to join.
*/
export function join(base: string, path: string): string {
if (!base) {
return normalize(path);
}
return normalize(base + '/' + path);
}
/**
* @function resolve
* @description Resolve the path.
* @param from The path to start.
* @param to The path to end.
*/
export function resolve(from: string, to?: string): string {
if (!to) {
return normalize(from);
}
if (isAbsolute(to)) {
return normalize(to);
}
return normalize(from + '/' + to);
}
/**
* @function prefix
* @description Prefix the path with symbol.
* @param path The path to prefix.
* @param symbol Prefix symbol.
*/
export function prefix(path: string, symbol: string): string {
return path.startsWith(symbol) ? path : symbol + path;
}
/**
* @function suffix
* @description Suffix the path with symbol.
* @param path The path to suffix.
* @param symbol Suffix symbol.
*/
export function suffix(path: string, symbol: string): string {
return path.endsWith(symbol) ? path : path + symbol;
}
/**
* @function isAboveRoot
* @description Is the path above root.
* @param root The root path.
* @param path The path to check.
* @param sensitive Is case sensitive.
*/
export function isAboveRoot(root: string, path: string, sensitive?: boolean): boolean {
root = suffix(root, '/');
if (!sensitive) {
root = root.toLowerCase();
path = path.toLowerCase();
}
return !path.startsWith(root);
}
| 21.053571 | 87 | 0.617048 | 52 | 7 | 0 | 13 | 3 | 0 | 4 | 0 | 20 | 0 | 0 | 5.428571 | 646 | 0.03096 | 0.004644 | 0 | 0 | 0 | 0 | 0.869565 | 0.257557 | /**
* @module path
*/
/**
* @function isAbsolute
* @description Check if the path is absolute.
* @param path The path to check.
*/
export /* Example usages of 'isAbsolute' are shown below:
isAbsolute(to);
*/
function isAbsolute(path) {
return /^\//.test(path);
}
/**
* @function normalize
* @description Normalize the path.
* @param path The path to normalize.
*/
export /* Example usages of 'normalize' are shown below:
normalize(path);
normalize(base + '/' + path);
normalize(from);
normalize(to);
normalize(from + '/' + to);
*/
function normalize(path) {
const segments = [];
const parts = path.replace(/\\+|\/{2,}/, '/').split('/');
for (const segment of parts) {
switch (segment) {
case '.':
break;
case '..':
const { length } = segments;
if (length && segments[length - 1] !== '..') {
segments.pop();
}
break;
default:
segments.push(segment);
break;
}
}
return segments.join('/') || '/';
}
/**
* @function join
* @description Join the path.
* @param base The base path.
* @param path The path to join.
*/
export /* Example usages of 'join' are shown below:
segments.join('/') || '/';
*/
function join(base, path) {
if (!base) {
return normalize(path);
}
return normalize(base + '/' + path);
}
/**
* @function resolve
* @description Resolve the path.
* @param from The path to start.
* @param to The path to end.
*/
export function resolve(from, to?) {
if (!to) {
return normalize(from);
}
if (isAbsolute(to)) {
return normalize(to);
}
return normalize(from + '/' + to);
}
/**
* @function prefix
* @description Prefix the path with symbol.
* @param path The path to prefix.
* @param symbol Prefix symbol.
*/
export function prefix(path, symbol) {
return path.startsWith(symbol) ? path : symbol + path;
}
/**
* @function suffix
* @description Suffix the path with symbol.
* @param path The path to suffix.
* @param symbol Suffix symbol.
*/
export /* Example usages of 'suffix' are shown below:
root = suffix(root, '/');
*/
function suffix(path, symbol) {
return path.endsWith(symbol) ? path : path + symbol;
}
/**
* @function isAboveRoot
* @description Is the path above root.
* @param root The root path.
* @param path The path to check.
* @param sensitive Is case sensitive.
*/
export function isAboveRoot(root, path, sensitive?) {
root = suffix(root, '/');
if (!sensitive) {
root = root.toLowerCase();
path = path.toLowerCase();
}
return !path.startsWith(root);
}
|
e7a3ab2b518f48d3acb4ad7900534ff03712d10f | 2,278 | ts | TypeScript | packages/foxpage-admin/src/pages/builder/toolbar/tools/structure/utils/utils.ts | foxpage/foxpage | 65bcdb7b1f8e6cd598d43ba1672c11283ad83d32 | [
"MIT"
] | 75 | 2022-01-11T06:30:59.000Z | 2022-03-31T15:05:55.000Z | packages/foxpage-admin/src/pages/builder/toolbar/tools/structure/utils/utils.ts | foxpage/foxpage | 65bcdb7b1f8e6cd598d43ba1672c11283ad83d32 | [
"MIT"
] | 5 | 2022-02-28T05:40:10.000Z | 2022-03-29T08:53:45.000Z | packages/foxpage-admin/src/pages/builder/toolbar/tools/structure/utils/utils.ts | foxpage/foxpage | 65bcdb7b1f8e6cd598d43ba1672c11283ad83d32 | [
"MIT"
] | 17 | 2022-01-11T06:31:05.000Z | 2022-03-31T02:49:54.000Z | export function getAttrData(node, attr) {
if (node) {
return node.getAttribute(attr);
}
return '';
}
function isComponent(node) {
return getAttrData(node, 'data-type') === 'component' && getAttrData(node, 'data-component-id');
}
function getParentNode(node) {
if (node.tagName === 'BODY') {
return undefined;
}
if (getAttrData(node, 'data-type') === 'layer') {
return node.childNodes[0];
}
return getParentNode(node.parentNode);
}
export function getComponentNode(node) {
if (node.tagName === 'BODY') {
return undefined;
}
if (isComponent(node)) {
return node;
}
return getComponentNode(node.parentNode);
}
export function getParentId(node) {
const parentNode = getParentNode(node);
if (parentNode) {
return getAttrData(parentNode, 'data-component-id');
}
return '';
}
export function isChildrenListNode(child) {
return child && getAttrData(child, 'data-type') === 'childrenList';
}
export function getFirstChildNode(node) {
const children = node.parentNode ? node.parentNode.childNodes : [];
for (let i = 0; i < children.length; i++) {
if (isChildrenListNode(children[i])) {
const childs = children[i].childNodes || [];
if (childs[0] && isComponent(childs[0].childNodes[0])) {
return childs[0].childNodes[0];
}
return '';
}
}
return '';
}
export function getRootLastNode(rootDom) {
if (isChildrenListNode(rootDom.childNodes[0])) {
const childs = rootDom.childNodes[0].childNodes || [];
const idx = childs.length - 1;
if (childs[idx] && isComponent(childs[idx].childNodes[0])) {
return childs[idx].childNodes[0];
}
return '';
}
return '';
}
export function getNodeData(node) {
const componentId = getAttrData(node, 'data-component-id');
const parentId = getAttrData(node, 'data-parent-id');
const destIndex = getAttrData(node, 'data-index');
return { componentId, parentId, destIndex };
}
export function newDnd(method, pos, componentId, hoverComponentId, parentId, destIndex, rect) {
return {
method,
pos,
hoverComponentId,
componentId,
parentId,
destIndex,
rect,
};
}
export function newRect(top, width, height, bottom) {
return {
top,
width,
height,
bottom,
};
}
| 23.484536 | 98 | 0.653205 | 86 | 11 | 0 | 21 | 9 | 0 | 5 | 0 | 0 | 0 | 0 | 5.818182 | 651 | 0.049155 | 0.013825 | 0 | 0 | 0 | 0 | 0 | 0.331528 | export /* Example usages of 'getAttrData' are shown below:
getAttrData(node, 'data-type') === 'component' && getAttrData(node, 'data-component-id');
getAttrData(node, 'data-type') === 'layer';
getAttrData(parentNode, 'data-component-id');
child && getAttrData(child, 'data-type') === 'childrenList';
getAttrData(node, 'data-component-id');
getAttrData(node, 'data-parent-id');
getAttrData(node, 'data-index');
*/
function getAttrData(node, attr) {
if (node) {
return node.getAttribute(attr);
}
return '';
}
/* Example usages of 'isComponent' are shown below:
isComponent(node);
childs[0] && isComponent(childs[0].childNodes[0]);
childs[idx] && isComponent(childs[idx].childNodes[0]);
*/
function isComponent(node) {
return getAttrData(node, 'data-type') === 'component' && getAttrData(node, 'data-component-id');
}
/* Example usages of 'getParentNode' are shown below:
getParentNode(node.parentNode);
getParentNode(node);
*/
function getParentNode(node) {
if (node.tagName === 'BODY') {
return undefined;
}
if (getAttrData(node, 'data-type') === 'layer') {
return node.childNodes[0];
}
return getParentNode(node.parentNode);
}
export /* Example usages of 'getComponentNode' are shown below:
getComponentNode(node.parentNode);
*/
function getComponentNode(node) {
if (node.tagName === 'BODY') {
return undefined;
}
if (isComponent(node)) {
return node;
}
return getComponentNode(node.parentNode);
}
export function getParentId(node) {
const parentNode = getParentNode(node);
if (parentNode) {
return getAttrData(parentNode, 'data-component-id');
}
return '';
}
export /* Example usages of 'isChildrenListNode' are shown below:
isChildrenListNode(children[i]);
isChildrenListNode(rootDom.childNodes[0]);
*/
function isChildrenListNode(child) {
return child && getAttrData(child, 'data-type') === 'childrenList';
}
export function getFirstChildNode(node) {
const children = node.parentNode ? node.parentNode.childNodes : [];
for (let i = 0; i < children.length; i++) {
if (isChildrenListNode(children[i])) {
const childs = children[i].childNodes || [];
if (childs[0] && isComponent(childs[0].childNodes[0])) {
return childs[0].childNodes[0];
}
return '';
}
}
return '';
}
export function getRootLastNode(rootDom) {
if (isChildrenListNode(rootDom.childNodes[0])) {
const childs = rootDom.childNodes[0].childNodes || [];
const idx = childs.length - 1;
if (childs[idx] && isComponent(childs[idx].childNodes[0])) {
return childs[idx].childNodes[0];
}
return '';
}
return '';
}
export function getNodeData(node) {
const componentId = getAttrData(node, 'data-component-id');
const parentId = getAttrData(node, 'data-parent-id');
const destIndex = getAttrData(node, 'data-index');
return { componentId, parentId, destIndex };
}
export function newDnd(method, pos, componentId, hoverComponentId, parentId, destIndex, rect) {
return {
method,
pos,
hoverComponentId,
componentId,
parentId,
destIndex,
rect,
};
}
export function newRect(top, width, height, bottom) {
return {
top,
width,
height,
bottom,
};
}
|
8421a8d472765fd2992d131fb5bbc260d133ef72 | 4,360 | ts | TypeScript | packages/graphlib/lib/data/priority-queue.ts | fluggo/graphlib | 4b603a04de1b9821ed4bc34383d22c7d66f15b4d | [
"MIT"
] | 1 | 2022-02-01T01:34:34.000Z | 2022-02-01T01:34:34.000Z | packages/graphlib/lib/data/priority-queue.ts | fluggo/graphlib | 4b603a04de1b9821ed4bc34383d22c7d66f15b4d | [
"MIT"
] | null | null | null | packages/graphlib/lib/data/priority-queue.ts | fluggo/graphlib | 4b603a04de1b9821ed4bc34383d22c7d66f15b4d | [
"MIT"
] | null | null | null | interface PQEntry<K> {
key: K;
priority: number;
}
/**
* A min-priority queue data structure. This algorithm is derived from Cormen,
* et al., "Introduction to Algorithms". The basic idea of a min-priority
* queue is that you can efficiently (in O(1) time) get the smallest key in
* the queue. Adding and removing elements takes O(log n) time. A key can
* have its priority decreased in O(log n) time.
*/
export class PriorityQueue<K> {
private readonly _arr: PQEntry<K>[];
private readonly _keyIndices: Map<K, number>;
constructor() {
this._arr = [];
this._keyIndices = new Map();
}
/**
* Returns the number of elements in the queue. Takes `O(1)` time.
*/
size(): number {
return this._arr.length;
}
/**
* Returns the keys that are in the queue. Takes `O(n)` time.
*/
keys(): K[] {
return this._arr.map(x => x.key);
}
/**
* Returns `true` if **key** is in the queue and `false` if not.
*/
has(key: K): boolean {
return this._keyIndices.has(key);
}
/**
* Returns the priority for **key**. If **key** is not present in the queue
* then this function returns `undefined`. Takes `O(1)` time.
*/
priority(key: K): number | undefined {
const index = this._keyIndices.get(key);
if(index !== undefined) {
return this._arr[index].priority;
}
}
/**
* Returns the key for the minimum element in this queue. If the queue is
* empty this function throws an Error. Takes `O(1)` time.
*/
min(): K {
if(this.size() === 0) {
throw new Error('Queue underflow');
}
return this._arr[0].key;
}
/**
* Inserts a new key into the priority queue. If the key already exists in
* the queue this function does nothing and returns `false`; otherwise it will return `true`.
* Takes `O(n)` time.
*
* @param key the key to add
* @param priority the initial priority for the key
*/
add(key: K, priority: number): boolean {
const keyIndices = this._keyIndices;
if(!keyIndices.has(key)) {
const arr = this._arr;
const index = arr.length;
keyIndices.set(key, index);
arr.push({key: key, priority: priority});
this._decrease(index);
return true;
}
return false;
}
/**
* Removes and returns the smallest key in the queue. Takes `O(log n)` time.
*/
removeMin(): K {
this._swap(0, this._arr.length - 1);
const min = this._arr.pop()!;
this._keyIndices.delete(min.key);
this._heapify(0);
return min.key;
}
/**
* Decreases the priority for **key** to **priority**. If the new priority is
* greater than the previous priority, this function will throw an Error.
*
* @param key the key for which to raise priority
* @param priority the new priority for the key
*/
decrease(key: K, priority: number): void {
const index = this._keyIndices.get(key);
if(index === undefined)
throw new RangeError('Key out of range');
if(priority > this._arr[index].priority) {
throw new Error('New priority is greater than current priority. ' +
`Key: ${String(key)} Old: ${this._arr[index].priority} New: ${priority}`);
}
this._arr[index].priority = priority;
this._decrease(index);
}
private _heapify(i: number): void {
const arr = this._arr;
const l = 2 * i;
const r = l + 1;
let largest = i;
if(l < arr.length) {
largest = arr[l].priority < arr[largest].priority ? l : largest;
if(r < arr.length) {
largest = arr[r].priority < arr[largest].priority ? r : largest;
}
if(largest !== i) {
this._swap(i, largest);
this._heapify(largest);
}
}
}
private _decrease(index: number): void {
const arr = this._arr;
const priority = arr[index].priority;
let parent: number;
while(index !== 0) {
// eslint-disable-next-line no-bitwise
parent = index >> 1;
if(arr[parent].priority < priority) {
break;
}
this._swap(index, parent);
index = parent;
}
}
private _swap(i: number, j: number): void {
const arr = this._arr;
const keyIndices = this._keyIndices;
const origArrI = arr[i];
const origArrJ = arr[j];
arr[i] = origArrJ;
arr[j] = origArrI;
keyIndices.set(origArrJ.key, i);
keyIndices.set(origArrI.key, j);
}
}
| 27.080745 | 95 | 0.608257 | 102 | 13 | 0 | 11 | 17 | 4 | 5 | 0 | 17 | 2 | 0 | 5.461538 | 1,248 | 0.019231 | 0.013622 | 0.003205 | 0.001603 | 0 | 0 | 0.377778 | 0.262913 | interface PQEntry<K> {
key;
priority;
}
/**
* A min-priority queue data structure. This algorithm is derived from Cormen,
* et al., "Introduction to Algorithms". The basic idea of a min-priority
* queue is that you can efficiently (in O(1) time) get the smallest key in
* the queue. Adding and removing elements takes O(log n) time. A key can
* have its priority decreased in O(log n) time.
*/
export class PriorityQueue<K> {
private readonly _arr;
private readonly _keyIndices;
constructor() {
this._arr = [];
this._keyIndices = new Map();
}
/**
* Returns the number of elements in the queue. Takes `O(1)` time.
*/
size() {
return this._arr.length;
}
/**
* Returns the keys that are in the queue. Takes `O(n)` time.
*/
keys() {
return this._arr.map(x => x.key);
}
/**
* Returns `true` if **key** is in the queue and `false` if not.
*/
has(key) {
return this._keyIndices.has(key);
}
/**
* Returns the priority for **key**. If **key** is not present in the queue
* then this function returns `undefined`. Takes `O(1)` time.
*/
priority(key) {
const index = this._keyIndices.get(key);
if(index !== undefined) {
return this._arr[index].priority;
}
}
/**
* Returns the key for the minimum element in this queue. If the queue is
* empty this function throws an Error. Takes `O(1)` time.
*/
min() {
if(this.size() === 0) {
throw new Error('Queue underflow');
}
return this._arr[0].key;
}
/**
* Inserts a new key into the priority queue. If the key already exists in
* the queue this function does nothing and returns `false`; otherwise it will return `true`.
* Takes `O(n)` time.
*
* @param key the key to add
* @param priority the initial priority for the key
*/
add(key, priority) {
const keyIndices = this._keyIndices;
if(!keyIndices.has(key)) {
const arr = this._arr;
const index = arr.length;
keyIndices.set(key, index);
arr.push({key: key, priority: priority});
this._decrease(index);
return true;
}
return false;
}
/**
* Removes and returns the smallest key in the queue. Takes `O(log n)` time.
*/
removeMin() {
this._swap(0, this._arr.length - 1);
const min = this._arr.pop()!;
this._keyIndices.delete(min.key);
this._heapify(0);
return min.key;
}
/**
* Decreases the priority for **key** to **priority**. If the new priority is
* greater than the previous priority, this function will throw an Error.
*
* @param key the key for which to raise priority
* @param priority the new priority for the key
*/
decrease(key, priority) {
const index = this._keyIndices.get(key);
if(index === undefined)
throw new RangeError('Key out of range');
if(priority > this._arr[index].priority) {
throw new Error('New priority is greater than current priority. ' +
`Key: ${String(key)} Old: ${this._arr[index].priority} New: ${priority}`);
}
this._arr[index].priority = priority;
this._decrease(index);
}
private _heapify(i) {
const arr = this._arr;
const l = 2 * i;
const r = l + 1;
let largest = i;
if(l < arr.length) {
largest = arr[l].priority < arr[largest].priority ? l : largest;
if(r < arr.length) {
largest = arr[r].priority < arr[largest].priority ? r : largest;
}
if(largest !== i) {
this._swap(i, largest);
this._heapify(largest);
}
}
}
private _decrease(index) {
const arr = this._arr;
const priority = arr[index].priority;
let parent;
while(index !== 0) {
// eslint-disable-next-line no-bitwise
parent = index >> 1;
if(arr[parent].priority < priority) {
break;
}
this._swap(index, parent);
index = parent;
}
}
private _swap(i, j) {
const arr = this._arr;
const keyIndices = this._keyIndices;
const origArrI = arr[i];
const origArrJ = arr[j];
arr[i] = origArrJ;
arr[j] = origArrI;
keyIndices.set(origArrJ.key, i);
keyIndices.set(origArrI.key, j);
}
}
|
8432c37532d90458c6cbb23b64c49fcf8e55c8b7 | 14,828 | ts | TypeScript | src/tokenizer.ts | optio-labs/aqua-compiler | de7bb97764f7d18870f09e156fdc280e4a8b578c | [
"MIT"
] | 1 | 2022-01-30T20:04:23.000Z | 2022-01-30T20:04:23.000Z | src/tokenizer.ts | optio-labs/aqua-compiler | de7bb97764f7d18870f09e156fdc280e4a8b578c | [
"MIT"
] | null | null | null | src/tokenizer.ts | optio-labs/aqua-compiler | de7bb97764f7d18870f09e156fdc280e4a8b578c | [
"MIT"
] | null | null | null | //
// Tokenizer for the Aqua language.
//
export enum TokenType {
EOF,
PLUS,
MINUS,
NUMBER,
SEMICOLON,
CONST,
LET,
ASSIGNMENT,
IDENTIFIER,
OPEN_PAREN,
CLOSE_PAREN,
OPEN_BRACKET,
CLOSE_BRACKET,
OPEN_BRACE,
CLOSE_BRACE,
FUNCTION,
COMMA,
RETURN,
IF,
ELSE,
WHILE,
FOR,
AND,
OR,
EQ,
NE,
LTE,
LT,
GTE,
GT,
MULTIPLY,
DIVIDE,
NOT,
DOT,
TXN,
GTXN,
ARG,
ADDR,
GLOBAL,
ONCOMPLETE,
TYPEENUM,
STRING,
};
//
// Maps TokenType to the name of each type of token.
//
export const TOKEN_NAME = [
"end-of-file",
"+",
"-",
"number",
"semicolon",
"const",
"let",
"=",
"identifier",
"(",
")",
"{",
"}",
"[",
"]",
"function",
",",
"return",
"if",
"else",
"while",
"for",
"&&",
"||",
"==",
"!=",
"<=",
"<",
">=",
">",
"*",
"/",
"!",
".",
"txn",
"gtxn",
"arg",
"addr",
"global",
"OnComplete",
"TypeEnum",
"string literal",
];
//
// A lookup table for single character operators.
//
const SINGLE_CHARACTER_OPERATORS = {
"+": TokenType.PLUS,
"-": TokenType.MINUS,
";": TokenType.SEMICOLON,
"=": TokenType.ASSIGNMENT,
"(": TokenType.OPEN_PAREN,
")": TokenType.CLOSE_PAREN,
"{": TokenType.OPEN_BRACKET,
"}": TokenType.CLOSE_BRACKET,
"[": TokenType.OPEN_BRACE,
"]": TokenType.CLOSE_BRACE,
",": TokenType.COMMA,
"<": TokenType.LT,
">": TokenType.GT,
"*": TokenType.MULTIPLY,
"/": TokenType.DIVIDE,
"!": TokenType.NOT,
".": TokenType.DOT,
}
//
// A lookup table for two character operators.
//
const TWO_CHARACTER_OPERATORS = {
"&": {
"&": TokenType.AND,
},
"|": {
"|": TokenType.OR,
},
"=": {
"=": TokenType.EQ,
},
"!": {
"=": TokenType.NE,
},
"<": {
"=": TokenType.LTE,
},
">": {
"=": TokenType.GTE,
},
}
//
// Maps a string of characters to a TokenType.
//
export const KEYWORDS = {
const: TokenType.CONST,
let: TokenType.LET,
function: TokenType.FUNCTION,
return: TokenType.RETURN,
if: TokenType.IF,
else: TokenType.ELSE,
for: TokenType.FOR,
while: TokenType.WHILE,
txn: TokenType.TXN,
gtxn: TokenType.GTXN,
arg: TokenType.ARG,
addr: TokenType.ADDR,
global: TokenType.GLOBAL,
OnComplete: TokenType.ONCOMPLETE,
TypeEnum: TokenType.TYPEENUM,
};
//
// Represents a token.
//
export interface IToken {
//
// Specifies the type of token.
//
readonly type: TokenType;
//
// The value of the token, for tokens that have a value.
//
readonly value?: any;
//
// Line number where the token starts.
//
readonly line: number;
//
// Column number where the token starts.
//
readonly column: number;
//
// The string value of the token.
//
// TODO: This should only be read from the source code buffer when necessary.
//
readonly string: string;
}
//
// Interface for reporting errors.
//
export interface IError {
//
// The error message.
//
msg: string;
//
// 1-based line number where the error occurred.
//
line: number;
//
// 0-based column number where the error occurred.
//
column: number;
}
//
// Interface to a source code tokenizer for the Aqua language.
//
export interface ITokenizer {
//
// Scans the next token and makes it the current token.
//
readNext(): void;
//
// Returns the current token.
//
getCurrent(): IToken | undefined;
//
// Returns true once all input has been consumed.
//
isAtEnd(): boolean;
//
// Gets the current line number in the input.
//
getLine(): number;
//
// Gets the current column number in the input.
//
getColumn(): number;
}
//
// Defines a handler for errors.
//
export type OnErrorFn = (err: IError) => void;
//
// A source code tokenizer for the Aqua language.
//
export class Tokenizer implements ITokenizer {
//
// The source code being tokenized.
//
private code: string;
//
// The current position in the code to read the next token.
//
private curPosition: number;
//
// Tracks the current line number within the input.
//
private curLine: number;
//
// Tracks the current column number within the input.
//
private curColumn: number;
//
// The position in the code where the current token starts.
//
private curTokenStart?: number;
//
// The line in the code where the current token starts.
//
private curTokenLine?: number;
//
// The column in the code where the current token starts.
//
private curTokenColumn?: number;
//
// The most recently scannned token.
//
private curToken?: IToken;
//
// A simple interface that allows the tokenizer to report an error and continue scanning.
//
private onError?: OnErrorFn;
constructor(code: string, onError?: OnErrorFn) {
this.code = code;
this.curPosition = 0;
this.curLine = 1;
this.curColumn = 0;
this.onError = onError;
}
//
// Scans the next token and makes it the current token.
// This must be called at least once to "prime" the tokenizer before trying to look at the
// "current token".
//
readNext(): void {
while (true) {
this.skipWhitespace();
if (this.isAtEnd()) {
this.setCurrent({
type: TokenType.EOF,
line: this.curLine,
column: this.curColumn,
string: "end of file",
});
return;
}
this.curTokenStart = this.curPosition;
this.curTokenLine = this.curLine;
this.curTokenColumn = this.curColumn;
const ch = this.advance();
if (ch === "/" && this.peek() === "/") {
// Single line comment.
this.skipToNewLine();
continue;
}
const twoCharacterTokenLookup = (TWO_CHARACTER_OPERATORS as any)[ch];
if (twoCharacterTokenLookup !== undefined) {
const nextCh = this.peek();
const twoCharacterTokenType = nextCh !== undefined && twoCharacterTokenLookup[nextCh] || undefined;
if (twoCharacterTokenType !== undefined) {
this.advance();
this.setCurrent({
type: twoCharacterTokenType,
line: this.curTokenLine,
column: this.curTokenColumn,
string: ch + nextCh,
});
return;
}
}
const singleCharacterTokenType: TokenType = (SINGLE_CHARACTER_OPERATORS as any)[ch];
if (singleCharacterTokenType !== undefined) {
this.setCurrent({
type: singleCharacterTokenType,
line: this.curTokenLine,
column: this.curTokenColumn,
string: ch,
});
return;
}
if (ch === "\"") {
this.stringLiteral();
return;
}
if (this.isDigit(ch)) {
this.readNumber();
return;
}
if (this.isAlpha(ch)) {
this.readIdentifer();
return;
}
// Report error, then continue scanning at the next character.
this.raiseError({
msg: `Encountered unexpected character "${ch}"`,
line: this.curTokenLine,
column: this.curTokenColumn,
});
}
}
//
// Raises an error.
//
private raiseError(err: IError) {
if (this.onError) {
this.onError(err);
}
}
//
// Returns the current token.
//
getCurrent(): IToken | undefined {
return this.curToken;
}
//
// Returns true once all input has been consumed.
//
isAtEnd(): boolean {
return this.curPosition >= this.code.length;
}
//
// Gets the current line number in the input.
//
getLine(): number {
return this.curLine;
}
//
// Gets the current column number in the input.
//
getColumn(): number {
return this.curColumn;
}
//
// Sets the current token.
//
private setCurrent(token: IToken) {
this.curToken = token;
}
//
// Return the current character and then advance the current position by one place.
//
private advance(): string {
const ch = this.code[this.curPosition];
if (ch === "\n") {
this.curLine += 1;
this.curColumn = 0;
}
else {
this.curColumn += 1;
}
this.curPosition += 1;
return ch;
}
//
// Look at the next character in the input without advancing the position.
// Returns undefined when there is no more input to look at.
//
private peek(): string | undefined {
if (this.isAtEnd()) {
return undefined;
}
return this.code[this.curPosition];
}
//
// Skips whitespace characters in the code.
//
private skipWhitespace(): void {
while (true) {
const ch = this.peek();
if (ch === " " || ch === "\t" || ch === "\r" || ch === "\n") {
this.advance();
}
else {
break;
}
}
}
//
// Skips to the next new line.
//
private skipToNewLine(): void {
while (true) {
const ch = this.peek();
if (ch === "\n") {
break;
}
if (ch === undefined) {
break;
}
this.advance();
}
}
//
// https://stackoverflow.com/a/38370808/25868
//
private readonly charCodeZero = "0".charCodeAt(0);
private readonly charCodeNine = "9".charCodeAt(0);
private readonly charCodea = "a".charCodeAt(0);
private readonly charCodez = "z".charCodeAt(0);
private readonly charCodeA = "A".charCodeAt(0);
private readonly charCodeZ = "Z".charCodeAt(0);
private readonly charCode_ = "_".charCodeAt(0);
//
// Returns true if the specified charater is a digit.
//
private isDigit(ch: string | undefined): boolean {
if (ch === undefined) {
// No more input, so by definition it's not a digit.
return false;
}
const charCode = ch.charCodeAt(0); //TODO: Optimization: Just pass the character offset in the original buffer through and then pull the char code directly from the buffer.
return charCode >= this.charCodeZero && charCode <= this.charCodeNine;
}
//
// Reads the subsequent digits of a number token.
//
private readNumber(): void {
while (this.isDigit(this.peek())) {
this.advance();
}
const stringValue = this.code.substring(this.curTokenStart!, this.curPosition);
this.setCurrent({
type: TokenType.NUMBER,
value: parseFloat(stringValue),
line: this.curTokenLine!,
column: this.curTokenColumn!,
string: stringValue,
});
}
//
// Returns true if the specified charater is a alphabetical character..
//
private isAlpha(ch: string | undefined): boolean {
if (ch === undefined) {
// No more input, so by definition it's not a digit.
return false;
}
const charCode = ch.charCodeAt(0); //TODO: Optimization: Just pass the character offset in the original buffer through and then pull the char code directly from the buffer.
return charCode >= this.charCodea && charCode <= this.charCodez
|| charCode >= this.charCodeA && charCode <= this.charCodeZ
|| charCode === this.charCode_;
}
//
// Returns true if the specified charater is a alphabetical or numerical character.
//
private isAlphaNumeric(ch: string | undefined): boolean {
return this.isAlpha(ch) || this.isDigit(ch);
}
//
// Reads the subsequent digits of an identifier or keyword token.
//
private readIdentifer(): void {
while (this.isAlphaNumeric(this.peek())) {
this.advance();
}
const stringValue = this.code.substring(this.curTokenStart!, this.curPosition);
const tokenType = (KEYWORDS as any)[stringValue];
if (tokenType === undefined) {
this.setCurrent({
type: TokenType.IDENTIFIER,
value: stringValue,
line: this.curTokenLine!,
column: this.curTokenColumn!,
string: stringValue,
});
}
else {
this.setCurrent({
type: tokenType,
line: this.curTokenLine!,
column: this.curTokenColumn!,
string: stringValue,
});
}
}
//
// Reads the characters of a string literal.
//
private stringLiteral(): void {
while (true) {
const ch = this.peek();
if (ch === undefined) {
// End of file!
this.raiseError({
msg: "Unterminated string literal.",
line: this.curTokenLine!,
column: this.curTokenColumn!,
});
break;
}
if (ch === "\n") {
// End of file!
this.raiseError({
msg: "String literal was terminated by a new line.",
line: this.curTokenLine!,
column: this.curTokenColumn!,
});
break;
}
this.advance();
if (ch === "\"") {
break; // End of string literal.
}
}
const value = this.code.substring(this.curTokenStart! + 1, this.curPosition - 1);
this.setCurrent({
type: TokenType.STRING,
value: value,
line: this.curTokenLine!,
column: this.curTokenColumn!,
string: value,
});
}
} | 23.573927 | 180 | 0.51133 | 403 | 18 | 5 | 7 | 19 | 24 | 13 | 4 | 36 | 5 | 3 | 10.277778 | 3,444 | 0.007259 | 0.005517 | 0.006969 | 0.001452 | 0.000871 | 0.054795 | 0.493151 | 0.209075 | //
// Tokenizer for the Aqua language.
//
export enum TokenType {
EOF,
PLUS,
MINUS,
NUMBER,
SEMICOLON,
CONST,
LET,
ASSIGNMENT,
IDENTIFIER,
OPEN_PAREN,
CLOSE_PAREN,
OPEN_BRACKET,
CLOSE_BRACKET,
OPEN_BRACE,
CLOSE_BRACE,
FUNCTION,
COMMA,
RETURN,
IF,
ELSE,
WHILE,
FOR,
AND,
OR,
EQ,
NE,
LTE,
LT,
GTE,
GT,
MULTIPLY,
DIVIDE,
NOT,
DOT,
TXN,
GTXN,
ARG,
ADDR,
GLOBAL,
ONCOMPLETE,
TYPEENUM,
STRING,
};
//
// Maps TokenType to the name of each type of token.
//
export const TOKEN_NAME = [
"end-of-file",
"+",
"-",
"number",
"semicolon",
"const",
"let",
"=",
"identifier",
"(",
")",
"{",
"}",
"[",
"]",
"function",
",",
"return",
"if",
"else",
"while",
"for",
"&&",
"||",
"==",
"!=",
"<=",
"<",
">=",
">",
"*",
"/",
"!",
".",
"txn",
"gtxn",
"arg",
"addr",
"global",
"OnComplete",
"TypeEnum",
"string literal",
];
//
// A lookup table for single character operators.
//
const SINGLE_CHARACTER_OPERATORS = {
"+": TokenType.PLUS,
"-": TokenType.MINUS,
";": TokenType.SEMICOLON,
"=": TokenType.ASSIGNMENT,
"(": TokenType.OPEN_PAREN,
")": TokenType.CLOSE_PAREN,
"{": TokenType.OPEN_BRACKET,
"}": TokenType.CLOSE_BRACKET,
"[": TokenType.OPEN_BRACE,
"]": TokenType.CLOSE_BRACE,
",": TokenType.COMMA,
"<": TokenType.LT,
">": TokenType.GT,
"*": TokenType.MULTIPLY,
"/": TokenType.DIVIDE,
"!": TokenType.NOT,
".": TokenType.DOT,
}
//
// A lookup table for two character operators.
//
const TWO_CHARACTER_OPERATORS = {
"&": {
"&": TokenType.AND,
},
"|": {
"|": TokenType.OR,
},
"=": {
"=": TokenType.EQ,
},
"!": {
"=": TokenType.NE,
},
"<": {
"=": TokenType.LTE,
},
">": {
"=": TokenType.GTE,
},
}
//
// Maps a string of characters to a TokenType.
//
export const KEYWORDS = {
const: TokenType.CONST,
let: TokenType.LET,
function: TokenType.FUNCTION,
return: TokenType.RETURN,
if: TokenType.IF,
else: TokenType.ELSE,
for: TokenType.FOR,
while: TokenType.WHILE,
txn: TokenType.TXN,
gtxn: TokenType.GTXN,
arg: TokenType.ARG,
addr: TokenType.ADDR,
global: TokenType.GLOBAL,
OnComplete: TokenType.ONCOMPLETE,
TypeEnum: TokenType.TYPEENUM,
};
//
// Represents a token.
//
export interface IToken {
//
// Specifies the type of token.
//
readonly type;
//
// The value of the token, for tokens that have a value.
//
readonly value?;
//
// Line number where the token starts.
//
readonly line;
//
// Column number where the token starts.
//
readonly column;
//
// The string value of the token.
//
// TODO: This should only be read from the source code buffer when necessary.
//
readonly string;
}
//
// Interface for reporting errors.
//
export interface IError {
//
// The error message.
//
msg;
//
// 1-based line number where the error occurred.
//
line;
//
// 0-based column number where the error occurred.
//
column;
}
//
// Interface to a source code tokenizer for the Aqua language.
//
export interface ITokenizer {
//
// Scans the next token and makes it the current token.
//
readNext();
//
// Returns the current token.
//
getCurrent();
//
// Returns true once all input has been consumed.
//
isAtEnd();
//
// Gets the current line number in the input.
//
getLine();
//
// Gets the current column number in the input.
//
getColumn();
}
//
// Defines a handler for errors.
//
export type OnErrorFn = (err) => void;
//
// A source code tokenizer for the Aqua language.
//
export class Tokenizer implements ITokenizer {
//
// The source code being tokenized.
//
private code;
//
// The current position in the code to read the next token.
//
private curPosition;
//
// Tracks the current line number within the input.
//
private curLine;
//
// Tracks the current column number within the input.
//
private curColumn;
//
// The position in the code where the current token starts.
//
private curTokenStart?;
//
// The line in the code where the current token starts.
//
private curTokenLine?;
//
// The column in the code where the current token starts.
//
private curTokenColumn?;
//
// The most recently scannned token.
//
private curToken?;
//
// A simple interface that allows the tokenizer to report an error and continue scanning.
//
private onError?;
constructor(code, onError?) {
this.code = code;
this.curPosition = 0;
this.curLine = 1;
this.curColumn = 0;
this.onError = onError;
}
//
// Scans the next token and makes it the current token.
// This must be called at least once to "prime" the tokenizer before trying to look at the
// "current token".
//
readNext() {
while (true) {
this.skipWhitespace();
if (this.isAtEnd()) {
this.setCurrent({
type: TokenType.EOF,
line: this.curLine,
column: this.curColumn,
string: "end of file",
});
return;
}
this.curTokenStart = this.curPosition;
this.curTokenLine = this.curLine;
this.curTokenColumn = this.curColumn;
const ch = this.advance();
if (ch === "/" && this.peek() === "/") {
// Single line comment.
this.skipToNewLine();
continue;
}
const twoCharacterTokenLookup = (TWO_CHARACTER_OPERATORS as any)[ch];
if (twoCharacterTokenLookup !== undefined) {
const nextCh = this.peek();
const twoCharacterTokenType = nextCh !== undefined && twoCharacterTokenLookup[nextCh] || undefined;
if (twoCharacterTokenType !== undefined) {
this.advance();
this.setCurrent({
type: twoCharacterTokenType,
line: this.curTokenLine,
column: this.curTokenColumn,
string: ch + nextCh,
});
return;
}
}
const singleCharacterTokenType = (SINGLE_CHARACTER_OPERATORS as any)[ch];
if (singleCharacterTokenType !== undefined) {
this.setCurrent({
type: singleCharacterTokenType,
line: this.curTokenLine,
column: this.curTokenColumn,
string: ch,
});
return;
}
if (ch === "\"") {
this.stringLiteral();
return;
}
if (this.isDigit(ch)) {
this.readNumber();
return;
}
if (this.isAlpha(ch)) {
this.readIdentifer();
return;
}
// Report error, then continue scanning at the next character.
this.raiseError({
msg: `Encountered unexpected character "${ch}"`,
line: this.curTokenLine,
column: this.curTokenColumn,
});
}
}
//
// Raises an error.
//
private raiseError(err) {
if (this.onError) {
this.onError(err);
}
}
//
// Returns the current token.
//
getCurrent() {
return this.curToken;
}
//
// Returns true once all input has been consumed.
//
isAtEnd() {
return this.curPosition >= this.code.length;
}
//
// Gets the current line number in the input.
//
getLine() {
return this.curLine;
}
//
// Gets the current column number in the input.
//
getColumn() {
return this.curColumn;
}
//
// Sets the current token.
//
private setCurrent(token) {
this.curToken = token;
}
//
// Return the current character and then advance the current position by one place.
//
private advance() {
const ch = this.code[this.curPosition];
if (ch === "\n") {
this.curLine += 1;
this.curColumn = 0;
}
else {
this.curColumn += 1;
}
this.curPosition += 1;
return ch;
}
//
// Look at the next character in the input without advancing the position.
// Returns undefined when there is no more input to look at.
//
private peek() {
if (this.isAtEnd()) {
return undefined;
}
return this.code[this.curPosition];
}
//
// Skips whitespace characters in the code.
//
private skipWhitespace() {
while (true) {
const ch = this.peek();
if (ch === " " || ch === "\t" || ch === "\r" || ch === "\n") {
this.advance();
}
else {
break;
}
}
}
//
// Skips to the next new line.
//
private skipToNewLine() {
while (true) {
const ch = this.peek();
if (ch === "\n") {
break;
}
if (ch === undefined) {
break;
}
this.advance();
}
}
//
// https://stackoverflow.com/a/38370808/25868
//
private readonly charCodeZero = "0".charCodeAt(0);
private readonly charCodeNine = "9".charCodeAt(0);
private readonly charCodea = "a".charCodeAt(0);
private readonly charCodez = "z".charCodeAt(0);
private readonly charCodeA = "A".charCodeAt(0);
private readonly charCodeZ = "Z".charCodeAt(0);
private readonly charCode_ = "_".charCodeAt(0);
//
// Returns true if the specified charater is a digit.
//
private isDigit(ch) {
if (ch === undefined) {
// No more input, so by definition it's not a digit.
return false;
}
const charCode = ch.charCodeAt(0); //TODO: Optimization: Just pass the character offset in the original buffer through and then pull the char code directly from the buffer.
return charCode >= this.charCodeZero && charCode <= this.charCodeNine;
}
//
// Reads the subsequent digits of a number token.
//
private readNumber() {
while (this.isDigit(this.peek())) {
this.advance();
}
const stringValue = this.code.substring(this.curTokenStart!, this.curPosition);
this.setCurrent({
type: TokenType.NUMBER,
value: parseFloat(stringValue),
line: this.curTokenLine!,
column: this.curTokenColumn!,
string: stringValue,
});
}
//
// Returns true if the specified charater is a alphabetical character..
//
private isAlpha(ch) {
if (ch === undefined) {
// No more input, so by definition it's not a digit.
return false;
}
const charCode = ch.charCodeAt(0); //TODO: Optimization: Just pass the character offset in the original buffer through and then pull the char code directly from the buffer.
return charCode >= this.charCodea && charCode <= this.charCodez
|| charCode >= this.charCodeA && charCode <= this.charCodeZ
|| charCode === this.charCode_;
}
//
// Returns true if the specified charater is a alphabetical or numerical character.
//
private isAlphaNumeric(ch) {
return this.isAlpha(ch) || this.isDigit(ch);
}
//
// Reads the subsequent digits of an identifier or keyword token.
//
private readIdentifer() {
while (this.isAlphaNumeric(this.peek())) {
this.advance();
}
const stringValue = this.code.substring(this.curTokenStart!, this.curPosition);
const tokenType = (KEYWORDS as any)[stringValue];
if (tokenType === undefined) {
this.setCurrent({
type: TokenType.IDENTIFIER,
value: stringValue,
line: this.curTokenLine!,
column: this.curTokenColumn!,
string: stringValue,
});
}
else {
this.setCurrent({
type: tokenType,
line: this.curTokenLine!,
column: this.curTokenColumn!,
string: stringValue,
});
}
}
//
// Reads the characters of a string literal.
//
private stringLiteral() {
while (true) {
const ch = this.peek();
if (ch === undefined) {
// End of file!
this.raiseError({
msg: "Unterminated string literal.",
line: this.curTokenLine!,
column: this.curTokenColumn!,
});
break;
}
if (ch === "\n") {
// End of file!
this.raiseError({
msg: "String literal was terminated by a new line.",
line: this.curTokenLine!,
column: this.curTokenColumn!,
});
break;
}
this.advance();
if (ch === "\"") {
break; // End of string literal.
}
}
const value = this.code.substring(this.curTokenStart! + 1, this.curPosition - 1);
this.setCurrent({
type: TokenType.STRING,
value: value,
line: this.curTokenLine!,
column: this.curTokenColumn!,
string: value,
});
}
} |
655a54a8828579567144872dc38c7ccacc368066 | 6,759 | ts | TypeScript | packages/common/src/format.ts | nakatamaho/qni | d384f2ab9eda8d0aeaa707a65179b03fadd458ff | [
"MIT"
] | 17 | 2022-01-25T00:30:12.000Z | 2022-03-17T07:38:32.000Z | packages/common/src/format.ts | qniapp/qni | 35b5fd05b5d01eb84aa16990056a11b439323301 | [
"MIT"
] | 51 | 2022-02-10T05:45:34.000Z | 2022-03-28T07:19:17.000Z | packages/common/src/format.ts | qniapp/qni | 35b5fd05b5d01eb84aa16990056a11b439323301 | [
"MIT"
] | 3 | 2022-02-06T13:34:46.000Z | 2022-02-17T07:29:19.000Z | type UnicodeFraction = {character: string; ref: string; value: number}
/**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const UNICODE_FRACTIONS = [
{character: '\u00BD', ref: '½', expanded: '1/2', value: 1 / 2},
{character: '\u00BC', ref: '¼', expanded: '1/4', value: 1 / 4},
{character: '\u00BE', ref: '¾', expanded: '3/4', value: 3 / 4},
{character: '\u2153', ref: '⅓', expanded: '1/3', value: 1 / 3},
{character: '\u2154', ref: '⅔', expanded: '2/3', value: 2 / 3},
{character: '\u2155', ref: '⅕', expanded: '1/5', value: 1 / 5},
{character: '\u2156', ref: '⅖', expanded: '2/5', value: 2 / 5},
{character: '\u2157', ref: '⅗', expanded: '3/5', value: 3 / 5},
{character: '\u2158', ref: '⅘', expanded: '4/5', value: 4 / 5},
{character: '\u2159', ref: '⅙', expanded: '1/6', value: 1 / 6},
{character: '\u215A', ref: '⅚', expanded: '5/6', value: 5 / 6},
{character: '\u2150', ref: '⅐', expanded: '1/7', value: 1 / 7},
{character: '\u215B', ref: '⅛', expanded: '1/8', value: 1 / 8},
{character: '\u215C', ref: '⅜', expanded: '3/8', value: 3 / 8},
{character: '\u215D', ref: '⅝', expanded: '5/8', value: 5 / 8},
{character: '\u215E', ref: '⅞', expanded: '7/8', value: 7 / 8},
{character: '\u2151', ref: '⅑', expanded: '1/9', value: 1 / 9},
{character: '\u2152', ref: '⅒', expanded: '1/10', value: 1 / 10}
]
/**
* Stores formatting options, for determining what string output should look
* like.
*/
export class Format {
/**
* Returns an approximated result, but with the constraint that when it
* changes slightly it should "look the same". (It should look good when
* varying and animated.)
*/
static readonly CONSISTENT = new Format(false, 0, 2, ', ')
/**
* Returns an accurate result, but favoring looking nice over being small.
*/
static readonly EXACT = new Format(true, 0, undefined, ', ')
/**
* Returns an accurate result, favoring being small over looking nice.
*/
static readonly MINIFIED = new Format(true, 0, undefined, ',')
/**
* Returns an approximated result, strongly favoring looking nice.
*/
static readonly SIMPLIFIED = new Format(true, 0.0005, 3, ', ')
/**
* Parses the given text into a float. Works for text created by
* [[formatFloat]].
*/
static parseFloat(text: string): number {
if (text.length === 0) {
throw new Error(`Not a number: '${text}'`)
}
if (text[0] === '-') {
return -Format.parseFloat(text.substr(1))
}
if (text[0] === '\u221A') {
return Math.sqrt(Format.parseFloat(text.substr(1)))
}
const fraction = Format.matchUnicodeFraction(e => e.character === text)
if (fraction !== undefined) {
return fraction.value
}
const result = parseFloat(text)
if (isNaN(result)) {
throw new Error(`Not a number: '${text}'`)
}
return result
}
/**
* Corrects a value to a nearby simple fraction or root thereof, such as
* sqrt(1/2), so it can be printed compactly.
*
* @param value The value to round.
* @param epsilon The maximum offset error introduced by the rounding.
*/
static simplifyByRounding(value: number, epsilon: number): number {
if (value < 0) {
return -Format.simplifyByRounding(-value, epsilon)
}
const r = value % 1
if (r <= epsilon || 1 - r <= epsilon) {
return Math.round(value)
}
const fraction = Format.matchUnicodeFraction(e => Math.abs(e.value - value) <= epsilon)
if (fraction !== undefined) {
return fraction.value
}
const rootFraction = Format.matchUnicodeFraction(e => Math.abs(Math.sqrt(e.value) - value) <= epsilon)
if (rootFraction !== undefined) {
return Math.sqrt(rootFraction.value)
}
return value
}
/**
* Returns the first element of an array matching the given predicate, or else
* returns undefined.
*
* @hidden
*/
static matchUnicodeFraction(predicate: (arrayItem: UnicodeFraction) => boolean): UnicodeFraction | undefined {
for (const each of UNICODE_FRACTIONS) {
if (predicate(each)) return each
}
return undefined
}
public allowAbbreviation: boolean
public maxAbbreviationError: number
public fixedDigits: number | undefined
public itemSeparator: string
/**
* @param allowAbbreviation Should outputs be shortened, if possible?
* @param maxAbbreviationError How much error is abbreviating allowed to introduce?
* @param fixedDigits Use toFixed? How many digits?
* @param itemSeparator What should list items be separated by?
*/
constructor(
allowAbbreviation: boolean,
maxAbbreviationError: number,
fixedDigits: number | undefined,
itemSeparator: string
) {
this.allowAbbreviation = allowAbbreviation
this.maxAbbreviationError = maxAbbreviationError
this.fixedDigits = fixedDigits
this.itemSeparator = itemSeparator
}
formatFloat(f: number): string {
if (this.allowAbbreviation) {
return this.abbreviateFloat(f, this.maxAbbreviationError, this.fixedDigits)
}
if (this.fixedDigits !== undefined) {
return f.toFixed(this.fixedDigits)
}
return String(f)
}
/**
* Returns a string representation of a float, taking advantage of unicode
* fractions and square roots.
*
* @param value The value to represent as a string.
* @param epsilon The maximum error introduced by using an expression.
* @param digits digits The number of digits to use if no expression matches.
*/
private abbreviateFloat(value: number, epsilon = 0, digits: number | undefined = undefined): string {
if (Math.abs(value) < epsilon) return '0'
if (value < 0) return `-${this.abbreviateFloat(-value, epsilon, digits)}`
const fraction = Format.matchUnicodeFraction(e => Math.abs(e.value - value) <= epsilon)
if (fraction !== undefined) {
return fraction.character
}
const rootFraction = Format.matchUnicodeFraction(e => Math.abs(Math.sqrt(e.value) - value) <= epsilon)
if (rootFraction !== undefined) {
return `\u221A${rootFraction.character}`
}
if (value % 1 !== 0 && digits !== undefined) {
return value.toFixed(digits)
}
return value.toString()
}
}
| 33.964824 | 112 | 0.646101 | 111 | 11 | 0 | 17 | 8 | 11 | 4 | 0 | 22 | 2 | 0 | 6.181818 | 2,013 | 0.01391 | 0.003974 | 0.005464 | 0.000994 | 0 | 0 | 0.468085 | 0.217576 | type UnicodeFraction = {character; ref; value}
/**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export const UNICODE_FRACTIONS = [
{character: '\u00BD', ref: '½', expanded: '1/2', value: 1 / 2},
{character: '\u00BC', ref: '¼', expanded: '1/4', value: 1 / 4},
{character: '\u00BE', ref: '¾', expanded: '3/4', value: 3 / 4},
{character: '\u2153', ref: '⅓', expanded: '1/3', value: 1 / 3},
{character: '\u2154', ref: '⅔', expanded: '2/3', value: 2 / 3},
{character: '\u2155', ref: '⅕', expanded: '1/5', value: 1 / 5},
{character: '\u2156', ref: '⅖', expanded: '2/5', value: 2 / 5},
{character: '\u2157', ref: '⅗', expanded: '3/5', value: 3 / 5},
{character: '\u2158', ref: '⅘', expanded: '4/5', value: 4 / 5},
{character: '\u2159', ref: '⅙', expanded: '1/6', value: 1 / 6},
{character: '\u215A', ref: '⅚', expanded: '5/6', value: 5 / 6},
{character: '\u2150', ref: '⅐', expanded: '1/7', value: 1 / 7},
{character: '\u215B', ref: '⅛', expanded: '1/8', value: 1 / 8},
{character: '\u215C', ref: '⅜', expanded: '3/8', value: 3 / 8},
{character: '\u215D', ref: '⅝', expanded: '5/8', value: 5 / 8},
{character: '\u215E', ref: '⅞', expanded: '7/8', value: 7 / 8},
{character: '\u2151', ref: '⅑', expanded: '1/9', value: 1 / 9},
{character: '\u2152', ref: '⅒', expanded: '1/10', value: 1 / 10}
]
/**
* Stores formatting options, for determining what string output should look
* like.
*/
export class Format {
/**
* Returns an approximated result, but with the constraint that when it
* changes slightly it should "look the same". (It should look good when
* varying and animated.)
*/
static readonly CONSISTENT = new Format(false, 0, 2, ', ')
/**
* Returns an accurate result, but favoring looking nice over being small.
*/
static readonly EXACT = new Format(true, 0, undefined, ', ')
/**
* Returns an accurate result, favoring being small over looking nice.
*/
static readonly MINIFIED = new Format(true, 0, undefined, ',')
/**
* Returns an approximated result, strongly favoring looking nice.
*/
static readonly SIMPLIFIED = new Format(true, 0.0005, 3, ', ')
/**
* Parses the given text into a float. Works for text created by
* [[formatFloat]].
*/
static parseFloat(text) {
if (text.length === 0) {
throw new Error(`Not a number: '${text}'`)
}
if (text[0] === '-') {
return -Format.parseFloat(text.substr(1))
}
if (text[0] === '\u221A') {
return Math.sqrt(Format.parseFloat(text.substr(1)))
}
const fraction = Format.matchUnicodeFraction(e => e.character === text)
if (fraction !== undefined) {
return fraction.value
}
const result = parseFloat(text)
if (isNaN(result)) {
throw new Error(`Not a number: '${text}'`)
}
return result
}
/**
* Corrects a value to a nearby simple fraction or root thereof, such as
* sqrt(1/2), so it can be printed compactly.
*
* @param value The value to round.
* @param epsilon The maximum offset error introduced by the rounding.
*/
static simplifyByRounding(value, epsilon) {
if (value < 0) {
return -Format.simplifyByRounding(-value, epsilon)
}
const r = value % 1
if (r <= epsilon || 1 - r <= epsilon) {
return Math.round(value)
}
const fraction = Format.matchUnicodeFraction(e => Math.abs(e.value - value) <= epsilon)
if (fraction !== undefined) {
return fraction.value
}
const rootFraction = Format.matchUnicodeFraction(e => Math.abs(Math.sqrt(e.value) - value) <= epsilon)
if (rootFraction !== undefined) {
return Math.sqrt(rootFraction.value)
}
return value
}
/**
* Returns the first element of an array matching the given predicate, or else
* returns undefined.
*
* @hidden
*/
static matchUnicodeFraction(predicate) {
for (const each of UNICODE_FRACTIONS) {
if (predicate(each)) return each
}
return undefined
}
public allowAbbreviation
public maxAbbreviationError
public fixedDigits
public itemSeparator
/**
* @param allowAbbreviation Should outputs be shortened, if possible?
* @param maxAbbreviationError How much error is abbreviating allowed to introduce?
* @param fixedDigits Use toFixed? How many digits?
* @param itemSeparator What should list items be separated by?
*/
constructor(
allowAbbreviation,
maxAbbreviationError,
fixedDigits,
itemSeparator
) {
this.allowAbbreviation = allowAbbreviation
this.maxAbbreviationError = maxAbbreviationError
this.fixedDigits = fixedDigits
this.itemSeparator = itemSeparator
}
formatFloat(f) {
if (this.allowAbbreviation) {
return this.abbreviateFloat(f, this.maxAbbreviationError, this.fixedDigits)
}
if (this.fixedDigits !== undefined) {
return f.toFixed(this.fixedDigits)
}
return String(f)
}
/**
* Returns a string representation of a float, taking advantage of unicode
* fractions and square roots.
*
* @param value The value to represent as a string.
* @param epsilon The maximum error introduced by using an expression.
* @param digits digits The number of digits to use if no expression matches.
*/
private abbreviateFloat(value, epsilon = 0, digits = undefined) {
if (Math.abs(value) < epsilon) return '0'
if (value < 0) return `-${this.abbreviateFloat(-value, epsilon, digits)}`
const fraction = Format.matchUnicodeFraction(e => Math.abs(e.value - value) <= epsilon)
if (fraction !== undefined) {
return fraction.character
}
const rootFraction = Format.matchUnicodeFraction(e => Math.abs(Math.sqrt(e.value) - value) <= epsilon)
if (rootFraction !== undefined) {
return `\u221A${rootFraction.character}`
}
if (value % 1 !== 0 && digits !== undefined) {
return value.toFixed(digits)
}
return value.toString()
}
}
|
659595749694bcb3185a5107ac11261f270b17f8 | 1,508 | ts | TypeScript | apps/website/src/docs/utils/get-route-context.ts | milanvanschaik/saas-ui | a26aa7cdc976e8394f81ea94ec3022555c4bc549 | [
"MIT"
] | 107 | 2022-01-28T13:28:58.000Z | 2022-03-31T21:59:55.000Z | apps/website/src/docs/utils/get-route-context.ts | milanvanschaik/saas-ui | a26aa7cdc976e8394f81ea94ec3022555c4bc549 | [
"MIT"
] | 25 | 2022-02-06T02:25:04.000Z | 2022-03-25T16:32:43.000Z | apps/website/src/docs/utils/get-route-context.ts | milanvanschaik/saas-ui | a26aa7cdc976e8394f81ea94ec3022555c4bc549 | [
"MIT"
] | 12 | 2022-01-29T12:03:14.000Z | 2022-03-26T15:04:24.000Z | export interface RouteItem {
title: string
path?: string
open?: boolean
heading?: boolean
sort?: boolean
routes?: RouteItem[]
new?: true
soon?: true
}
export interface Routes {
routes: RouteItem[]
}
export interface Page {
id: string
html: string
title: string
toc: any
}
export interface Post {
slug: string
content: string
title: string
date: string
author: string
toc: any
ogImage: {
url: string
}
coverImage: string
}
export interface RouteContext {
parent?: RouteItem
prevRoute?: RouteItem
nextRoute?: RouteItem
route?: RouteItem
}
export const getAllRoutes = (routes: any) => {
const allRoutes = []
routes[0].routes.forEach((route: RouteItem) => {
if (route.routes) {
route.routes.forEach((item) => {
allRoutes.push(item)
})
} else {
allRoutes.push(route)
}
})
return allRoutes
}
/**
* Returns the siblings of a specific route (that is the previous and next routes).
*/
export const getRouteContext = (
_route: RouteItem,
routes: RouteItem[]
): RouteContext => {
let ctx = {}
if (!_route) return ctx
const { path } = _route
const allRoutes = getAllRoutes(routes)
for (let i = 0; i < allRoutes.length; i += 1) {
const route = allRoutes[i]
if (route && route.path === path) {
const nextRoute = allRoutes[i + 1]
const prevRoute = allRoutes[i - 1]
ctx = {
nextRoute,
prevRoute,
route: _route,
}
}
}
return ctx
}
| 17.136364 | 83 | 0.619363 | 72 | 4 | 0 | 5 | 10 | 24 | 1 | 3 | 15 | 5 | 0 | 9 | 423 | 0.021277 | 0.023641 | 0.056738 | 0.01182 | 0 | 0.069767 | 0.348837 | 0.314857 | export interface RouteItem {
title
path?
open?
heading?
sort?
routes?
new?: true
soon?
}
export interface Routes {
routes
}
export interface Page {
id
html
title
toc
}
export interface Post {
slug
content
title
date
author
toc
ogImage
coverImage
}
export interface RouteContext {
parent?
prevRoute?
nextRoute?
route?
}
export /* Example usages of 'getAllRoutes' are shown below:
getAllRoutes(routes);
*/
const getAllRoutes = (routes) => {
const allRoutes = []
routes[0].routes.forEach((route) => {
if (route.routes) {
route.routes.forEach((item) => {
allRoutes.push(item)
})
} else {
allRoutes.push(route)
}
})
return allRoutes
}
/**
* Returns the siblings of a specific route (that is the previous and next routes).
*/
export const getRouteContext = (
_route,
routes
) => {
let ctx = {}
if (!_route) return ctx
const { path } = _route
const allRoutes = getAllRoutes(routes)
for (let i = 0; i < allRoutes.length; i += 1) {
const route = allRoutes[i]
if (route && route.path === path) {
const nextRoute = allRoutes[i + 1]
const prevRoute = allRoutes[i - 1]
ctx = {
nextRoute,
prevRoute,
route: _route,
}
}
}
return ctx
}
|
c6809d0badc6c8f808466d7d4c6fca23ae804536 | 10,259 | ts | TypeScript | packages/language/combinator/core.ts | tqma113/graph-test-language | 64cc01c77687867fd2d67e99827f3945d4ea14c7 | [
"MIT"
] | null | null | null | packages/language/combinator/core.ts | tqma113/graph-test-language | 64cc01c77687867fd2d67e99827f3945d4ea14c7 | [
"MIT"
] | 2 | 2022-02-13T19:38:16.000Z | 2022-02-27T09:49:27.000Z | packages/language/combinator/core.ts | tqma113/graph-test | 64cc01c77687867fd2d67e99827f3945d4ea14c7 | [
"MIT"
] | null | null | null | type Err<T> = {
kind: 'Err'
value: T
}
type Ok<T> = {
kind: 'Ok'
value: T
}
export type Result<A, B> = Ok<A> | Err<B>
export const Err = <B>(value: B): Result<any, B> => {
return {
kind: 'Err',
value,
}
}
export const Ok = <A>(value: A): Result<A, any> => {
return {
kind: 'Ok',
value,
}
}
export type ParserStateHooks = {
getSource: () => string
getOffset: () => number
setOffset: (offset: number) => void
getError: () => string
setError: (message: string) => void
}
let currentSource = ''
let currentOffset = 0
let currentMessage = ''
const hooks: ParserStateHooks = {
getSource: () => {
return currentSource
},
getOffset: () => {
return currentOffset
},
setOffset: (newOffset: number) => {
currentOffset = newOffset
},
getError: () => {
return currentMessage
},
setError: (newMessage: string) => {
currentMessage = newMessage
},
}
export type Parser<T = any> = () => Result<T, string>
const { getSource, getOffset, setOffset, getError, setError } = hooks
export const runParser = <P extends Parser>(
parser: P,
source: string
): [
ReturnType<P>,
{
source: string
offset: number
message: string
}
] => {
currentSource = source
currentOffset = 0
currentMessage = ''
let result = parser() as ReturnType<P>
let info = {
source,
offset: currentOffset,
message: currentMessage,
}
currentSource = ''
currentMessage = ''
currentOffset = 0
return [result, info]
}
export const inject = <T>(value: T): Parser<T> => {
return () => Ok(value)
}
export const map = <A, B>(parser: Parser<A>, f: (a: A) => B): Parser<B> => {
return () => {
let result = parser()
if (result.kind === 'Err') {
return result
}
return Ok(f(result.value))
}
}
export const ap = <A, B>(
parserFn: Parser<(a: A) => B>,
parserArg: Parser<A>
): Parser<B> => {
return () => {
let resultFn = parserFn()
if (resultFn.kind === 'Err') {
return resultFn
}
let resultArg = parserArg()
if (resultArg.kind === 'Err') {
return resultArg
}
return Ok(resultFn.value(resultArg.value))
}
}
export function apply<A, B>(
parserFn: Parser<(a: A) => B>,
a: Parser<A>
): Parser<B>
export function apply<A, B, C>(
parserFn: Parser<(a: A) => (b: B) => C>,
a: Parser<A>,
b: Parser<B>
): Parser<C>
export function apply<A, B, C, D>(
parserFn: Parser<(a: A) => (b: B) => (c: C) => D>,
a: Parser<A>,
b: Parser<B>,
c: Parser<C>
): Parser<D>
export function apply<A, B, C, D, E>(
parserFn: Parser<(a: A) => (b: B) => (c: C) => (d: D) => E>,
a: Parser<A>,
b: Parser<B>,
c: Parser<C>,
d: Parser<D>
): Parser<E>
export function apply<A, B, C, D, E, F>(
parserFn: Parser<(a: A) => (b: B) => (c: C) => (d: D) => (e: E) => F>,
a: Parser<A>,
b: Parser<B>,
c: Parser<C>,
d: Parser<D>,
e: Parser<E>
): Parser<F>
export function apply<A, B, C, D, E, F>(
parserFn: Parser<(a: A) => (b: B) => (c: C) => (d: D) => (e: E) => F>,
a: Parser<A>,
b: Parser<B>,
c: Parser<C>,
d: Parser<D>,
e: Parser<E>
): Parser<F>
export function apply<A, B, C, D, E, F, G>(
parserFn: Parser<
(a: A) => (b: B) => (c: C) => (d: D) => (e: E) => (f: F) => G
>,
a: Parser<A>,
b: Parser<B>,
c: Parser<C>,
d: Parser<D>,
e: Parser<E>,
f: Parser<F>
): Parser<G>
export function apply(...args: Parser[]) {
if (args.length < 2) {
throw new Error(`Expected receiving at least two arguments`)
}
return args.reduce(ap)
}
export const item: Parser<string> = () => {
let source = getSource()
let offset = getOffset()
if (offset >= source.length) {
return Err('EOF')
}
setOffset(offset + 1)
return Ok(source[offset])
}
export const satisfy = (predicate: (a: string) => boolean): Parser<string> => {
return () => {
let result = item()
if (result.kind === 'Err') {
return result
}
if (predicate(result.value)) {
return result
} else {
return Err(`Unmatched char ${result.value}`)
}
}
}
export const digit = satisfy((c) => c >= '0' && c <= '9')
export const lower = satisfy((c) => c >= 'a' && c <= 'z')
export const uppper = satisfy((c) => c >= 'A' && c <= 'Z')
export const char = (target: string) => {
return satisfy((c) => c === target)
}
export const notChar = (x: string) => {
return satisfy((value) => value !== x)
}
export const comma = char(',')
export const semicolon = char(':')
export const either = <A, B>(
parserA: Parser<A>,
parserB: Parser<B>
): Parser<A | B> => {
return () => {
let offset = getOffset()
let resultA = parserA()
if (resultA.kind === 'Err') {
setOffset(offset)
return parserB()
}
return resultA
}
}
export function oneOf<A>(parserA: Parser<A>): Parser<A>
export function oneOf<A, B>(
parserA: Parser<A>,
parserB: Parser<B>
): Parser<A | B>
export function oneOf<A, B, C>(
parserA: Parser<A>,
parserB: Parser<B>,
parserC: Parser<C>
): Parser<A | B | C>
export function oneOf<A, B, C, D>(
parserA: Parser<A>,
parserB: Parser<B>,
parserC: Parser<C>,
parserD: Parser<D>
): Parser<A | B | C | D>
export function oneOf<A, B, C, D, E>(
parserA: Parser<A>,
parserB: Parser<B>,
parserC: Parser<C>,
parserD: Parser<D>,
parserE: Parser<E>
): Parser<A | B | C | D | E>
export function oneOf<A, B, C, D, E, F>(
parserA: Parser<A>,
parserB: Parser<B>,
parserC: Parser<C>,
parserD: Parser<D>,
parserE: Parser<E>,
parserF: Parser<F>
): Parser<A | B | C | D | E | F>
export function oneOf<A, B, C, D, E, F, G>(
parserA: Parser<A>,
parserB: Parser<B>,
parserC: Parser<C>,
parserD: Parser<D>,
parserE: Parser<E>,
parserF: Parser<F>,
parserG: Parser<G>
): Parser<A | B | C | D | E | F | G>
export function oneOf(...parsers: Parser[]) {
if (parsers.length < 2) {
throw new Error(
`Expected received at least two parsers, but got ${parsers.length}`
)
}
return parsers.reduce(either)
}
export const whiteSpace = satisfy((x) => {
if (x === ' ') return true
if (x === '\n') return true
if (x === '\t') return true
if (x === '\r') return true
return false
})
export const many = <T>(parser: Parser<T>): Parser<T[]> => {
return () => {
let list: T[] = []
while (true) {
let offset = getOffset()
let result = parser()
if (result.kind === 'Err') {
setError(result.value)
setOffset(offset)
return Ok(list)
} else {
list[list.length] = result.value
}
}
}
}
export const many1 = <T>(parser: Parser<T>): Parser<T[]> => {
let manyParser = many(parser)
return () => {
let result = manyParser()
if (result.kind === 'Err') {
return result
}
if (result.value.length === 0) {
return Err(getError() || `at least match once`)
}
return result
}
}
export const whiteSpaces = many1(whiteSpace)
// tslint:disable-next-line: variable-name
export const string = (str: string): Parser<string> => {
return () => {
for (let i = 0; i < str.length; i++) {
let result = item()
if (result.kind === 'Err') {
return result
}
if (result.value !== str[i]) {
return Err(`Unmatched string: ${str}`)
}
}
return Ok(str)
}
}
export const letter = either(lower, uppper)
export const digits = many1(digit)
export const positiveInteger: Parser<number> = () => {
let result = digits()
if (result.kind === 'Err') {
return result
}
let value = Number(result.value.join(''))
return Ok(value)
}
export const negativeInteger: Parser<number> = () => {
let charResult = char('-')()
if (charResult.kind === 'Err') {
return charResult
}
let intResult = positiveInteger()
if (intResult.kind === 'Err') {
return intResult
}
return Ok(-intResult.value)
}
export const integer = either(positiveInteger, negativeInteger)
export const dot = char('.')
export const positiveFloat: Parser<number> = () => {
let digitsResult0 = digits()
if (digitsResult0.kind === 'Err') {
return digitsResult0
}
let dotResult = dot()
if (dotResult.kind === 'Err') {
return dotResult
}
let digitsResult1 = digits()
if (digitsResult1.kind === 'Err') {
return digitsResult1
}
let value = Number(
digitsResult0.value.join('') +
dotResult.value +
digitsResult1.value.join('')
)
return Ok(value)
}
export const negativeFloat: Parser<number> = () => {
let charResult = char('-')()
if (charResult.kind === 'Err') {
return charResult
}
let floatResult = positiveFloat()
if (floatResult.kind === 'Err') {
return floatResult
}
return Ok(-floatResult.value)
}
export const float = either(positiveFloat, negativeFloat)
// tslint:disable-next-line: variable-name
export const number = either(float, integer)
export const separateBy = <A, S>(
parser: Parser<A>,
separator: Parser<S>
): Parser<A[]> => {
let pair: Parser<A> = () => {
let separatorResult = separator()
if (separatorResult.kind === 'Err') {
return separatorResult
}
return parser()
}
let pairs = many(pair)
return () => {
let result = parser()
if (result.kind === 'Err') {
return result
}
let pairsResult = pairs()
if (pairsResult.kind === 'Err') {
return pairsResult
}
let value = [result.value, ...pairsResult.value]
return Ok(value)
}
}
export const bracket = <O, A, C>(
open: Parser<O>,
parser: Parser<A>,
close: Parser<C>
): Parser<A> => () => {
let openResult = open()
if (openResult.kind === 'Err') {
return openResult
}
let parserResult = parser()
if (parserResult.kind === 'Err') {
return parserResult
}
let closeResult = close()
if (closeResult.kind === 'Err') {
return closeResult
}
return parserResult
}
export const aroundBy = <A, S>(
parser: Parser<A>,
surround: Parser<S>
): Parser<A> => {
return bracket(many(surround), parser, many(surround))
}
export const aroundBySpace = <A>(parser: Parser<A>): Parser<A> => {
return aroundBy(parser, whiteSpace)
}
export const stringLiteral = map(
bracket(char('"'), many(notChar('"')), char('"')),
(list) => list.join('')
)
| 19.175701 | 79 | 0.575007 | 417 | 47 | 14 | 97 | 77 | 9 | 14 | 3 | 26 | 5 | 1 | 6.361702 | 3,333 | 0.043204 | 0.023102 | 0.0027 | 0.0015 | 0.0003 | 0.012295 | 0.106557 | 0.352265 | type Err<T> = {
kind
value
}
type Ok<T> = {
kind
value
}
export type Result<A, B> = Ok<A> | Err<B>
export /* Example usages of 'Err' are shown below:
;
Err('EOF');
Err(`Unmatched char ${result.value}`);
Err(getError() || `at least match once`);
Err(`Unmatched string: ${str}`);
*/
const Err = <B>(value) => {
return {
kind: 'Err',
value,
}
}
export /* Example usages of 'Ok' are shown below:
;
Ok(value);
Ok(f(result.value));
Ok(resultFn.value(resultArg.value));
Ok(source[offset]);
Ok(list);
Ok(str);
Ok(-intResult.value);
Ok(-floatResult.value);
*/
const Ok = <A>(value) => {
return {
kind: 'Ok',
value,
}
}
export type ParserStateHooks = {
getSource
getOffset
setOffset
getError
setError
}
let currentSource = ''
let currentOffset = 0
let currentMessage = ''
const hooks = {
getSource: () => {
return currentSource
},
getOffset: () => {
return currentOffset
},
setOffset: (newOffset) => {
currentOffset = newOffset
},
getError: () => {
return currentMessage
},
setError: (newMessage) => {
currentMessage = newMessage
},
}
export type Parser<T = any> = () => Result<T, string>
const { getSource, getOffset, setOffset, getError, setError } = hooks
export const runParser = <P extends Parser>(
parser,
source
) => {
currentSource = source
currentOffset = 0
currentMessage = ''
let result = parser() as ReturnType<P>
let info = {
source,
offset: currentOffset,
message: currentMessage,
}
currentSource = ''
currentMessage = ''
currentOffset = 0
return [result, info]
}
export const inject = <T>(value) => {
return () => Ok(value)
}
export /* Example usages of 'map' are shown below:
map(bracket(char('"'), many(notChar('"')), char('"')), (list) => list.join(''));
*/
const map = <A, B>(parser, f) => {
return () => {
let result = parser()
if (result.kind === 'Err') {
return result
}
return Ok(f(result.value))
}
}
export /* Example usages of 'ap' are shown below:
args.reduce(ap);
*/
const ap = <A, B>(
parserFn,
parserArg
) => {
return () => {
let resultFn = parserFn()
if (resultFn.kind === 'Err') {
return resultFn
}
let resultArg = parserArg()
if (resultArg.kind === 'Err') {
return resultArg
}
return Ok(resultFn.value(resultArg.value))
}
}
export function apply<A, B>(
parserFn,
a
)
export function apply<A, B, C>(
parserFn,
a,
b
)
export function apply<A, B, C, D>(
parserFn,
a,
b,
c
)
export function apply<A, B, C, D, E>(
parserFn,
a,
b,
c,
d
)
export function apply<A, B, C, D, E, F>(
parserFn,
a,
b,
c,
d,
e
)
export function apply<A, B, C, D, E, F>(
parserFn,
a,
b,
c,
d,
e
)
export function apply<A, B, C, D, E, F, G>(
parserFn,
a,
b,
c,
d,
e,
f
)
export function apply(...args) {
if (args.length < 2) {
throw new Error(`Expected receiving at least two arguments`)
}
return args.reduce(ap)
}
export /* Example usages of 'item' are shown below:
item();
*/
const item = () => {
let source = getSource()
let offset = getOffset()
if (offset >= source.length) {
return Err('EOF')
}
setOffset(offset + 1)
return Ok(source[offset])
}
export /* Example usages of 'satisfy' are shown below:
satisfy((c) => c >= '0' && c <= '9');
satisfy((c) => c >= 'a' && c <= 'z');
satisfy((c) => c >= 'A' && c <= 'Z');
satisfy((c) => c === target);
satisfy((value) => value !== x);
satisfy((x) => {
if (x === ' ')
return true;
if (x === '\n')
return true;
if (x === '\t')
return true;
if (x === '\r')
return true;
return false;
});
*/
const satisfy = (predicate) => {
return () => {
let result = item()
if (result.kind === 'Err') {
return result
}
if (predicate(result.value)) {
return result
} else {
return Err(`Unmatched char ${result.value}`)
}
}
}
export const digit = satisfy((c) => c >= '0' && c <= '9')
export const lower = satisfy((c) => c >= 'a' && c <= 'z')
export const uppper = satisfy((c) => c >= 'A' && c <= 'Z')
export /* Example usages of 'char' are shown below:
char(',');
char(':');
char('-')();
char('.');
map(bracket(char('"'), many(notChar('"')), char('"')), (list) => list.join(''));
*/
const char = (target) => {
return satisfy((c) => c === target)
}
export /* Example usages of 'notChar' are shown below:
map(bracket(char('"'), many(notChar('"')), char('"')), (list) => list.join(''));
*/
const notChar = (x) => {
return satisfy((value) => value !== x)
}
export const comma = char(',')
export const semicolon = char(':')
export /* Example usages of 'either' are shown below:
parsers.reduce(either);
either(lower, uppper);
either(positiveInteger, negativeInteger);
either(positiveFloat, negativeFloat);
either(float, integer);
*/
const either = <A, B>(
parserA,
parserB
) => {
return () => {
let offset = getOffset()
let resultA = parserA()
if (resultA.kind === 'Err') {
setOffset(offset)
return parserB()
}
return resultA
}
}
export function oneOf<A>(parserA)
export function oneOf<A, B>(
parserA,
parserB
)
export function oneOf<A, B, C>(
parserA,
parserB,
parserC
)
export function oneOf<A, B, C, D>(
parserA,
parserB,
parserC,
parserD
)
export function oneOf<A, B, C, D, E>(
parserA,
parserB,
parserC,
parserD,
parserE
)
export function oneOf<A, B, C, D, E, F>(
parserA,
parserB,
parserC,
parserD,
parserE,
parserF
)
export function oneOf<A, B, C, D, E, F, G>(
parserA,
parserB,
parserC,
parserD,
parserE,
parserF,
parserG
)
export function oneOf(...parsers) {
if (parsers.length < 2) {
throw new Error(
`Expected received at least two parsers, but got ${parsers.length}`
)
}
return parsers.reduce(either)
}
export const whiteSpace = satisfy((x) => {
if (x === ' ') return true
if (x === '\n') return true
if (x === '\t') return true
if (x === '\r') return true
return false
})
export /* Example usages of 'many' are shown below:
many(parser);
many(pair);
bracket(many(surround), parser, many(surround));
map(bracket(char('"'), many(notChar('"')), char('"')), (list) => list.join(''));
*/
const many = <T>(parser) => {
return () => {
let list = []
while (true) {
let offset = getOffset()
let result = parser()
if (result.kind === 'Err') {
setError(result.value)
setOffset(offset)
return Ok(list)
} else {
list[list.length] = result.value
}
}
}
}
export /* Example usages of 'many1' are shown below:
many1(whiteSpace);
many1(digit);
*/
const many1 = <T>(parser) => {
let manyParser = many(parser)
return () => {
let result = manyParser()
if (result.kind === 'Err') {
return result
}
if (result.value.length === 0) {
return Err(getError() || `at least match once`)
}
return result
}
}
export const whiteSpaces = many1(whiteSpace)
// tslint:disable-next-line: variable-name
export const string = (str) => {
return () => {
for (let i = 0; i < str.length; i++) {
let result = item()
if (result.kind === 'Err') {
return result
}
if (result.value !== str[i]) {
return Err(`Unmatched string: ${str}`)
}
}
return Ok(str)
}
}
export const letter = either(lower, uppper)
export const digits = many1(digit)
export /* Example usages of 'positiveInteger' are shown below:
positiveInteger();
either(positiveInteger, negativeInteger);
*/
const positiveInteger = () => {
let result = digits()
if (result.kind === 'Err') {
return result
}
let value = Number(result.value.join(''))
return Ok(value)
}
export /* Example usages of 'negativeInteger' are shown below:
either(positiveInteger, negativeInteger);
*/
const negativeInteger = () => {
let charResult = char('-')()
if (charResult.kind === 'Err') {
return charResult
}
let intResult = positiveInteger()
if (intResult.kind === 'Err') {
return intResult
}
return Ok(-intResult.value)
}
export const integer = either(positiveInteger, negativeInteger)
export const dot = char('.')
export /* Example usages of 'positiveFloat' are shown below:
positiveFloat();
either(positiveFloat, negativeFloat);
*/
const positiveFloat = () => {
let digitsResult0 = digits()
if (digitsResult0.kind === 'Err') {
return digitsResult0
}
let dotResult = dot()
if (dotResult.kind === 'Err') {
return dotResult
}
let digitsResult1 = digits()
if (digitsResult1.kind === 'Err') {
return digitsResult1
}
let value = Number(
digitsResult0.value.join('') +
dotResult.value +
digitsResult1.value.join('')
)
return Ok(value)
}
export /* Example usages of 'negativeFloat' are shown below:
either(positiveFloat, negativeFloat);
*/
const negativeFloat = () => {
let charResult = char('-')()
if (charResult.kind === 'Err') {
return charResult
}
let floatResult = positiveFloat()
if (floatResult.kind === 'Err') {
return floatResult
}
return Ok(-floatResult.value)
}
export const float = either(positiveFloat, negativeFloat)
// tslint:disable-next-line: variable-name
export const number = either(float, integer)
export const separateBy = <A, S>(
parser,
separator
) => {
/* Example usages of 'pair' are shown below:
many(pair);
*/
let pair = () => {
let separatorResult = separator()
if (separatorResult.kind === 'Err') {
return separatorResult
}
return parser()
}
let pairs = many(pair)
return () => {
let result = parser()
if (result.kind === 'Err') {
return result
}
let pairsResult = pairs()
if (pairsResult.kind === 'Err') {
return pairsResult
}
let value = [result.value, ...pairsResult.value]
return Ok(value)
}
}
export /* Example usages of 'bracket' are shown below:
bracket(many(surround), parser, many(surround));
map(bracket(char('"'), many(notChar('"')), char('"')), (list) => list.join(''));
*/
const bracket = <O, A, C>(
open,
parser,
close
) => () => {
let openResult = open()
if (openResult.kind === 'Err') {
return openResult
}
let parserResult = parser()
if (parserResult.kind === 'Err') {
return parserResult
}
let closeResult = close()
if (closeResult.kind === 'Err') {
return closeResult
}
return parserResult
}
export /* Example usages of 'aroundBy' are shown below:
aroundBy(parser, whiteSpace);
*/
const aroundBy = <A, S>(
parser,
surround
) => {
return bracket(many(surround), parser, many(surround))
}
export const aroundBySpace = <A>(parser) => {
return aroundBy(parser, whiteSpace)
}
export const stringLiteral = map(
bracket(char('"'), many(notChar('"')), char('"')),
(list) => list.join('')
)
|
c68b703282d188f9482f6f5037ca165aa9b9338b | 2,142 | ts | TypeScript | frontend/utils/models/repo.ts | 24HeuresINSA/Overbookd | 99088b4a0e023b3e9477e6826b56ccc3361b166d | [
"Apache-2.0"
] | 1 | 2022-01-26T13:29:57.000Z | 2022-01-26T13:29:57.000Z | frontend/utils/models/repo.ts | 24HeuresINSA/Overbookd | 99088b4a0e023b3e9477e6826b56ccc3361b166d | [
"Apache-2.0"
] | null | null | null | frontend/utils/models/repo.ts | 24HeuresINSA/Overbookd | 99088b4a0e023b3e9477e6826b56ccc3361b166d | [
"Apache-2.0"
] | null | null | null | export class BroadcastNotif {
link: string;
team: string;
message: string;
date: Date;
type: string;
constructor() {
this.date = new Date();
this.link = "";
this.team = "";
this.message = "";
this.type = "";
}
}
export interface Expense {
type: "expense";
from: string;
to: null;
amount: number;
context: string;
createdAt: Date;
}
export interface Deposit {
type: "deposit";
from: string;
to: null;
amount: number;
context: null;
createdAt: Date;
}
export interface Transfer {
type: "transfer";
from: string;
to: string;
amount: number;
context: string;
createdAt: Date;
isValid: boolean;
}
export type Transaction = Expense | Deposit | Transfer;
export interface Notification {
link: string;
message: string;
team: string;
date: string;
type: string;
index?: number;
}
export interface User {
_id: string;
team: string[];
friends: any[];
nickname?: string;
firstname: string;
lastname: string;
username?: string;
isValid: boolean;
birthdate: string;
email: string;
phone: number;
__v: number;
notifications: Notification[];
clicks?: number;
transactionHistory?: Transaction[];
balance?: number;
charisma?: number;
availabilities: string[];
hasDriverLicense: boolean;
}
export interface availability {
name: string;
description: string;
days: daysFrame[];
}
export interface daysFrame {
date: string;
frames: timeframe[];
}
export interface timeframe {
start: string;
end: string;
charisma: string;
isSelected: boolean;
}
export interface FriendRequest {
type: "friendRequest";
message: string;
from: string;
date: Date;
data: {
username: string;
id: string;
};
}
export interface FriendRequestData {
to: string; // _id
data: FriendRequest;
}
export interface Timeslot {
_id?: string;
groupTitle: string;
groupDescription?: string;
timeFrame: {
start: Date;
end: Date;
};
charisma: number;
forHardOnly?: boolean;
}
export interface location {
_id: string;
name: string;
latitude?: number;
longitude?: number;
neededBy: string[];
}
| 16.351145 | 55 | 0.660131 | 116 | 1 | 0 | 0 | 0 | 76 | 0 | 1 | 58 | 14 | 0 | 5 | 594 | 0.001684 | 0 | 0.127946 | 0.023569 | 0 | 0.012987 | 0.753247 | 0.210804 | export class BroadcastNotif {
link;
team;
message;
date;
type;
constructor() {
this.date = new Date();
this.link = "";
this.team = "";
this.message = "";
this.type = "";
}
}
export interface Expense {
type;
from;
to;
amount;
context;
createdAt;
}
export interface Deposit {
type;
from;
to;
amount;
context;
createdAt;
}
export interface Transfer {
type;
from;
to;
amount;
context;
createdAt;
isValid;
}
export type Transaction = Expense | Deposit | Transfer;
export interface Notification {
link;
message;
team;
date;
type;
index?;
}
export interface User {
_id;
team;
friends;
nickname?;
firstname;
lastname;
username?;
isValid;
birthdate;
email;
phone;
__v;
notifications;
clicks?;
transactionHistory?;
balance?;
charisma?;
availabilities;
hasDriverLicense;
}
export interface availability {
name;
description;
days;
}
export interface daysFrame {
date;
frames;
}
export interface timeframe {
start;
end;
charisma;
isSelected;
}
export interface FriendRequest {
type;
message;
from;
date;
data;
}
export interface FriendRequestData {
to; // _id
data;
}
export interface Timeslot {
_id?;
groupTitle;
groupDescription?;
timeFrame;
charisma;
forHardOnly?;
}
export interface location {
_id;
name;
latitude?;
longitude?;
neededBy;
}
|
c6d5ffda245e6c24ad9fa341ce408a2da2efaa93 | 7,113 | ts | TypeScript | projects/nge-ide/core/src/utils/paths.ts | cisstech/nge-ide | c6b87c602b69b0815d44d1b3b60e02bd844d13e6 | [
"MIT"
] | 1 | 2022-02-01T19:05:28.000Z | 2022-02-01T19:05:28.000Z | projects/nge-ide/core/src/utils/paths.ts | mciissee/nge-ide | bbb25d64f41a7bb7f212db32f0909f1fee0f0f68 | [
"MIT"
] | null | null | null | projects/nge-ide/core/src/utils/paths.ts | mciissee/nge-ide | bbb25d64f41a7bb7f212db32f0909f1fee0f0f68 | [
"MIT"
] | null | null | null | const BINARIES = [
"3dm",
"3ds",
"3g2",
"3gp",
"7z",
"a",
"aac",
"adp",
"ai",
"aif",
"aiff",
"alz",
"ape",
"apk",
"appimage",
"ar",
"arj",
"asf",
"au",
"avi",
"bak",
"baml",
"bh",
"bin",
"bk",
"bmp",
"btif",
"bz2",
"bzip2",
"cab",
"caf",
"cgm",
"class",
"cmx",
"cpio",
"cr2",
"cur",
"dat",
"dcm",
"deb",
"dex",
"djvu",
"dll",
"dmg",
"dng",
"doc",
"docm",
"docx",
"dot",
"dotm",
"dra",
"DS_Store",
"dsk",
"dts",
"dtshd",
"dvb",
"dwg",
"dxf",
"ecelp4800",
"ecelp7470",
"ecelp9600",
"egg",
"eol",
"eot",
"epub",
"exe",
"f4v",
"fbs",
"fh",
"fla",
"flac",
"flatpak",
"fli",
"flv",
"fpx",
"fst",
"fvt",
"g3",
"gh",
"gif",
"graffle",
"gz",
"gzip",
"h261",
"h263",
"h264",
"icns",
"ico",
"ief",
"img",
"ipa",
"iso",
"jar",
"jpeg",
"jpg",
"jpgv",
"jpm",
"jxr",
"key",
"ktx",
"lha",
"lib",
"lvp",
"lz",
"lzh",
"lzma",
"lzo",
"m3u",
"m4a",
"m4v",
"mar",
"mdi",
"mht",
"mid",
"midi",
"mj2",
"mka",
"mkv",
"mmr",
"mng",
"mobi",
"mov",
"movie",
"mp3",
"mp4",
"mp4a",
"mpeg",
"mpg",
"mpga",
"mxu",
"nef",
"npx",
"numbers",
"nupkg",
"o",
"odp",
"ods",
"odt",
"oga",
"ogg",
"ogv",
"otf",
"ott",
"pages",
"pbm",
"pcx",
"pdb",
"pdf",
"pea",
"pgm",
"pic",
"png",
"pnm",
"pot",
"potm",
"potx",
"ppa",
"ppam",
"ppm",
"pps",
"ppsm",
"ppsx",
"ppt",
"pptm",
"pptx",
"psd",
"pya",
"pyc",
"pyo",
"pyv",
"qt",
"rar",
"ras",
"raw",
"resources",
"rgb",
"rip",
"rlc",
"rmf",
"rmvb",
"rpm",
"rtf",
"rz",
"s3m",
"s7z",
"scpt",
"sgi",
"shar",
"snap",
"sil",
"sketch",
"slk",
"smv",
"snk",
"so",
"stl",
"suo",
"sub",
"swf",
"tar",
"tbz",
"tbz2",
"tga",
"tgz",
"thmx",
"tif",
"tiff",
"tlz",
"ttc",
"ttf",
"txz",
"udf",
"uvh",
"uvi",
"uvm",
"uvp",
"uvs",
"uvu",
"viv",
"vob",
"war",
"wav",
"wax",
"wbmp",
"wdp",
"weba",
"webm",
"webp",
"whl",
"wim",
"wm",
"wma",
"wmv",
"wmx",
"woff",
"woff2",
"wrm",
"wvx",
"xbm",
"xif",
"xla",
"xlam",
"xls",
"xlsb",
"xlsm",
"xlsx",
"xlt",
"xltm",
"xltx",
"xm",
"xmind",
"xpi",
"xpm",
"xwd",
"xz",
"z",
"zip",
"zipx"
];
export class Paths {
/**
* Returns the extension of the path (in lowercase), from the last '.' to end of string in the last portion of the path.
* If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string
* @param path the path to evaluate
* @returns the extension in lowercase (without a dot) or an empty string.
*/
static extname(path: string) {
if (path == null) {
throw new ReferenceError('"path" is required');
}
const base = Paths.basename(path);
if (!base) {
return base;
}
if (base.startsWith('.')) {
return '';
}
const dotIndex = base.lastIndexOf('.');
if (dotIndex === -1) {
return '';
}
return base.substring(dotIndex + 1).toLowerCase();
}
/**
* Returns the directory name of a path. Similar to the Unix dirname command.
* @param path the path to evaluate
*/
static dirname(path: string) {
if (path == null) {
throw new ReferenceError('"path" is required');
}
path = Paths.normalize(path.replace(/\\/g, '/'));
let head = path.slice(0, path.lastIndexOf('/') + 1);
if (head && !head.match(/^\/*$/g)) {
head = head.replace(/\/*$/g, '');
}
return head;
}
/**
* Returns the last portion of a path. Similar to the Unix basename command.
* Often used to extract the file name from a fully qualified path.
* @param the path to evaluate.
*/
static basename(path: string) {
if (path == null) {
throw new ReferenceError('"path" is required');
}
path = Paths.normalize(path.replace(/\\/g, '/'));
return path.slice(path.lastIndexOf('/') + 1, path.length);
}
/**
* Join several segments into one path
* @param parts: the segments
* @param sep: path separator
*/
static join(parts: string[], sep: string = '') {
if (parts == null) {
throw new ReferenceError('"parts" is required');
}
sep = sep || '/';
const separator = sep || '/';
const replace = new RegExp(separator + '{1,}', 'g');
return parts.join(separator).replace(replace, separator);
}
// https://github.com/jonschlinkert/normalize-path/blob/master/index.js
/**
* Normalize slashes in a file path to be posix/unix-like forward slashes.
* Also condenses repeat slashes to a single slash and removes and trailing slashes, unless disabled.
* @param path path to normalize
* @param stripTrailing remove trailing slashes
*/
static normalize(path: string, stripTrailing: boolean = true) {
if (typeof path !== 'string') {
throw new TypeError('expected path to be a string');
}
if (path === '\\' || path === '/') {
return '/';
}
const len = path.length;
if (len <= 1) {
return path;
}
// ensure that win32 namespaces has two leading slashes, so that the path is
// handled properly by the win32 version of path.parse() after being normalized
// https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
let prefix = '';
if (len > 4 && path[3] === '\\') {
const ch = path[2];
if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
path = path.slice(2);
prefix = '//';
}
}
const segs = path.split(/[/\\]+/);
if (stripTrailing !== false && segs[segs.length - 1] === '') {
segs.pop();
}
return prefix + segs.join('/');
}
static isAbsolutePath(path: string): boolean {
return !!path && path[0] === '/';
}
/**
* Determines whether the given path is a binary file path.
* @param path the path to test.
* @returns
*/
static isBinaryFile(path: string): boolean {
return BINARIES.includes(Paths.extname(path));
}
}
| 18.332474 | 126 | 0.437509 | 337 | 7 | 0 | 9 | 10 | 0 | 4 | 0 | 11 | 1 | 1 | 8.714286 | 2,212 | 0.007233 | 0.004521 | 0 | 0.000452 | 0.000452 | 0 | 0.423077 | 0.202861 | const BINARIES = [
"3dm",
"3ds",
"3g2",
"3gp",
"7z",
"a",
"aac",
"adp",
"ai",
"aif",
"aiff",
"alz",
"ape",
"apk",
"appimage",
"ar",
"arj",
"asf",
"au",
"avi",
"bak",
"baml",
"bh",
"bin",
"bk",
"bmp",
"btif",
"bz2",
"bzip2",
"cab",
"caf",
"cgm",
"class",
"cmx",
"cpio",
"cr2",
"cur",
"dat",
"dcm",
"deb",
"dex",
"djvu",
"dll",
"dmg",
"dng",
"doc",
"docm",
"docx",
"dot",
"dotm",
"dra",
"DS_Store",
"dsk",
"dts",
"dtshd",
"dvb",
"dwg",
"dxf",
"ecelp4800",
"ecelp7470",
"ecelp9600",
"egg",
"eol",
"eot",
"epub",
"exe",
"f4v",
"fbs",
"fh",
"fla",
"flac",
"flatpak",
"fli",
"flv",
"fpx",
"fst",
"fvt",
"g3",
"gh",
"gif",
"graffle",
"gz",
"gzip",
"h261",
"h263",
"h264",
"icns",
"ico",
"ief",
"img",
"ipa",
"iso",
"jar",
"jpeg",
"jpg",
"jpgv",
"jpm",
"jxr",
"key",
"ktx",
"lha",
"lib",
"lvp",
"lz",
"lzh",
"lzma",
"lzo",
"m3u",
"m4a",
"m4v",
"mar",
"mdi",
"mht",
"mid",
"midi",
"mj2",
"mka",
"mkv",
"mmr",
"mng",
"mobi",
"mov",
"movie",
"mp3",
"mp4",
"mp4a",
"mpeg",
"mpg",
"mpga",
"mxu",
"nef",
"npx",
"numbers",
"nupkg",
"o",
"odp",
"ods",
"odt",
"oga",
"ogg",
"ogv",
"otf",
"ott",
"pages",
"pbm",
"pcx",
"pdb",
"pdf",
"pea",
"pgm",
"pic",
"png",
"pnm",
"pot",
"potm",
"potx",
"ppa",
"ppam",
"ppm",
"pps",
"ppsm",
"ppsx",
"ppt",
"pptm",
"pptx",
"psd",
"pya",
"pyc",
"pyo",
"pyv",
"qt",
"rar",
"ras",
"raw",
"resources",
"rgb",
"rip",
"rlc",
"rmf",
"rmvb",
"rpm",
"rtf",
"rz",
"s3m",
"s7z",
"scpt",
"sgi",
"shar",
"snap",
"sil",
"sketch",
"slk",
"smv",
"snk",
"so",
"stl",
"suo",
"sub",
"swf",
"tar",
"tbz",
"tbz2",
"tga",
"tgz",
"thmx",
"tif",
"tiff",
"tlz",
"ttc",
"ttf",
"txz",
"udf",
"uvh",
"uvi",
"uvm",
"uvp",
"uvs",
"uvu",
"viv",
"vob",
"war",
"wav",
"wax",
"wbmp",
"wdp",
"weba",
"webm",
"webp",
"whl",
"wim",
"wm",
"wma",
"wmv",
"wmx",
"woff",
"woff2",
"wrm",
"wvx",
"xbm",
"xif",
"xla",
"xlam",
"xls",
"xlsb",
"xlsm",
"xlsx",
"xlt",
"xltm",
"xltx",
"xm",
"xmind",
"xpi",
"xpm",
"xwd",
"xz",
"z",
"zip",
"zipx"
];
export class Paths {
/**
* Returns the extension of the path (in lowercase), from the last '.' to end of string in the last portion of the path.
* If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string
* @param path the path to evaluate
* @returns the extension in lowercase (without a dot) or an empty string.
*/
static extname(path) {
if (path == null) {
throw new ReferenceError('"path" is required');
}
const base = Paths.basename(path);
if (!base) {
return base;
}
if (base.startsWith('.')) {
return '';
}
const dotIndex = base.lastIndexOf('.');
if (dotIndex === -1) {
return '';
}
return base.substring(dotIndex + 1).toLowerCase();
}
/**
* Returns the directory name of a path. Similar to the Unix dirname command.
* @param path the path to evaluate
*/
static dirname(path) {
if (path == null) {
throw new ReferenceError('"path" is required');
}
path = Paths.normalize(path.replace(/\\/g, '/'));
let head = path.slice(0, path.lastIndexOf('/') + 1);
if (head && !head.match(/^\/*$/g)) {
head = head.replace(/\/*$/g, '');
}
return head;
}
/**
* Returns the last portion of a path. Similar to the Unix basename command.
* Often used to extract the file name from a fully qualified path.
* @param the path to evaluate.
*/
static basename(path) {
if (path == null) {
throw new ReferenceError('"path" is required');
}
path = Paths.normalize(path.replace(/\\/g, '/'));
return path.slice(path.lastIndexOf('/') + 1, path.length);
}
/**
* Join several segments into one path
* @param parts: the segments
* @param sep: path separator
*/
static join(parts, sep = '') {
if (parts == null) {
throw new ReferenceError('"parts" is required');
}
sep = sep || '/';
const separator = sep || '/';
const replace = new RegExp(separator + '{1,}', 'g');
return parts.join(separator).replace(replace, separator);
}
// https://github.com/jonschlinkert/normalize-path/blob/master/index.js
/**
* Normalize slashes in a file path to be posix/unix-like forward slashes.
* Also condenses repeat slashes to a single slash and removes and trailing slashes, unless disabled.
* @param path path to normalize
* @param stripTrailing remove trailing slashes
*/
static normalize(path, stripTrailing = true) {
if (typeof path !== 'string') {
throw new TypeError('expected path to be a string');
}
if (path === '\\' || path === '/') {
return '/';
}
const len = path.length;
if (len <= 1) {
return path;
}
// ensure that win32 namespaces has two leading slashes, so that the path is
// handled properly by the win32 version of path.parse() after being normalized
// https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
let prefix = '';
if (len > 4 && path[3] === '\\') {
const ch = path[2];
if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
path = path.slice(2);
prefix = '//';
}
}
const segs = path.split(/[/\\]+/);
if (stripTrailing !== false && segs[segs.length - 1] === '') {
segs.pop();
}
return prefix + segs.join('/');
}
static isAbsolutePath(path) {
return !!path && path[0] === '/';
}
/**
* Determines whether the given path is a binary file path.
* @param path the path to test.
* @returns
*/
static isBinaryFile(path) {
return BINARIES.includes(Paths.extname(path));
}
}
|
c6df44611ee0c019489696962b3397f9bec5493b | 2,447 | ts | TypeScript | src/model.ts | fraenkelc/minecraft-perf-viewer | 934977d15566edc0b7772f1d69bfb62c13d2830b | [
"Apache-2.0"
] | null | null | null | src/model.ts | fraenkelc/minecraft-perf-viewer | 934977d15566edc0b7772f1d69bfb62c13d2830b | [
"Apache-2.0"
] | 21 | 2022-01-11T12:25:45.000Z | 2022-03-28T12:35:56.000Z | src/model.ts | fraenkelc/minecraft-perf-viewer | 934977d15566edc0b7772f1d69bfb62c13d2830b | [
"Apache-2.0"
] | null | null | null | const profilePattern =
/(?:^\[(\d+)\][ |]*(#\w+) (\d+)\/(\d+)$)|(?:^\[(\d+)\][ |]*([^(]+)\((\d+)\/(\d+)\) - ([\d.]+)%\/([\d.]+)%$)/;
const startPattern = /--- BEGIN PROFILE DUMP ---/;
const endPattern = /--- END PROFILE DUMP ---/;
export class ProfileReport {
root: ProfileLine = new Root();
constructor(text: string) {
this.parseProfileReport(text);
}
private parseProfileReport(text: string): void {
const lines = text.split(/\r?\n/);
let parent: ProfileLine = this.root;
let previous: ProfileLine = this.root;
let lastLevel = 0;
let foundStart = false;
for (const line of lines) {
if (!foundStart) {
if (!startPattern.exec(line)) continue;
foundStart = true;
continue;
}
if (endPattern.exec(line)) break;
let m;
if ((m = profilePattern.exec(line)) != null) {
const level = parseInt(m[1] ?? m[5], 10);
if (level < lastLevel) {
while (level <= parent.level && parent != this.root)
parent = parent.parent;
} else if (level > lastLevel) {
parent = previous;
}
lastLevel = level;
let current;
if (m[1]) {
// counter
current = {
parent,
text: m[2],
children: [],
level,
num1: parseInt(m[3]),
num2: parseInt(m[4]),
} as CounterLine;
} else if (m[5]) {
// pct
current = {
parent,
text: m[6],
children: [],
level,
num1: parseInt(m[7]),
num2: parseInt(m[8]),
pctParent: parseFloat(m[9]),
pctTotal: parseFloat(m[10]),
} as PctLine;
} else continue;
parent.children.push(current);
previous = current;
}
}
}
}
// [00] tick (86/1) - 95.17%/95.17%
// ---- text (num1/num2) - pctParent / ptcTotal
export interface ProfileLine {
parent: ProfileLine;
level: number;
children: ProfileLine[];
text: string;
}
class Root implements ProfileLine {
parent = this;
level = -1;
children: ProfileLine[] = [];
text = 'Profile Report';
}
export interface PctLine extends ProfileLine {
parent: ProfileLine;
num1: number;
num2: number;
pctParent: number;
pctTotal: number;
}
export interface CounterLine extends ProfileLine {
parent: ProfileLine;
num1: number;
num2: number;
}
| 24.969388 | 111 | 0.523089 | 84 | 2 | 0 | 2 | 11 | 17 | 1 | 0 | 11 | 5 | 2 | 24.5 | 691 | 0.005789 | 0.015919 | 0.024602 | 0.007236 | 0.002894 | 0 | 0.34375 | 0.246719 | const profilePattern =
/(?:^\[(\d+)\][ |]*(#\w+) (\d+)\/(\d+)$)|(?:^\[(\d+)\][ |]*([^(]+)\((\d+)\/(\d+)\) - ([\d.]+)%\/([\d.]+)%$)/;
const startPattern = /--- BEGIN PROFILE DUMP ---/;
const endPattern = /--- END PROFILE DUMP ---/;
export class ProfileReport {
root = new Root();
constructor(text) {
this.parseProfileReport(text);
}
private parseProfileReport(text) {
const lines = text.split(/\r?\n/);
let parent = this.root;
let previous = this.root;
let lastLevel = 0;
let foundStart = false;
for (const line of lines) {
if (!foundStart) {
if (!startPattern.exec(line)) continue;
foundStart = true;
continue;
}
if (endPattern.exec(line)) break;
let m;
if ((m = profilePattern.exec(line)) != null) {
const level = parseInt(m[1] ?? m[5], 10);
if (level < lastLevel) {
while (level <= parent.level && parent != this.root)
parent = parent.parent;
} else if (level > lastLevel) {
parent = previous;
}
lastLevel = level;
let current;
if (m[1]) {
// counter
current = {
parent,
text: m[2],
children: [],
level,
num1: parseInt(m[3]),
num2: parseInt(m[4]),
} as CounterLine;
} else if (m[5]) {
// pct
current = {
parent,
text: m[6],
children: [],
level,
num1: parseInt(m[7]),
num2: parseInt(m[8]),
pctParent: parseFloat(m[9]),
pctTotal: parseFloat(m[10]),
} as PctLine;
} else continue;
parent.children.push(current);
previous = current;
}
}
}
}
// [00] tick (86/1) - 95.17%/95.17%
// ---- text (num1/num2) - pctParent / ptcTotal
export interface ProfileLine {
parent;
level;
children;
text;
}
class Root implements ProfileLine {
parent = this;
level = -1;
children = [];
text = 'Profile Report';
}
export interface PctLine extends ProfileLine {
parent;
num1;
num2;
pctParent;
pctTotal;
}
export interface CounterLine extends ProfileLine {
parent;
num1;
num2;
}
|
c6e892ea9503ba7057ea0877d679b9904817e668 | 2,069 | ts | TypeScript | music-client/src/utils/index.ts | Changjinxing/wx-public-sharing-website | 5dfe6a714b0e20c528808a82aae9ad87d48e9231 | [
"Apache-2.0"
] | 1 | 2022-03-14T07:36:56.000Z | 2022-03-14T07:36:56.000Z | music-client/src/utils/index.ts | Changjinxing/wx-public-sharing-website | 5dfe6a714b0e20c528808a82aae9ad87d48e9231 | [
"Apache-2.0"
] | null | null | null | music-client/src/utils/index.ts | Changjinxing/wx-public-sharing-website | 5dfe6a714b0e20c528808a82aae9ad87d48e9231 | [
"Apache-2.0"
] | null | null | null | // 解析日期
export function getDateTime(date = new Date()) {
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}
// 解析歌词
export function parseLyric(text) {
let lines = text.split("\n");
const pattern = /\[\d{2}:\d{2}.(\d{3}|\d{2})\]/g;
const result = [];
// 对于歌词格式不对的特殊处理
if (!/\[.+\]/.test(text)) {
return [[0, text]];
}
while (!pattern.test(lines[0])) {
lines = lines.slice(1);
}
lines[lines.length - 1].length === 0 && lines.pop();
for (const item of lines) {
const time = item.match(pattern); // 存前面的时间段
const value = item.replace(pattern, ""); // 存歌词
for (const item1 of time) {
const t = item1.slice(1, -1).split(":");
if (value !== "") {
result.push([parseInt(t[0], 10) * 60 + parseFloat(t[1]), value]);
}
}
}
result.sort((a, b) => a[0] - b[0]);
return result;
}
// 解析播放时间
export function formatSeconds(value) {
let theTime = parseInt(value);
let theTime1 = 0;
let theTime2 = 0;
if (theTime > 60) {
theTime1 = parseInt((theTime / 60).toString()); // 分
theTime = parseInt((theTime % 60).toString()); // 秒
// 是否超过一个小时
if (theTime1 > 60) {
theTime2 = parseInt((theTime1 / 60).toString()); // 小时
theTime1 = 60; // 分
}
}
// 多少秒
let result = "";
if (parseInt((theTime).toString()) < 10) {
result = "0:0" + parseInt((theTime).toString());
} else {
result = "0:" + parseInt((theTime).toString());
}
// 多少分钟时
if (theTime1 > 0) {
if (parseInt((theTime).toString()) < 10) {
result = "0" + parseInt((theTime).toString());
} else {
result = parseInt((theTime).toString()).toString();
}
result = parseInt((theTime1).toString()) + ":" + result;
}
// 多少小时时
if (theTime2 > 0) {
if (parseInt((theTime).toString()) < 10) {
result = "0" + parseInt((theTime).toString());
} else {
result = parseInt((theTime).toString()).toString();
}
result = parseInt((theTime2).toString()) + ":" + parseInt((theTime1).toString()) + ":" + result;
}
return result;
}
| 26.87013 | 100 | 0.551474 | 63 | 4 | 0 | 5 | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 14.5 | 698 | 0.012894 | 0.014327 | 0 | 0 | 0 | 0 | 0 | 0.247044 | // 解析日期
export function getDateTime(date = new Date()) {
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}
// 解析歌词
export function parseLyric(text) {
let lines = text.split("\n");
const pattern = /\[\d{2}:\d{2}.(\d{3}|\d{2})\]/g;
const result = [];
// 对于歌词格式不对的特殊处理
if (!/\[.+\]/.test(text)) {
return [[0, text]];
}
while (!pattern.test(lines[0])) {
lines = lines.slice(1);
}
lines[lines.length - 1].length === 0 && lines.pop();
for (const item of lines) {
const time = item.match(pattern); // 存前面的时间段
const value = item.replace(pattern, ""); // 存歌词
for (const item1 of time) {
const t = item1.slice(1, -1).split(":");
if (value !== "") {
result.push([parseInt(t[0], 10) * 60 + parseFloat(t[1]), value]);
}
}
}
result.sort((a, b) => a[0] - b[0]);
return result;
}
// 解析播放时间
export function formatSeconds(value) {
let theTime = parseInt(value);
let theTime1 = 0;
let theTime2 = 0;
if (theTime > 60) {
theTime1 = parseInt((theTime / 60).toString()); // 分
theTime = parseInt((theTime % 60).toString()); // 秒
// 是否超过一个小时
if (theTime1 > 60) {
theTime2 = parseInt((theTime1 / 60).toString()); // 小时
theTime1 = 60; // 分
}
}
// 多少秒
let result = "";
if (parseInt((theTime).toString()) < 10) {
result = "0:0" + parseInt((theTime).toString());
} else {
result = "0:" + parseInt((theTime).toString());
}
// 多少分钟时
if (theTime1 > 0) {
if (parseInt((theTime).toString()) < 10) {
result = "0" + parseInt((theTime).toString());
} else {
result = parseInt((theTime).toString()).toString();
}
result = parseInt((theTime1).toString()) + ":" + result;
}
// 多少小时时
if (theTime2 > 0) {
if (parseInt((theTime).toString()) < 10) {
result = "0" + parseInt((theTime).toString());
} else {
result = parseInt((theTime).toString()).toString();
}
result = parseInt((theTime2).toString()) + ":" + parseInt((theTime1).toString()) + ":" + result;
}
return result;
}
|
c6f7caaa0590e6613ea1d397ac2df028f848091b | 1,584 | ts | TypeScript | packages/components/time-select/src/utils.ts | yhuijune/analyse-element-plus | efd6c2b2a7ccacf48bb847264bbda0156568a149 | [
"MIT"
] | null | null | null | packages/components/time-select/src/utils.ts | yhuijune/analyse-element-plus | efd6c2b2a7ccacf48bb847264bbda0156568a149 | [
"MIT"
] | 3 | 2022-03-13T20:43:36.000Z | 2022-03-14T21:43:33.000Z | packages/components/time-select/src/utils.ts | yhuijune/analyse-element-plus | efd6c2b2a7ccacf48bb847264bbda0156568a149 | [
"MIT"
] | null | null | null | interface Time {
hours: number
minutes: number
}
export const parseTime = (time: string): null | Time => {
const values = (time || '').split(':')
if (values.length >= 2) {
let hours = Number.parseInt(values[0], 10)
const minutes = Number.parseInt(values[1], 10)
const timeUpper = time.toUpperCase()
if (timeUpper.includes('AM') && hours === 12) {
hours = 0
} else if (timeUpper.includes('PM') && hours !== 12) {
hours += 12
}
return {
hours,
minutes,
}
}
return null
}
export const compareTime = (time1: string, time2: string): number => {
const value1 = parseTime(time1)
if (!value1) return -1
const value2 = parseTime(time2)
if (!value2) return -1
const minutes1 = value1.minutes + value1.hours * 60
const minutes2 = value2.minutes + value2.hours * 60
if (minutes1 === minutes2) {
return 0
}
return minutes1 > minutes2 ? 1 : -1
}
export const padTime = (time: number | string) => {
return `${time}`.padStart(2, '0')
}
export const formatTime = (time: Time): string => {
return `${padTime(time.hours)}:${padTime(time.minutes)}`
}
export const nextTime = (time: string, step: string): string => {
const timeValue = parseTime(time)
if (!timeValue) return ''
const stepValue = parseTime(step)
if (!stepValue) return ''
const next = {
hours: timeValue.hours,
minutes: timeValue.minutes,
}
next.minutes += stepValue.minutes
next.hours += stepValue.hours
next.hours += Math.floor(next.minutes / 60)
next.minutes = next.minutes % 60
return formatTime(next)
}
| 25.142857 | 70 | 0.631944 | 55 | 5 | 0 | 7 | 16 | 2 | 3 | 0 | 12 | 1 | 0 | 8.2 | 489 | 0.02454 | 0.03272 | 0.00409 | 0.002045 | 0 | 0 | 0.4 | 0.337942 | interface Time {
hours
minutes
}
export /* Example usages of 'parseTime' are shown below:
parseTime(time1);
parseTime(time2);
parseTime(time);
parseTime(step);
*/
const parseTime = (time) => {
const values = (time || '').split(':')
if (values.length >= 2) {
let hours = Number.parseInt(values[0], 10)
const minutes = Number.parseInt(values[1], 10)
const timeUpper = time.toUpperCase()
if (timeUpper.includes('AM') && hours === 12) {
hours = 0
} else if (timeUpper.includes('PM') && hours !== 12) {
hours += 12
}
return {
hours,
minutes,
}
}
return null
}
export const compareTime = (time1, time2) => {
const value1 = parseTime(time1)
if (!value1) return -1
const value2 = parseTime(time2)
if (!value2) return -1
const minutes1 = value1.minutes + value1.hours * 60
const minutes2 = value2.minutes + value2.hours * 60
if (minutes1 === minutes2) {
return 0
}
return minutes1 > minutes2 ? 1 : -1
}
export /* Example usages of 'padTime' are shown below:
padTime(time.hours);
padTime(time.minutes);
*/
const padTime = (time) => {
return `${time}`.padStart(2, '0')
}
export /* Example usages of 'formatTime' are shown below:
formatTime(next);
*/
const formatTime = (time) => {
return `${padTime(time.hours)}:${padTime(time.minutes)}`
}
export const nextTime = (time, step) => {
const timeValue = parseTime(time)
if (!timeValue) return ''
const stepValue = parseTime(step)
if (!stepValue) return ''
const next = {
hours: timeValue.hours,
minutes: timeValue.minutes,
}
next.minutes += stepValue.minutes
next.hours += stepValue.hours
next.hours += Math.floor(next.minutes / 60)
next.minutes = next.minutes % 60
return formatTime(next)
}
|
5b1d02076dfe1cfda11f3e2d457204e393691d85 | 2,818 | ts | TypeScript | src/generators/Schema/utils.ts | kkopanidis/CLI | 18b9119ca7ff2fa271efd1de7a6c1bb583fdb290 | [
"MIT"
] | 3 | 2022-01-30T18:09:30.000Z | 2022-02-25T13:46:26.000Z | src/generators/Schema/utils.ts | ConduitPlatform/CLI | a7b23e8fcfc57f795a76a164e17feedae12f2393 | [
"MIT"
] | null | null | null | src/generators/Schema/utils.ts | ConduitPlatform/CLI | a7b23e8fcfc57f795a76a164e17feedae12f2393 | [
"MIT"
] | null | null | null | function extractType(field: any) {
switch (field) {
case 'ObjectId':
return 'string';
case 'String':
return 'string';
case 'Number':
return 'number';
case 'Date':
return 'Date';
default:
return field;
}
}
export function parseFieldsToTs(fields: any) {
let typings = '';
let imports = '';
for (const field in fields) {
if (typeof fields[field] === 'string') {
typings += ` ${field}: ${extractType(fields[field])};\n`;
} else if (fields[field].enum) {
const types = (fields[field].enum as string[])
.map((val) => "'" + val + "'")
.join(' | ');
typings += ` ${field}${fields[field].required ? '!' : ''}: ${types};\n`;
} else if (fields[field].type === 'Relation') {
const name =
fields[field].model.charAt(0).toUpperCase() + fields[field].model.slice(1);
const importText = `import {${name}} from \'./${name}.schema\'\n`;
if (imports.indexOf(importText) === -1) {
imports += importText;
}
typings += ` ${field}${fields[field].required ? '!' : ''}: ${name};\n`;
} else if (typeof fields[field].type === 'string') {
typings += ` ${field}${fields[field].required ? '!' : ''}: ${extractType(
fields[field].type
)};\n`;
} else if (
Array.isArray(fields[field].type) &&
typeof fields[field].type[0] === 'object'
) {
if (fields[field].type[0].type) {
const fieldParse = parseFieldsToTs({ [field]: fields[field].type[0] });
fieldParse.typings = fieldParse.typings.replace(';', '[];');
fieldParse.imports.split('\n').forEach((imported) => {
if (imports.indexOf(imported) === -1) {
imports += imported + '\n';
}
});
typings += fieldParse.typings;
} else {
const fieldParse = parseFieldsToTs(fields[field].type[0]);
fieldParse.imports.split('\n').forEach((imported) => {
if (imports.indexOf(imported) === -1) {
imports += imported + '\n';
}
});
typings += ` ${field}${fields[field].required ? '!' : ''}: {${
fieldParse.typings
}}[];\n`;
}
} else if (Array.isArray(fields[field].type)) {
typings += ` ${field}${fields[field].required ? '!' : ''}: ${extractType(
fields[field].type[0]
)}[];\n`;
} else if (typeof fields[field].type === 'object') {
const fieldParse = parseFieldsToTs(fields[field].type);
fieldParse.imports.split('\n').forEach((imported) => {
if (imports.indexOf(imported) === -1) {
imports += imported + '\n';
}
});
typings += ` ${field}${fields[field].required ? '!' : ''}: {${
fieldParse.typings
}};\n`;
}
}
return { typings, imports };
}
| 34.790123 | 83 | 0.519517 | 79 | 6 | 0 | 6 | 8 | 0 | 2 | 2 | 1 | 0 | 5 | 14.166667 | 788 | 0.015228 | 0.010152 | 0 | 0 | 0.006345 | 0.1 | 0.05 | 0.236765 | /* Example usages of 'extractType' are shown below:
extractType(fields[field]);
extractType(fields[field].type);
extractType(fields[field].type[0]);
*/
function extractType(field) {
switch (field) {
case 'ObjectId':
return 'string';
case 'String':
return 'string';
case 'Number':
return 'number';
case 'Date':
return 'Date';
default:
return field;
}
}
export /* Example usages of 'parseFieldsToTs' are shown below:
parseFieldsToTs({ [field]: fields[field].type[0] });
parseFieldsToTs(fields[field].type[0]);
parseFieldsToTs(fields[field].type);
*/
function parseFieldsToTs(fields) {
let typings = '';
let imports = '';
for (const field in fields) {
if (typeof fields[field] === 'string') {
typings += ` ${field}: ${extractType(fields[field])};\n`;
} else if (fields[field].enum) {
const types = (fields[field].enum as string[])
.map((val) => "'" + val + "'")
.join(' | ');
typings += ` ${field}${fields[field].required ? '!' : ''}: ${types};\n`;
} else if (fields[field].type === 'Relation') {
const name =
fields[field].model.charAt(0).toUpperCase() + fields[field].model.slice(1);
const importText = `import {${name}} from \'./${name}.schema\'\n`;
if (imports.indexOf(importText) === -1) {
imports += importText;
}
typings += ` ${field}${fields[field].required ? '!' : ''}: ${name};\n`;
} else if (typeof fields[field].type === 'string') {
typings += ` ${field}${fields[field].required ? '!' : ''}: ${extractType(
fields[field].type
)};\n`;
} else if (
Array.isArray(fields[field].type) &&
typeof fields[field].type[0] === 'object'
) {
if (fields[field].type[0].type) {
const fieldParse = parseFieldsToTs({ [field]: fields[field].type[0] });
fieldParse.typings = fieldParse.typings.replace(';', '[];');
fieldParse.imports.split('\n').forEach((imported) => {
if (imports.indexOf(imported) === -1) {
imports += imported + '\n';
}
});
typings += fieldParse.typings;
} else {
const fieldParse = parseFieldsToTs(fields[field].type[0]);
fieldParse.imports.split('\n').forEach((imported) => {
if (imports.indexOf(imported) === -1) {
imports += imported + '\n';
}
});
typings += ` ${field}${fields[field].required ? '!' : ''}: {${
fieldParse.typings
}}[];\n`;
}
} else if (Array.isArray(fields[field].type)) {
typings += ` ${field}${fields[field].required ? '!' : ''}: ${extractType(
fields[field].type[0]
)}[];\n`;
} else if (typeof fields[field].type === 'object') {
const fieldParse = parseFieldsToTs(fields[field].type);
fieldParse.imports.split('\n').forEach((imported) => {
if (imports.indexOf(imported) === -1) {
imports += imported + '\n';
}
});
typings += ` ${field}${fields[field].required ? '!' : ''}: {${
fieldParse.typings
}};\n`;
}
}
return { typings, imports };
}
|
5b82a1ed5e883233d9103395a1da4ecb4296ec2e | 7,322 | ts | TypeScript | packages/playwright-core/src/server/injected/componentUtils.ts | Yexiaoxing/playwright | 174225697a5d3ba5227fbb52b3a23c54d4877f4b | [
"Apache-2.0"
] | 1 | 2022-03-27T07:23:56.000Z | 2022-03-27T07:23:56.000Z | packages/playwright-core/src/server/injected/componentUtils.ts | Yexiaoxing/playwright | 174225697a5d3ba5227fbb52b3a23c54d4877f4b | [
"Apache-2.0"
] | null | null | null | packages/playwright-core/src/server/injected/componentUtils.ts | Yexiaoxing/playwright | 174225697a5d3ba5227fbb52b3a23c54d4877f4b | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (c) Microsoft Corporation.
*
* 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.
*/
type Operator = '<truthy>'|'='|'*='|'|='|'^='|'$='|'~=';
export type ParsedComponentAttribute = {
jsonPath: string[],
op: Operator,
value: any,
caseSensitive: boolean,
};
export type ParsedComponentSelector = {
name: string,
attributes: ParsedComponentAttribute[],
};
export function checkComponentAttribute(obj: any, attr: ParsedComponentAttribute) {
for (const token of attr.jsonPath) {
if (obj !== undefined && obj !== null)
obj = obj[token];
}
return matchesAttribute(obj, attr);
}
export function matchesAttribute(value: any, attr: ParsedComponentAttribute) {
const objValue = typeof value === 'string' && !attr.caseSensitive ? value.toUpperCase() : value;
const attrValue = typeof attr.value === 'string' && !attr.caseSensitive ? attr.value.toUpperCase() : attr.value;
if (attr.op === '<truthy>')
return !!objValue;
if (attr.op === '=') {
if (attrValue instanceof RegExp)
return typeof objValue === 'string' && !!objValue.match(attrValue);
return objValue === attrValue;
}
if (typeof objValue !== 'string' || typeof attrValue !== 'string')
return false;
if (attr.op === '*=')
return objValue.includes(attrValue);
if (attr.op === '^=')
return objValue.startsWith(attrValue);
if (attr.op === '$=')
return objValue.endsWith(attrValue);
if (attr.op === '|=')
return objValue === attrValue || objValue.startsWith(attrValue + '-');
if (attr.op === '~=')
return objValue.split(' ').includes(attrValue);
return false;
}
export function parseComponentSelector(selector: string): ParsedComponentSelector {
let wp = 0;
let EOL = selector.length === 0;
const next = () => selector[wp] || '';
const eat1 = () => {
const result = next();
++wp;
EOL = wp >= selector.length;
return result;
};
const syntaxError = (stage: string|undefined) => {
if (EOL)
throw new Error(`Unexpected end of selector while parsing selector \`${selector}\``);
throw new Error(`Error while parsing selector \`${selector}\` - unexpected symbol "${next()}" at position ${wp}` + (stage ? ' during ' + stage : ''));
};
function skipSpaces() {
while (!EOL && /\s/.test(next()))
eat1();
}
function readIdentifier() {
let result = '';
skipSpaces();
while (!EOL && /[-$0-9A-Z_]/i.test(next()))
result += eat1();
return result;
}
function readQuotedString(quote: string) {
let result = eat1();
if (result !== quote)
syntaxError('parsing quoted string');
while (!EOL && next() !== quote) {
if (next() === '\\')
eat1();
result += eat1();
}
if (next() !== quote)
syntaxError('parsing quoted string');
result += eat1();
return result;
}
function readRegularExpression() {
if (eat1() !== '/')
syntaxError('parsing regular expression');
let source = '';
let inClass = false;
// https://262.ecma-international.org/11.0/#sec-literals-regular-expression-literals
while (!EOL) {
if (next() === '\\') {
source += eat1();
if (EOL)
syntaxError('parsing regular expressiion');
} else if (inClass && next() === ']') {
inClass = false;
} else if (!inClass && next() === '[') {
inClass = true;
} else if (!inClass && next() === '/') {
break;
}
source += eat1();
}
if (eat1() !== '/')
syntaxError('parsing regular expression');
let flags = '';
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
while (!EOL && next().match(/[dgimsuy]/))
flags += eat1();
try {
return new RegExp(source, flags);
} catch (e) {
throw new Error(`Error while parsing selector \`${selector}\`: ${e.message}`);
}
}
function readAttributeToken() {
let token = '';
skipSpaces();
if (next() === `'` || next() === `"`)
token = readQuotedString(next()).slice(1, -1);
else
token = readIdentifier();
if (!token)
syntaxError('parsing property path');
return token;
}
function readOperator(): Operator {
skipSpaces();
let op = '';
if (!EOL)
op += eat1();
if (!EOL && (op !== '='))
op += eat1();
if (!['=', '*=', '^=', '$=', '|=', '~='].includes(op))
syntaxError('parsing operator');
return (op as Operator);
}
function readAttribute(): ParsedComponentAttribute {
// skip leading [
eat1();
// read attribute name:
// foo.bar
// 'foo' . "ba zz"
const jsonPath = [];
jsonPath.push(readAttributeToken());
skipSpaces();
while (next() === '.') {
eat1();
jsonPath.push(readAttributeToken());
skipSpaces();
}
// check property is truthy: [enabled]
if (next() === ']') {
eat1();
return { jsonPath, op: '<truthy>', value: null, caseSensitive: false };
}
const operator = readOperator();
let value = undefined;
let caseSensitive = true;
skipSpaces();
if (next() === '/') {
if (operator !== '=')
throw new Error(`Error while parsing selector \`${selector}\` - cannot use ${operator} in attribute with regular expression`);
value = readRegularExpression();
} else if (next() === `'` || next() === `"`) {
value = readQuotedString(next()).slice(1, -1);
skipSpaces();
if (next() === 'i' || next() === 'I') {
caseSensitive = false;
eat1();
} else if (next() === 's' || next() === 'S') {
caseSensitive = true;
eat1();
}
} else {
value = '';
while (!EOL && !/\s/.test(next()) && next() !== ']')
value += eat1();
if (value === 'true') {
value = true;
} else if (value === 'false') {
value = false;
} else {
value = +value;
if (isNaN(value))
syntaxError('parsing attribute value');
}
}
skipSpaces();
if (next() !== ']')
syntaxError('parsing attribute value');
eat1();
if (operator !== '=' && typeof value !== 'string')
throw new Error(`Error while parsing selector \`${selector}\` - cannot use ${operator} in attribute with non-string matching value - ${value}`);
return { jsonPath, op: operator, value, caseSensitive };
}
const result: ParsedComponentSelector = {
name: '',
attributes: [],
};
result.name = readIdentifier();
skipSpaces();
while (next() === '[') {
result.attributes.push(readAttribute());
skipSpaces();
}
if (!EOL)
syntaxError(undefined);
if (!result.name && !result.attributes.length)
throw new Error(`Error while parsing selector \`${selector}\` - selector cannot be empty`);
return result;
}
| 29.643725 | 154 | 0.574433 | 204 | 13 | 0 | 7 | 20 | 6 | 11 | 3 | 6 | 3 | 8 | 24 | 1,889 | 0.010588 | 0.010588 | 0.003176 | 0.001588 | 0.004235 | 0.065217 | 0.130435 | 0.233004 | /**
* Copyright (c) Microsoft Corporation.
*
* 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.
*/
type Operator = '<truthy>'|'='|'*='|'|='|'^='|'$='|'~=';
export type ParsedComponentAttribute = {
jsonPath,
op,
value,
caseSensitive,
};
export type ParsedComponentSelector = {
name,
attributes,
};
export function checkComponentAttribute(obj, attr) {
for (const token of attr.jsonPath) {
if (obj !== undefined && obj !== null)
obj = obj[token];
}
return matchesAttribute(obj, attr);
}
export /* Example usages of 'matchesAttribute' are shown below:
matchesAttribute(obj, attr);
*/
function matchesAttribute(value, attr) {
const objValue = typeof value === 'string' && !attr.caseSensitive ? value.toUpperCase() : value;
const attrValue = typeof attr.value === 'string' && !attr.caseSensitive ? attr.value.toUpperCase() : attr.value;
if (attr.op === '<truthy>')
return !!objValue;
if (attr.op === '=') {
if (attrValue instanceof RegExp)
return typeof objValue === 'string' && !!objValue.match(attrValue);
return objValue === attrValue;
}
if (typeof objValue !== 'string' || typeof attrValue !== 'string')
return false;
if (attr.op === '*=')
return objValue.includes(attrValue);
if (attr.op === '^=')
return objValue.startsWith(attrValue);
if (attr.op === '$=')
return objValue.endsWith(attrValue);
if (attr.op === '|=')
return objValue === attrValue || objValue.startsWith(attrValue + '-');
if (attr.op === '~=')
return objValue.split(' ').includes(attrValue);
return false;
}
export function parseComponentSelector(selector) {
let wp = 0;
let EOL = selector.length === 0;
/* Example usages of 'next' are shown below:
next();
!EOL && /\s/.test(next());
!EOL && /[-$0-9A-Z_]/i.test(next());
!EOL && next() !== quote;
next() === '\\';
next() !== quote;
inClass && next() === ']';
!inClass && next() === '[';
!inClass && next() === '/';
!EOL && next().match(/[dgimsuy]/);
next() === `'` || next() === `"`;
token = readQuotedString(next()).slice(1, -1);
next() === '.';
next() === ']';
next() === '/';
value = readQuotedString(next()).slice(1, -1);
next() === 'i' || next() === 'I';
next() === 's' || next() === 'S';
!EOL && !/\s/.test(next()) && next() !== ']';
next() !== ']';
next() === '[';
*/
const next = () => selector[wp] || '';
/* Example usages of 'eat1' are shown below:
eat1();
result += eat1();
eat1() !== '/';
source += eat1();
flags += eat1();
op += eat1();
// skip leading [
eat1();
value += eat1();
*/
const eat1 = () => {
const result = next();
++wp;
EOL = wp >= selector.length;
return result;
};
/* Example usages of 'syntaxError' are shown below:
syntaxError('parsing quoted string');
syntaxError('parsing regular expression');
syntaxError('parsing regular expressiion');
syntaxError('parsing property path');
syntaxError('parsing operator');
syntaxError('parsing attribute value');
syntaxError(undefined);
*/
const syntaxError = (stage) => {
if (EOL)
throw new Error(`Unexpected end of selector while parsing selector \`${selector}\``);
throw new Error(`Error while parsing selector \`${selector}\` - unexpected symbol "${next()}" at position ${wp}` + (stage ? ' during ' + stage : ''));
};
/* Example usages of 'skipSpaces' are shown below:
skipSpaces();
*/
function skipSpaces() {
while (!EOL && /\s/.test(next()))
eat1();
}
/* Example usages of 'readIdentifier' are shown below:
token = readIdentifier();
result.name = readIdentifier();
*/
function readIdentifier() {
let result = '';
skipSpaces();
while (!EOL && /[-$0-9A-Z_]/i.test(next()))
result += eat1();
return result;
}
/* Example usages of 'readQuotedString' are shown below:
token = readQuotedString(next()).slice(1, -1);
value = readQuotedString(next()).slice(1, -1);
*/
function readQuotedString(quote) {
let result = eat1();
if (result !== quote)
syntaxError('parsing quoted string');
while (!EOL && next() !== quote) {
if (next() === '\\')
eat1();
result += eat1();
}
if (next() !== quote)
syntaxError('parsing quoted string');
result += eat1();
return result;
}
/* Example usages of 'readRegularExpression' are shown below:
value = readRegularExpression();
*/
function readRegularExpression() {
if (eat1() !== '/')
syntaxError('parsing regular expression');
let source = '';
let inClass = false;
// https://262.ecma-international.org/11.0/#sec-literals-regular-expression-literals
while (!EOL) {
if (next() === '\\') {
source += eat1();
if (EOL)
syntaxError('parsing regular expressiion');
} else if (inClass && next() === ']') {
inClass = false;
} else if (!inClass && next() === '[') {
inClass = true;
} else if (!inClass && next() === '/') {
break;
}
source += eat1();
}
if (eat1() !== '/')
syntaxError('parsing regular expression');
let flags = '';
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
while (!EOL && next().match(/[dgimsuy]/))
flags += eat1();
try {
return new RegExp(source, flags);
} catch (e) {
throw new Error(`Error while parsing selector \`${selector}\`: ${e.message}`);
}
}
/* Example usages of 'readAttributeToken' are shown below:
jsonPath.push(readAttributeToken());
*/
function readAttributeToken() {
let token = '';
skipSpaces();
if (next() === `'` || next() === `"`)
token = readQuotedString(next()).slice(1, -1);
else
token = readIdentifier();
if (!token)
syntaxError('parsing property path');
return token;
}
/* Example usages of 'readOperator' are shown below:
readOperator();
*/
function readOperator() {
skipSpaces();
let op = '';
if (!EOL)
op += eat1();
if (!EOL && (op !== '='))
op += eat1();
if (!['=', '*=', '^=', '$=', '|=', '~='].includes(op))
syntaxError('parsing operator');
return (op as Operator);
}
/* Example usages of 'readAttribute' are shown below:
result.attributes.push(readAttribute());
*/
function readAttribute() {
// skip leading [
eat1();
// read attribute name:
// foo.bar
// 'foo' . "ba zz"
const jsonPath = [];
jsonPath.push(readAttributeToken());
skipSpaces();
while (next() === '.') {
eat1();
jsonPath.push(readAttributeToken());
skipSpaces();
}
// check property is truthy: [enabled]
if (next() === ']') {
eat1();
return { jsonPath, op: '<truthy>', value: null, caseSensitive: false };
}
const operator = readOperator();
let value = undefined;
let caseSensitive = true;
skipSpaces();
if (next() === '/') {
if (operator !== '=')
throw new Error(`Error while parsing selector \`${selector}\` - cannot use ${operator} in attribute with regular expression`);
value = readRegularExpression();
} else if (next() === `'` || next() === `"`) {
value = readQuotedString(next()).slice(1, -1);
skipSpaces();
if (next() === 'i' || next() === 'I') {
caseSensitive = false;
eat1();
} else if (next() === 's' || next() === 'S') {
caseSensitive = true;
eat1();
}
} else {
value = '';
while (!EOL && !/\s/.test(next()) && next() !== ']')
value += eat1();
if (value === 'true') {
value = true;
} else if (value === 'false') {
value = false;
} else {
value = +value;
if (isNaN(value))
syntaxError('parsing attribute value');
}
}
skipSpaces();
if (next() !== ']')
syntaxError('parsing attribute value');
eat1();
if (operator !== '=' && typeof value !== 'string')
throw new Error(`Error while parsing selector \`${selector}\` - cannot use ${operator} in attribute with non-string matching value - ${value}`);
return { jsonPath, op: operator, value, caseSensitive };
}
const result = {
name: '',
attributes: [],
};
result.name = readIdentifier();
skipSpaces();
while (next() === '[') {
result.attributes.push(readAttribute());
skipSpaces();
}
if (!EOL)
syntaxError(undefined);
if (!result.name && !result.attributes.length)
throw new Error(`Error while parsing selector \`${selector}\` - selector cannot be empty`);
return result;
}
|
5bf8f0f2946da835300025c6804a609bef4277ab | 5,727 | ts | TypeScript | tests/cases/conformance/types/unknown/unknownControlFlow.ts | warting/TypeScript | 180bc4cbea87db2fd9a0facbdd94eddf683e19b4 | [
"Apache-2.0"
] | 16 | 2022-01-29T06:47:58.000Z | 2022-03-29T16:37:13.000Z | tests/cases/conformance/types/unknown/unknownControlFlow.ts | warting/TypeScript | 180bc4cbea87db2fd9a0facbdd94eddf683e19b4 | [
"Apache-2.0"
] | 40 | 2022-01-29T04:06:48.000Z | 2022-03-31T21:24:32.000Z | tests/cases/conformance/types/unknown/unknownControlFlow.ts | warting/TypeScript | 180bc4cbea87db2fd9a0facbdd94eddf683e19b4 | [
"Apache-2.0"
] | 1 | 2022-01-29T04:16:45.000Z | 2022-01-29T04:16:45.000Z | // @strict: true
// @declaration: true
type T01 = {} & string; // string
type T02 = {} & 'a'; // 'a'
type T03 = {} & object; // object
type T04 = {} & { x: number }; // { x: number }
type T05 = {} & null; // never
type T06 = {} & undefined; // never
type T07 = undefined & void; // undefined
type T10 = string & {}; // Specially preserved
type T11 = number & {}; // Specially preserved
type T12 = bigint & {}; // Specially preserved
type ThisNode = {};
type ThatNode = {};
type ThisOrThatNode = ThisNode | ThatNode;
function f01(u: unknown) {
let x1: {} = u; // Error
let x2: {} | null | undefined = u;
let x3: {} | { x: string } | null | undefined = u;
let x4: ThisOrThatNode | null | undefined = u;
}
function f10(x: unknown) {
if (x) {
x; // {}
}
else {
x; // unknown
}
if (!x) {
x; // unknown
}
else {
x; // {}
}
}
function f11<T>(x: T) {
if (x) {
x; // T & {}
}
else {
x; // T
}
if (!x) {
x; // T
}
else {
x; // T & {}
}
}
function f12<T extends {}>(x: T) {
if (x) {
x; // T
}
else {
x; // T
}
}
function f20(x: unknown) {
if (x !== undefined) {
x; // {} | null
}
else {
x; // undefined
}
if (x !== null) {
x; // {} | undefined
}
else {
x; // null
}
if (x !== undefined && x !== null) {
x; // {}
}
else {
x; // null | undefined
}
if (x != undefined) {
x; // {}
}
else {
x; // null | undefined
}
if (x != null) {
x; // {}
}
else {
x; // null | undefined
}
}
function f21<T>(x: T) {
if (x !== undefined) {
x; // T & ({} | null)
}
else {
x; // T
}
if (x !== null) {
x; // T & ({} | undefined)
}
else {
x; // T
}
if (x !== undefined && x !== null) {
x; // T & {}
}
else {
x; // T
}
if (x != undefined) {
x; // T & {}
}
else {
x; // T
}
if (x != null) {
x; // T & {}
}
else {
x; // T
}
}
function f22<T extends {} | undefined>(x: T) {
if (x !== undefined) {
x; // T & {}
}
else {
x; // T
}
if (x !== null) {
x; // T
}
else {
x; // T
}
if (x !== undefined && x !== null) {
x; // T & {}
}
else {
x; // T
}
if (x != undefined) {
x; // T & {}
}
else {
x; // T
}
if (x != null) {
x; // T & {}
}
else {
x; // T
}
}
function f23<T>(x: T | undefined | null) {
if (x !== undefined) {
x; // T & {} | null
}
if (x !== null) {
x; // T & {} | undefined
}
if (x != undefined) {
x; // T & {}
}
if (x != null) {
x; // T & {}
}
}
function f30(x: {}) {
if (typeof x === "object") {
x; // object
}
}
function f31<T>(x: T) {
if (typeof x === "object") {
x; // T & object | T & null
}
if (x && typeof x === "object") {
x; // T & object
}
if (typeof x === "object" && x) {
x; // T & object
}
}
function f32<T extends {} | undefined>(x: T) {
if (typeof x === "object") {
x; // T & object
}
}
function possiblyNull<T>(x: T) {
return !!true ? x : null; // T | null
}
function possiblyUndefined<T>(x: T) {
return !!true ? x : undefined; // T | undefined
}
function possiblyNullOrUndefined<T>(x: T) {
return possiblyUndefined(possiblyNull(x)); // T | null | undefined
}
function ensureNotNull<T>(x: T) {
if (x === null) throw Error();
return x; // T & ({} | undefined)
}
function ensureNotUndefined<T>(x: T) {
if (x === undefined) throw Error();
return x; // T & ({} | null)
}
function ensureNotNullOrUndefined<T>(x: T) {
return ensureNotUndefined(ensureNotNull(x)); // T & {}
}
function f40(a: string | undefined, b: number | null | undefined) {
let a1 = ensureNotNullOrUndefined(a); // string
let b1 = ensureNotNullOrUndefined(b); // number
}
type QQ<T> = NonNullable<NonNullable<NonNullable<T>>>;
function f41<T>(a: T) {
let a1 = ensureNotUndefined(ensureNotNull(a)); // T & {}
let a2 = ensureNotNull(ensureNotUndefined(a)); // T & {}
let a3 = ensureNotNull(ensureNotNull(a)); // T & {} | T & undefined
let a4 = ensureNotUndefined(ensureNotUndefined(a)); // T & {} | T & null
let a5 = ensureNotNullOrUndefined(ensureNotNullOrUndefined(a)); // T & {}
let a6 = ensureNotNull(possiblyNullOrUndefined(a)); // T & {} | undefined
let a7 = ensureNotUndefined(possiblyNullOrUndefined(a)); // T & {} | null
let a8 = ensureNotNull(possiblyUndefined(a)); // T & {} | undefined
let a9 = ensureNotUndefined(possiblyNull(a)); // T & {} | null
}
// Repro from #48468
function deepEquals<T>(a: T, b: T): boolean {
if (typeof a !== 'object' || typeof b !== 'object' || !a || !b) {
return false;
}
if (Array.isArray(a) || Array.isArray(b)) {
return false;
}
if (Object.keys(a).length !== Object.keys(b).length) { // Error here
return false;
}
return true;
}
// Repro from #49386
function foo<T>(x: T | null) {
let y = x;
if (y !== null) {
y;
}
}
| 21.055147 | 79 | 0.422211 | 240 | 21 | 0 | 23 | 16 | 0 | 6 | 0 | 13 | 14 | 7 | 8.761905 | 1,866 | 0.02358 | 0.008574 | 0 | 0.007503 | 0.003751 | 0 | 0.216667 | 0.266034 | // @strict: true
// @declaration: true
type T01 = {} & string; // string
type T02 = {} & 'a'; // 'a'
type T03 = {} & object; // object
type T04 = {} & { x }; // { x: number }
type T05 = {} & null; // never
type T06 = {} & undefined; // never
type T07 = undefined & void; // undefined
type T10 = string & {}; // Specially preserved
type T11 = number & {}; // Specially preserved
type T12 = bigint & {}; // Specially preserved
type ThisNode = {};
type ThatNode = {};
type ThisOrThatNode = ThisNode | ThatNode;
function f01(u) {
let x1 = u; // Error
let x2 = u;
let x3 = u;
let x4 = u;
}
function f10(x) {
if (x) {
x; // {}
}
else {
x; // unknown
}
if (!x) {
x; // unknown
}
else {
x; // {}
}
}
function f11<T>(x) {
if (x) {
x; // T & {}
}
else {
x; // T
}
if (!x) {
x; // T
}
else {
x; // T & {}
}
}
function f12<T extends {}>(x) {
if (x) {
x; // T
}
else {
x; // T
}
}
function f20(x) {
if (x !== undefined) {
x; // {} | null
}
else {
x; // undefined
}
if (x !== null) {
x; // {} | undefined
}
else {
x; // null
}
if (x !== undefined && x !== null) {
x; // {}
}
else {
x; // null | undefined
}
if (x != undefined) {
x; // {}
}
else {
x; // null | undefined
}
if (x != null) {
x; // {}
}
else {
x; // null | undefined
}
}
function f21<T>(x) {
if (x !== undefined) {
x; // T & ({} | null)
}
else {
x; // T
}
if (x !== null) {
x; // T & ({} | undefined)
}
else {
x; // T
}
if (x !== undefined && x !== null) {
x; // T & {}
}
else {
x; // T
}
if (x != undefined) {
x; // T & {}
}
else {
x; // T
}
if (x != null) {
x; // T & {}
}
else {
x; // T
}
}
function f22<T extends {} | undefined>(x) {
if (x !== undefined) {
x; // T & {}
}
else {
x; // T
}
if (x !== null) {
x; // T
}
else {
x; // T
}
if (x !== undefined && x !== null) {
x; // T & {}
}
else {
x; // T
}
if (x != undefined) {
x; // T & {}
}
else {
x; // T
}
if (x != null) {
x; // T & {}
}
else {
x; // T
}
}
function f23<T>(x) {
if (x !== undefined) {
x; // T & {} | null
}
if (x !== null) {
x; // T & {} | undefined
}
if (x != undefined) {
x; // T & {}
}
if (x != null) {
x; // T & {}
}
}
function f30(x) {
if (typeof x === "object") {
x; // object
}
}
function f31<T>(x) {
if (typeof x === "object") {
x; // T & object | T & null
}
if (x && typeof x === "object") {
x; // T & object
}
if (typeof x === "object" && x) {
x; // T & object
}
}
function f32<T extends {} | undefined>(x) {
if (typeof x === "object") {
x; // T & object
}
}
/* Example usages of 'possiblyNull' are shown below:
possiblyUndefined(possiblyNull(x));
ensureNotUndefined(possiblyNull(a));
*/
function possiblyNull<T>(x) {
return !!true ? x : null; // T | null
}
/* Example usages of 'possiblyUndefined' are shown below:
possiblyUndefined(possiblyNull(x));
ensureNotNull(possiblyUndefined(a));
*/
function possiblyUndefined<T>(x) {
return !!true ? x : undefined; // T | undefined
}
/* Example usages of 'possiblyNullOrUndefined' are shown below:
ensureNotNull(possiblyNullOrUndefined(a));
ensureNotUndefined(possiblyNullOrUndefined(a));
*/
function possiblyNullOrUndefined<T>(x) {
return possiblyUndefined(possiblyNull(x)); // T | null | undefined
}
/* Example usages of 'ensureNotNull' are shown below:
ensureNotUndefined(ensureNotNull(x));
ensureNotUndefined(ensureNotNull(a));
ensureNotNull(ensureNotUndefined(a));
ensureNotNull(ensureNotNull(a));
ensureNotNull(possiblyNullOrUndefined(a));
ensureNotNull(possiblyUndefined(a));
*/
function ensureNotNull<T>(x) {
if (x === null) throw Error();
return x; // T & ({} | undefined)
}
/* Example usages of 'ensureNotUndefined' are shown below:
ensureNotUndefined(ensureNotNull(x));
ensureNotUndefined(ensureNotNull(a));
ensureNotNull(ensureNotUndefined(a));
ensureNotUndefined(ensureNotUndefined(a));
ensureNotUndefined(possiblyNullOrUndefined(a));
ensureNotUndefined(possiblyNull(a));
*/
function ensureNotUndefined<T>(x) {
if (x === undefined) throw Error();
return x; // T & ({} | null)
}
/* Example usages of 'ensureNotNullOrUndefined' are shown below:
ensureNotNullOrUndefined(a);
ensureNotNullOrUndefined(b);
ensureNotNullOrUndefined(ensureNotNullOrUndefined(a));
*/
function ensureNotNullOrUndefined<T>(x) {
return ensureNotUndefined(ensureNotNull(x)); // T & {}
}
function f40(a, b) {
let a1 = ensureNotNullOrUndefined(a); // string
let b1 = ensureNotNullOrUndefined(b); // number
}
type QQ<T> = NonNullable<NonNullable<NonNullable<T>>>;
function f41<T>(a) {
let a1 = ensureNotUndefined(ensureNotNull(a)); // T & {}
let a2 = ensureNotNull(ensureNotUndefined(a)); // T & {}
let a3 = ensureNotNull(ensureNotNull(a)); // T & {} | T & undefined
let a4 = ensureNotUndefined(ensureNotUndefined(a)); // T & {} | T & null
let a5 = ensureNotNullOrUndefined(ensureNotNullOrUndefined(a)); // T & {}
let a6 = ensureNotNull(possiblyNullOrUndefined(a)); // T & {} | undefined
let a7 = ensureNotUndefined(possiblyNullOrUndefined(a)); // T & {} | null
let a8 = ensureNotNull(possiblyUndefined(a)); // T & {} | undefined
let a9 = ensureNotUndefined(possiblyNull(a)); // T & {} | null
}
// Repro from #48468
function deepEquals<T>(a, b) {
if (typeof a !== 'object' || typeof b !== 'object' || !a || !b) {
return false;
}
if (Array.isArray(a) || Array.isArray(b)) {
return false;
}
if (Object.keys(a).length !== Object.keys(b).length) { // Error here
return false;
}
return true;
}
// Repro from #49386
function foo<T>(x) {
let y = x;
if (y !== null) {
y;
}
}
|
4626f86ebac17685496987c0b44d830041d92194 | 2,663 | ts | TypeScript | app/common/parts.ts | pkukkapalli/emblemsnake | 63e699d5a1095d14edacde306f1bae30f39219f8 | [
"MIT"
] | null | null | null | app/common/parts.ts | pkukkapalli/emblemsnake | 63e699d5a1095d14edacde306f1bae30f39219f8 | [
"MIT"
] | 1 | 2022-02-13T19:22:01.000Z | 2022-02-13T19:22:01.000Z | app/common/parts.ts | pkukkapalli/emblemsnake | 63e699d5a1095d14edacde306f1bae30f39219f8 | [
"MIT"
] | null | null | null | export interface Part {
name: string;
group: PartGroupType;
path: string;
pathToSmallImage: string;
}
export interface PartsState {
isLoading: boolean;
error?: Error;
backParts: Record<string, Part>;
frontParts: Record<string, Part>;
wordParts: Record<string, Part>;
}
export enum PartGroupType {
BACK_NORMAL = 'BACK_NORMAL',
BACK_SPECIAL = 'BACK_SPECIAL',
FRONT_NORMAL = 'FRONT_NORMAL',
FRONT_ANIMALS = 'FRONT_ANIMALS',
FRONT_CODENAMES = 'FRONT_CODENAMES',
FRONT_SPECIAL = 'FRONT_SPECIAL',
WORD_NORMAL = 'WORD_NORMAL',
WORD_PHONETIC = 'WORD_PHONETIC',
WORD_CODENAMES = 'WORD_CODENAMES',
WORD_NUMBER = 'WORD_NUMBER',
WORD_LETTER = 'WORD_LETTER',
}
export const groupTypeDisplayNames = new Map([
[PartGroupType.BACK_NORMAL, 'Normal'],
[PartGroupType.BACK_SPECIAL, 'Special'],
[PartGroupType.FRONT_NORMAL, 'Normal'],
[PartGroupType.FRONT_SPECIAL, 'Special'],
[PartGroupType.FRONT_ANIMALS, 'Animals'],
[PartGroupType.FRONT_CODENAMES, 'Codenames'],
[PartGroupType.WORD_NORMAL, 'Normal'],
[PartGroupType.WORD_NUMBER, 'Numbers'],
[PartGroupType.WORD_LETTER, 'Letter'],
[PartGroupType.WORD_PHONETIC, 'Phonetic'],
[PartGroupType.WORD_CODENAMES, 'Codenames'],
]);
export const backGroupTypes = new Set([
PartGroupType.BACK_NORMAL,
PartGroupType.BACK_SPECIAL,
]);
export const frontGroupTypes = new Set([
PartGroupType.FRONT_NORMAL,
PartGroupType.FRONT_ANIMALS,
PartGroupType.FRONT_CODENAMES,
PartGroupType.FRONT_SPECIAL,
]);
export const wordGroupTypes = new Set([
PartGroupType.WORD_NORMAL,
PartGroupType.WORD_PHONETIC,
PartGroupType.WORD_CODENAMES,
PartGroupType.WORD_NUMBER,
PartGroupType.WORD_LETTER,
]);
export function loadingPartsState(): PartsState {
return {
isLoading: true,
backParts: {},
frontParts: {},
wordParts: {},
};
}
export function successPartsState(json: Record<string, Part>): PartsState {
const backParts: Record<string, Part> = {};
const frontParts: Record<string, Part> = {};
const wordParts: Record<string, Part> = {};
for (const id of Object.keys(json)) {
const part = json[id];
part.path = `/assets/images/${part.path}`;
if (backGroupTypes.has(part.group)) {
backParts[id] = part;
} else if (frontGroupTypes.has(part.group)) {
frontParts[id] = part;
} else if (wordGroupTypes.has(part.group)) {
wordParts[id] = part;
}
}
return {
isLoading: false,
backParts,
frontParts,
wordParts,
};
}
export function errorPartsState(error: Error): PartsState {
return {
isLoading: false,
error,
backParts: {},
frontParts: {},
wordParts: {},
};
}
| 24.657407 | 75 | 0.701089 | 95 | 3 | 0 | 2 | 8 | 9 | 0 | 0 | 11 | 2 | 0 | 11 | 800 | 0.00625 | 0.01 | 0.01125 | 0.0025 | 0 | 0 | 0.5 | 0.220728 | export interface Part {
name;
group;
path;
pathToSmallImage;
}
export interface PartsState {
isLoading;
error?;
backParts;
frontParts;
wordParts;
}
export enum PartGroupType {
BACK_NORMAL = 'BACK_NORMAL',
BACK_SPECIAL = 'BACK_SPECIAL',
FRONT_NORMAL = 'FRONT_NORMAL',
FRONT_ANIMALS = 'FRONT_ANIMALS',
FRONT_CODENAMES = 'FRONT_CODENAMES',
FRONT_SPECIAL = 'FRONT_SPECIAL',
WORD_NORMAL = 'WORD_NORMAL',
WORD_PHONETIC = 'WORD_PHONETIC',
WORD_CODENAMES = 'WORD_CODENAMES',
WORD_NUMBER = 'WORD_NUMBER',
WORD_LETTER = 'WORD_LETTER',
}
export const groupTypeDisplayNames = new Map([
[PartGroupType.BACK_NORMAL, 'Normal'],
[PartGroupType.BACK_SPECIAL, 'Special'],
[PartGroupType.FRONT_NORMAL, 'Normal'],
[PartGroupType.FRONT_SPECIAL, 'Special'],
[PartGroupType.FRONT_ANIMALS, 'Animals'],
[PartGroupType.FRONT_CODENAMES, 'Codenames'],
[PartGroupType.WORD_NORMAL, 'Normal'],
[PartGroupType.WORD_NUMBER, 'Numbers'],
[PartGroupType.WORD_LETTER, 'Letter'],
[PartGroupType.WORD_PHONETIC, 'Phonetic'],
[PartGroupType.WORD_CODENAMES, 'Codenames'],
]);
export const backGroupTypes = new Set([
PartGroupType.BACK_NORMAL,
PartGroupType.BACK_SPECIAL,
]);
export const frontGroupTypes = new Set([
PartGroupType.FRONT_NORMAL,
PartGroupType.FRONT_ANIMALS,
PartGroupType.FRONT_CODENAMES,
PartGroupType.FRONT_SPECIAL,
]);
export const wordGroupTypes = new Set([
PartGroupType.WORD_NORMAL,
PartGroupType.WORD_PHONETIC,
PartGroupType.WORD_CODENAMES,
PartGroupType.WORD_NUMBER,
PartGroupType.WORD_LETTER,
]);
export function loadingPartsState() {
return {
isLoading: true,
backParts: {},
frontParts: {},
wordParts: {},
};
}
export function successPartsState(json) {
const backParts = {};
const frontParts = {};
const wordParts = {};
for (const id of Object.keys(json)) {
const part = json[id];
part.path = `/assets/images/${part.path}`;
if (backGroupTypes.has(part.group)) {
backParts[id] = part;
} else if (frontGroupTypes.has(part.group)) {
frontParts[id] = part;
} else if (wordGroupTypes.has(part.group)) {
wordParts[id] = part;
}
}
return {
isLoading: false,
backParts,
frontParts,
wordParts,
};
}
export function errorPartsState(error) {
return {
isLoading: false,
error,
backParts: {},
frontParts: {},
wordParts: {},
};
}
|
465aca866742965184ee78b911779d2e6a210117 | 3,378 | ts | TypeScript | pipeline/compression/Base91.ts | mlomb/chat-analytics | ce8bb16bee95020171493699d63d4cc74cedd080 | [
"MIT"
] | 34 | 2022-02-04T02:10:50.000Z | 2022-03-27T16:08:53.000Z | pipeline/compression/Base91.ts | mlomb/chat-analytics | ce8bb16bee95020171493699d63d4cc74cedd080 | [
"MIT"
] | null | null | null | pipeline/compression/Base91.ts | mlomb/chat-analytics | ce8bb16bee95020171493699d63d4cc74cedd080 | [
"MIT"
] | 1 | 2022-03-04T14:43:54.000Z | 2022-03-04T14:43:54.000Z | // This is a browser version of https://github.com/Equim-chan/base91
/*
BSD 3-Clause License
Copyright (c) 2017, Equim
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// NOTE: the character "<" was replaced by "-" to avoid problems embedding in HTML ↓
const TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&()*+,./:;-=>?@[]^_`{|}~"';
const B91_LENGTH_DIGITS = 12;
// TODO: use buffers
export const base91encode = (data: Uint8Array): string => {
let ret = (data.length + "").padStart(B91_LENGTH_DIGITS, "0");
const len = data.length;
let i = 0;
let n = 0;
let b = 0;
while (i < len) {
b |= data[i] << n;
n += 8;
if (n > 13) {
let v = b & 8191;
if (v > 88) {
b >>= 13;
n -= 13;
} else {
v = b & 16383;
b >>= 14;
n -= 14;
}
ret += TABLE[v % 91] + TABLE[(v / 91) | 0];
}
i++;
}
if (n) {
ret += TABLE[b % 91];
if (n > 7 || b > 90) ret += TABLE[(b / 91) | 0];
}
return ret;
};
export const base91decode = (data: string): Uint8Array => {
let i = B91_LENGTH_DIGITS;
let k = 0;
let b = 0;
let n = 0;
let v = -1;
const len = data.length;
const outputLength = parseInt(data.slice(0, B91_LENGTH_DIGITS));
const ret = new Uint8Array(outputLength);
while (i < len) {
const p = TABLE.indexOf(data[i]);
if (p === -1) continue;
if (v < 0) {
v = p;
} else {
v += p * 91;
b |= v << n;
n += (v & 8191) > 88 ? 13 : 14;
do {
ret[k++] = b & 0xff;
b >>= 8;
n -= 8;
} while (n > 7);
v = -1;
}
i++;
}
if (v > -1) {
ret[k++] = (b | (v << n)) & 0xff;
}
return ret;
};
| 30.160714 | 108 | 0.589698 | 63 | 2 | 0 | 2 | 19 | 0 | 0 | 0 | 2 | 0 | 0 | 28.5 | 957 | 0.00418 | 0.019854 | 0 | 0 | 0 | 0 | 0.086957 | 0.244661 | // This is a browser version of https://github.com/Equim-chan/base91
/*
BSD 3-Clause License
Copyright (c) 2017, Equim
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// NOTE: the character "<" was replaced by "-" to avoid problems embedding in HTML ↓
const TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&()*+,./:;-=>?@[]^_`{|}~"';
const B91_LENGTH_DIGITS = 12;
// TODO: use buffers
export const base91encode = (data) => {
let ret = (data.length + "").padStart(B91_LENGTH_DIGITS, "0");
const len = data.length;
let i = 0;
let n = 0;
let b = 0;
while (i < len) {
b |= data[i] << n;
n += 8;
if (n > 13) {
let v = b & 8191;
if (v > 88) {
b >>= 13;
n -= 13;
} else {
v = b & 16383;
b >>= 14;
n -= 14;
}
ret += TABLE[v % 91] + TABLE[(v / 91) | 0];
}
i++;
}
if (n) {
ret += TABLE[b % 91];
if (n > 7 || b > 90) ret += TABLE[(b / 91) | 0];
}
return ret;
};
export const base91decode = (data) => {
let i = B91_LENGTH_DIGITS;
let k = 0;
let b = 0;
let n = 0;
let v = -1;
const len = data.length;
const outputLength = parseInt(data.slice(0, B91_LENGTH_DIGITS));
const ret = new Uint8Array(outputLength);
while (i < len) {
const p = TABLE.indexOf(data[i]);
if (p === -1) continue;
if (v < 0) {
v = p;
} else {
v += p * 91;
b |= v << n;
n += (v & 8191) > 88 ? 13 : 14;
do {
ret[k++] = b & 0xff;
b >>= 8;
n -= 8;
} while (n > 7);
v = -1;
}
i++;
}
if (v > -1) {
ret[k++] = (b | (v << n)) & 0xff;
}
return ret;
};
|
46db563dd7e7f7a5daf1c6d96ede4b374aba6ef3 | 1,891 | ts | TypeScript | packages/zero-lib/src/color.ts | 0soft/zero-packages | a3c59ca640eea061bb20cbe60005434f66008c6a | [
"MIT"
] | null | null | null | packages/zero-lib/src/color.ts | 0soft/zero-packages | a3c59ca640eea061bb20cbe60005434f66008c6a | [
"MIT"
] | 1 | 2022-01-28T23:52:58.000Z | 2022-01-28T23:52:58.000Z | packages/zero-lib/src/color.ts | 0soft/zero-packages | a3c59ca640eea061bb20cbe60005434f66008c6a | [
"MIT"
] | null | null | null | interface Color {
red: number;
green: number;
blue: number;
}
export const colorGradient = (
fadeFraction: number,
rgbColor1: Color,
rgbColor2: Color,
rgbColor3?: Color
): Color => {
let color1 = rgbColor1;
let color2 = rgbColor2;
let fade = fadeFraction;
// Do we have 3 colors for the gradient? Need to adjust the params.
if (rgbColor3) {
fade = fade * 2;
// Find which interval to use and adjust the fade percentage
if (fade >= 1) {
fade -= 1;
color1 = rgbColor2;
color2 = rgbColor3;
}
}
const diffRed = color2.red - color1.red;
const diffGreen = color2.green - color1.green;
const diffBlue = color2.blue - color1.blue;
const gradient = {
red: parseInt(Math.floor(color1.red + diffRed * fade).toString(), 10),
green: parseInt(Math.floor(color1.green + diffGreen * fade).toString(), 10),
blue: parseInt(Math.floor(color1.blue + diffBlue * fade).toString(), 10),
};
// return 'rgb(' + gradient.red + ',' + gradient.green + ',' + gradient.blue + ')';
return gradient;
};
export const perc2color = (
perc: number,
maxPerc: number,
color1: Color,
color2: Color,
color3?: Color
): string => {
perc = perc / maxPerc;
if (color3) {
perc = perc * 2;
if (perc >= 1) {
perc -= 1;
color1 = color2;
color2 = color3;
}
}
const diffRed = color2.red - color1.red;
const diffGreen = color2.green - color1.green;
const diffBlue = color2.blue - color1.blue;
const gradient = {
red: parseInt(Math.floor(color1.red + diffRed * perc).toString(), 10),
green: parseInt(Math.floor(color1.green + diffGreen * perc).toString(), 10),
blue: parseInt(Math.floor(color1.blue + diffBlue * perc).toString(), 10),
};
const sum = 0x10000 * gradient.red + 0x100 * gradient.green + 0x1 * gradient.blue;
return '#' + ('000000' + sum.toString(16)).slice(-6);
};
| 27.014286 | 85 | 0.629297 | 59 | 2 | 0 | 9 | 14 | 3 | 0 | 0 | 7 | 1 | 0 | 19.5 | 613 | 0.017945 | 0.022838 | 0.004894 | 0.001631 | 0 | 0 | 0.25 | 0.28902 | interface Color {
red;
green;
blue;
}
export const colorGradient = (
fadeFraction,
rgbColor1,
rgbColor2,
rgbColor3?
) => {
let color1 = rgbColor1;
let color2 = rgbColor2;
let fade = fadeFraction;
// Do we have 3 colors for the gradient? Need to adjust the params.
if (rgbColor3) {
fade = fade * 2;
// Find which interval to use and adjust the fade percentage
if (fade >= 1) {
fade -= 1;
color1 = rgbColor2;
color2 = rgbColor3;
}
}
const diffRed = color2.red - color1.red;
const diffGreen = color2.green - color1.green;
const diffBlue = color2.blue - color1.blue;
const gradient = {
red: parseInt(Math.floor(color1.red + diffRed * fade).toString(), 10),
green: parseInt(Math.floor(color1.green + diffGreen * fade).toString(), 10),
blue: parseInt(Math.floor(color1.blue + diffBlue * fade).toString(), 10),
};
// return 'rgb(' + gradient.red + ',' + gradient.green + ',' + gradient.blue + ')';
return gradient;
};
export const perc2color = (
perc,
maxPerc,
color1,
color2,
color3?
) => {
perc = perc / maxPerc;
if (color3) {
perc = perc * 2;
if (perc >= 1) {
perc -= 1;
color1 = color2;
color2 = color3;
}
}
const diffRed = color2.red - color1.red;
const diffGreen = color2.green - color1.green;
const diffBlue = color2.blue - color1.blue;
const gradient = {
red: parseInt(Math.floor(color1.red + diffRed * perc).toString(), 10),
green: parseInt(Math.floor(color1.green + diffGreen * perc).toString(), 10),
blue: parseInt(Math.floor(color1.blue + diffBlue * perc).toString(), 10),
};
const sum = 0x10000 * gradient.red + 0x100 * gradient.green + 0x1 * gradient.blue;
return '#' + ('000000' + sum.toString(16)).slice(-6);
};
|
045b699adff8faf61fdd5d17b9b56462562bfdc0 | 911 | ts | TypeScript | parser/src/token.ts | biowaffeln/cooklang | 037717dcbf588eb326cb306e19aa06d035ec536a | [
"MIT"
] | 21 | 2022-01-21T17:39:40.000Z | 2022-03-16T20:24:30.000Z | parser/src/token.ts | biowaffeln/cooklang | 037717dcbf588eb326cb306e19aa06d035ec536a | [
"MIT"
] | 2 | 2022-03-08T14:04:46.000Z | 2022-03-15T14:28:21.000Z | parser/src/token.ts | biowaffeln/cooklang | 037717dcbf588eb326cb306e19aa06d035ec536a | [
"MIT"
] | 1 | 2022-03-13T21:36:34.000Z | 2022-03-13T21:36:34.000Z | export interface TextToken {
type: "text";
value: string;
}
export interface IngredientToken {
type: "ingredient";
name: string;
quantity: string | number;
units: string;
}
export interface CookwareToken {
type: "cookware";
name: string;
quantity: string | number;
}
export interface TimerToken {
type: "timer";
name: string;
quantity: string | number;
units: string;
}
export const text = (value: string): TextToken => ({
type: "text",
value,
});
export const ingredient = (
name: string,
quantity: string | number,
units: string
): IngredientToken => ({
type: "ingredient",
name,
quantity,
units,
});
export const cookware = (
name: string,
quantity: string | number
): CookwareToken => ({
type: "cookware",
name,
quantity,
});
export const timer = (
name: string,
quantity: string | number,
units: string
): TimerToken => ({
type: "timer",
name,
quantity,
units,
});
| 14.934426 | 52 | 0.667398 | 53 | 4 | 0 | 9 | 4 | 13 | 0 | 0 | 24 | 4 | 0 | 5.25 | 307 | 0.042345 | 0.013029 | 0.042345 | 0.013029 | 0 | 0 | 0.8 | 0.331709 | export interface TextToken {
type;
value;
}
export interface IngredientToken {
type;
name;
quantity;
units;
}
export interface CookwareToken {
type;
name;
quantity;
}
export interface TimerToken {
type;
name;
quantity;
units;
}
export const text = (value) => ({
type: "text",
value,
});
export const ingredient = (
name,
quantity,
units
) => ({
type: "ingredient",
name,
quantity,
units,
});
export const cookware = (
name,
quantity
) => ({
type: "cookware",
name,
quantity,
});
export const timer = (
name,
quantity,
units
) => ({
type: "timer",
name,
quantity,
units,
});
|
049d44af639197bb983370ed9c905cd9cb9e60c5 | 1,633 | ts | TypeScript | src/date-string.ts | whitphx/react-date-select | 557bd2a187d8fe2785cf7c1dcd42f1ba64c540d5 | [
"MIT"
] | null | null | null | src/date-string.ts | whitphx/react-date-select | 557bd2a187d8fe2785cf7c1dcd42f1ba64c540d5 | [
"MIT"
] | 1 | 2022-03-19T15:08:21.000Z | 2022-03-19T15:08:21.000Z | src/date-string.ts | whitphx/react-date-select | 557bd2a187d8fe2785cf7c1dcd42f1ba64c540d5 | [
"MIT"
] | null | null | null | function padZero(value: number, digits: number): string {
// This implementation is only to be used from `compileDateString()`,
// assuming the `value` is a positive integer.
// Negative or floating numbers as inputs can lead to unexpected results.
return ("0".repeat(digits - 1) + value.toString()).slice(-digits);
}
export function compileDateString(
year: number,
month: number,
day: number
): string | null {
// Create a date string in the format of `yyyy-MM-dd`.
// For the detailed specs of the format, see https://developer.mozilla.org/en-US/docs/Web/HTML/Date_and_time_formats#date_strings
if (month < 1 || 12 < month) {
return null;
}
if (day < 1 || 31 < day) {
return null;
}
const dateString =
padZero(year, 4) + "-" + padZero(month, 2) + "-" + padZero(day, 2);
const dateObj = new Date(dateString);
if (
dateObj.getFullYear() !== year ||
dateObj.getMonth() !== month - 1 ||
dateObj.getDate() !== day
) {
return null;
}
return dateString;
}
export function parseDateString(dateString: string): {
year: string;
month: string;
day: string;
} {
const date = new Date(dateString);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
if (isNaN(year) || isNaN(month) || isNaN(day)) {
return { year: "", month: "", day: "" };
}
return {
year: year.toString(),
month: month.toString(),
day: day.toString(),
};
}
export function getDateString(date: Date): string | null {
return compileDateString(
date.getFullYear(),
date.getMonth() + 1,
date.getDate()
);
}
| 25.123077 | 131 | 0.635028 | 51 | 4 | 0 | 7 | 6 | 0 | 2 | 0 | 12 | 0 | 0 | 8.75 | 471 | 0.023355 | 0.012739 | 0 | 0 | 0 | 0 | 0.705882 | 0.265922 | /* Example usages of 'padZero' are shown below:
padZero(year, 4) + "-" + padZero(month, 2) + "-" + padZero(day, 2);
*/
function padZero(value, digits) {
// This implementation is only to be used from `compileDateString()`,
// assuming the `value` is a positive integer.
// Negative or floating numbers as inputs can lead to unexpected results.
return ("0".repeat(digits - 1) + value.toString()).slice(-digits);
}
export /* Example usages of 'compileDateString' are shown below:
compileDateString(date.getFullYear(), date.getMonth() + 1, date.getDate());
*/
function compileDateString(
year,
month,
day
) {
// Create a date string in the format of `yyyy-MM-dd`.
// For the detailed specs of the format, see https://developer.mozilla.org/en-US/docs/Web/HTML/Date_and_time_formats#date_strings
if (month < 1 || 12 < month) {
return null;
}
if (day < 1 || 31 < day) {
return null;
}
const dateString =
padZero(year, 4) + "-" + padZero(month, 2) + "-" + padZero(day, 2);
const dateObj = new Date(dateString);
if (
dateObj.getFullYear() !== year ||
dateObj.getMonth() !== month - 1 ||
dateObj.getDate() !== day
) {
return null;
}
return dateString;
}
export function parseDateString(dateString) {
const date = new Date(dateString);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
if (isNaN(year) || isNaN(month) || isNaN(day)) {
return { year: "", month: "", day: "" };
}
return {
year: year.toString(),
month: month.toString(),
day: day.toString(),
};
}
export function getDateString(date) {
return compileDateString(
date.getFullYear(),
date.getMonth() + 1,
date.getDate()
);
}
|
1737ab8f9cf16019f48c8d6a4c382ac7ebf7a1e3 | 2,619 | ts | TypeScript | utils/helper.ts | avaneeshtripathi/type-generator | 26125ed6168e976e61637afc93fd5ff73f780a0b | [
"MIT"
] | 2 | 2022-03-08T11:05:47.000Z | 2022-03-25T09:59:19.000Z | utils/helper.ts | avaneeshtripathi/type-generator | 26125ed6168e976e61637afc93fd5ff73f780a0b | [
"MIT"
] | 3 | 2022-03-25T21:48:24.000Z | 2022-03-25T23:53:21.000Z | utils/helper.ts | avaneeshtripathi/type-generator | 26125ed6168e976e61637afc93fd5ff73f780a0b | [
"MIT"
] | null | null | null | const getFormattedTypeLabel = (label: string) => {
return label
.split("_")
.map((each) => each.charAt(0).toUpperCase() + each.substring(1))
.join("");
};
const getFormattedKey = (key: string) => {
return key.includes(" ") ? `"${key}"` : key;
};
export const getStringifiedTypes = (
jsonData: Record<string, any>,
spacing: string,
label: string,
format: boolean
) => {
/** More things to come up here */
return getTypeForObject(jsonData, spacing, label, [], format).join("");
};
export const getTypeForObject = (
obj: Record<string, any>,
spacing: string,
name: string,
typesStrArr: string[],
isTFormat: boolean
) => {
let typesStr = isTFormat ? `type T${name} = ` : `type ${name}Type = `;
if (typeof obj === "object" && obj !== null && !Array.isArray(obj)) {
typesStr += "{\n";
Object.keys(obj).forEach((key) => {
if (typeof obj[key] === "object") {
if (obj[key] === null) {
typesStr += `${spacing}${getFormattedKey(key)}: null;\n`;
} else if (Array.isArray(obj[key])) {
const keyName = getFormattedTypeLabel(
`${name}_${key.replace(/ /g, "_")}`
);
typesStr += isTFormat
? `${spacing}${getFormattedKey(key)}: T${keyName}[];\n`
: `${spacing}${getFormattedKey(key)}: ${keyName}Type[];\n`;
getTypeForObject(
obj[key][0],
spacing,
keyName,
typesStrArr,
isTFormat
);
/**
* More logic needs to be added here to check for
* 1. optional parameters in array of objects
* 2. an array consisting multiple types like (string | number) etc
*/
} else {
const keyName = getFormattedTypeLabel(
`${name}_${key.replace(/ /g, "_")}`
);
typesStr += isTFormat
? `${spacing}${getFormattedKey(key)}: T${keyName};\n`
: `${spacing}${getFormattedKey(key)}: ${keyName}Type;\n`;
getTypeForObject(obj[key], spacing, keyName, typesStrArr, isTFormat);
}
} else {
typesStr += `${spacing}${getFormattedKey(key)}: ${typeof obj[key]};\n`;
}
});
typesStr += "}";
} else if (Array.isArray(obj)) {
const keyName = getFormattedTypeLabel(`${name}_HelloWorldArr`);
typesStr += isTFormat ? `T${keyName}[];\n` : `${keyName}Type[];\n`;
getTypeForObject(obj[0], spacing, keyName, typesStrArr, isTFormat);
} else {
typesStr += `${obj === null ? "null" : typeof obj};`;
}
typesStrArr.push(typesStr + "\n\n");
return typesStrArr;
};
| 32.333333 | 79 | 0.547919 | 69 | 6 | 0 | 13 | 8 | 0 | 3 | 2 | 11 | 0 | 4 | 13.333333 | 711 | 0.026723 | 0.011252 | 0 | 0 | 0.005626 | 0.074074 | 0.407407 | 0.267581 | /* Example usages of 'getFormattedTypeLabel' are shown below:
getFormattedTypeLabel(`${name}_${key.replace(/ /g, "_")}`);
getFormattedTypeLabel(`${name}_HelloWorldArr`);
*/
const getFormattedTypeLabel = (label) => {
return label
.split("_")
.map((each) => each.charAt(0).toUpperCase() + each.substring(1))
.join("");
};
/* Example usages of 'getFormattedKey' are shown below:
getFormattedKey(key);
*/
const getFormattedKey = (key) => {
return key.includes(" ") ? `"${key}"` : key;
};
export const getStringifiedTypes = (
jsonData,
spacing,
label,
format
) => {
/** More things to come up here */
return getTypeForObject(jsonData, spacing, label, [], format).join("");
};
export /* Example usages of 'getTypeForObject' are shown below:
getTypeForObject(jsonData, spacing, label, [], format).join("");
getTypeForObject(obj[key][0], spacing, keyName, typesStrArr, isTFormat);
getTypeForObject(obj[key], spacing, keyName, typesStrArr, isTFormat);
getTypeForObject(obj[0], spacing, keyName, typesStrArr, isTFormat);
*/
const getTypeForObject = (
obj,
spacing,
name,
typesStrArr,
isTFormat
) => {
let typesStr = isTFormat ? `type T${name} = ` : `type ${name}Type = `;
if (typeof obj === "object" && obj !== null && !Array.isArray(obj)) {
typesStr += "{\n";
Object.keys(obj).forEach((key) => {
if (typeof obj[key] === "object") {
if (obj[key] === null) {
typesStr += `${spacing}${getFormattedKey(key)}: null;\n`;
} else if (Array.isArray(obj[key])) {
const keyName = getFormattedTypeLabel(
`${name}_${key.replace(/ /g, "_")}`
);
typesStr += isTFormat
? `${spacing}${getFormattedKey(key)}: T${keyName}[];\n`
: `${spacing}${getFormattedKey(key)}: ${keyName}Type[];\n`;
getTypeForObject(
obj[key][0],
spacing,
keyName,
typesStrArr,
isTFormat
);
/**
* More logic needs to be added here to check for
* 1. optional parameters in array of objects
* 2. an array consisting multiple types like (string | number) etc
*/
} else {
const keyName = getFormattedTypeLabel(
`${name}_${key.replace(/ /g, "_")}`
);
typesStr += isTFormat
? `${spacing}${getFormattedKey(key)}: T${keyName};\n`
: `${spacing}${getFormattedKey(key)}: ${keyName}Type;\n`;
getTypeForObject(obj[key], spacing, keyName, typesStrArr, isTFormat);
}
} else {
typesStr += `${spacing}${getFormattedKey(key)}: ${typeof obj[key]};\n`;
}
});
typesStr += "}";
} else if (Array.isArray(obj)) {
const keyName = getFormattedTypeLabel(`${name}_HelloWorldArr`);
typesStr += isTFormat ? `T${keyName}[];\n` : `${keyName}Type[];\n`;
getTypeForObject(obj[0], spacing, keyName, typesStrArr, isTFormat);
} else {
typesStr += `${obj === null ? "null" : typeof obj};`;
}
typesStrArr.push(typesStr + "\n\n");
return typesStrArr;
};
|
7e3097b403ff2f08b30c7052caf73efb460e75bf | 5,980 | ts | TypeScript | src/swaggerDiff.ts | psrabhishek/vscode-swagger-diff | c739ce49fa889a1125d616f19e615b2ee1bbba0e | [
"MIT"
] | 1 | 2022-01-10T17:25:14.000Z | 2022-01-10T17:25:14.000Z | src/swaggerDiff.ts | psrabhishek/vscode-swagger-diff | c739ce49fa889a1125d616f19e615b2ee1bbba0e | [
"MIT"
] | null | null | null | src/swaggerDiff.ts | psrabhishek/vscode-swagger-diff | c739ce49fa889a1125d616f19e615b2ee1bbba0e | [
"MIT"
] | null | null | null | var cssStyles = `
<style>
table, th, td {
border: 1px solid darkgray;
border-collapse: collapse;
padding: 5px;
}
</style>
`;
var htmlTemplateStart = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Swagger Diff</title>` +
cssStyles +
`</head>
<body>
`;
var htmlTemplateEnd = `
</table>
</body>
</html>`;
// This is needed to enable actions like selectAll(ctrl+a), copy (ctrl+c) in the webView iFrame
// Refer: https://github.com/microsoft/vscode/issues/65452#issuecomment-586485815
var enableContextActionsScript = `
<script type="text/javascript">
document.addEventListener('keydown', e => {
const obj = {
altKey: e.altKey,
code: e.code,
ctrlKey: e.ctrlKey,
isComposing: e.isComposing,
key: e.key,
location: e.location,
metaKey: e.metaKey,
repeat: e.repeat,
shiftKey: e.shiftKey
}
window.parent.postMessage( JSON.stringify(obj), '*');
})
</script>`;
// Construct a HTML Table from the Swagger Diff
export function getSwaggerDiffTable(diff: any) {
var htmlContent = htmlTemplateStart;
htmlContent += enableContextActionsScript;
htmlContent += "\t<h2>ChangeLog</h2>\n" +
"\t<hr/>\n";
// Populate the changes tables, level by level
htmlContent += getDiffTable(diff.errors, "Errors - Breaking Changes");
htmlContent += getDiffTable(diff.warnings, "Warnings - Smooth Changes");
htmlContent += getRawDiffTable(diff.unmatchDiffs, "UnCategorized");
htmlContent += getDiffTable(diff.infos, "Infos");
return htmlContent + htmlTemplateEnd;
}
function diffReplacer(key: any, value: any) {
// Filtering out properties
if (key === 'ruleId' || key === 'message') {
return undefined;
}
return value;
}
function rawDiffReplacer(key: any, value: any) {
// Filtering out properties
if (key === 'kind' || key === 'path') {
return undefined;
}
return value;
}
function getChangeType(type: string) {
if (type === 'N') {
return "Newly Added";
}
if (type === 'D') {
return "Deleted";
}
if (type === 'E') {
return "Modified";
}
if (type === 'A') {
return "Changes within Array";
}
return "Unkown";
}
function getDiffBody(diff: any, indent: string) {
if (typeof diff === 'string') {
return diff;
}
var body = "";
var childIndent = indent;
if (indent === "") {
childIndent = "└─ ";
}
else {
body = "<br/>";
}
var body = "";
for (var key in diff) {
if (key === 'ruleId' || key === 'message') {
continue;
}
body += indent + "<b>" + key + "</b>: " + getDiffBody(diff[key], "  " + childIndent) + "<br/>";
}
if (body === "") {
return "<b>NA</b>";
}
if (body === "<br/>") {
return "";
}
return body.replace("<br/><br/>", "<br/>").replace(/\<br\/\>+$/, "");
}
function getRawDiffBody(diff: any, indent: string) {
if (typeof diff === 'string') {
return diff;
}
var body = "";
var printKey = "";
var childIndent = indent;
if (indent === "") {
childIndent = "└─ ";
}
else {
body = "<br/>";
}
for (var key in diff) {
if (key === 'kind' || key === 'path') {
continue;
}
else if (key === "lhs") {
printKey = "old";
}
else if (key === "rhs") {
printKey = "new";
}
else {
printKey = key;
}
body += indent + "<b>" + printKey + "</b>: " + getRawDiffBody(diff[key], "  " + childIndent) + "<br/>";
}
if (body === "") {
return "<b>NA</b>";
}
if (body === "<br/>") {
return "";
}
return body.replace("<br/><br/>", "<br/>").replace(/\<br\/\>+$/, "");
}
function getDiffTable(diff: any[], type: string) {
var len = diff.length;
if (len === 0) {
return "";
}
var htmlContent = "\t<h3>" + type + "</h3>\n" +
"\t<table>\n" +
"\t\t<tr>\n" +
"\t\t\t<th>Change Type</th>\n" +
"\t\t\t<th>Shot Description</th>\n" +
"\t\t\t<th>Description</th>\n" +
"\t\t</tr>\n";
var i = 0;
for (i = 0; i < diff.length; i++) {
htmlContent += "\t\t<tr>\n" +
"\t\t\t<td>" + diff[i].ruleId + "</td>\n" +
"\t\t\t<td>" + diff[i].message + "</td>\n" +
// "\t\t\t<td>"+JSON.stringify(diff[i], diffReplacer) + "</td>\n"+
"\t\t\t<td>" + getDiffBody(diff[i], "") + "</td>\n" +
"\t\t</tr>\n";
};
htmlContent += "\t</table>\n";
return htmlContent;
}
function getRawDiffTable(diff: any[], type: string) {
var len = diff.length;
if (len === 0) {
return "";
}
var htmlContent = "\t<h3>" + type + "</h3>\n" +
"\t<table>\n" +
"\t\t<tr>\n" +
"\t\t\t<th>Change Type</th>\n" +
"\t\t\t<th>Shot Description</th>\n" +
"\t\t\t<th>Description</th>\n" +
"\t\t</tr>\n";
var i = 0;
for (i = 0; i < diff.length; i++) {
htmlContent += "\t\t<tr>\n" +
"\t\t\t<td>" + getChangeType(diff[i].kind) + "</td>\n" +
"\t\t\t<td>" + diff[i].path.join("/") + "</td>\n" +
// "\t\t\t<td>"+JSON.stringify(diff[i], rawDiffReplacer) + "</td>\n"+
"\t\t\t<td>" + getRawDiffBody(diff[i], "") + "</td>\n" +
"\t\t</tr>\n";
};
htmlContent += "\t</table>\n";
return htmlContent;
}
| 27.431193 | 122 | 0.472742 | 187 | 8 | 0 | 14 | 17 | 0 | 5 | 9 | 5 | 0 | 2 | 16.375 | 1,812 | 0.012141 | 0.009382 | 0 | 0 | 0.001104 | 0.230769 | 0.128205 | 0.226409 | var cssStyles = `
<style>
table, th, td {
border: 1px solid darkgray;
border-collapse: collapse;
padding: 5px;
}
</style>
`;
var htmlTemplateStart = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Swagger Diff</title>` +
cssStyles +
`</head>
<body>
`;
var htmlTemplateEnd = `
</table>
</body>
</html>`;
// This is needed to enable actions like selectAll(ctrl+a), copy (ctrl+c) in the webView iFrame
// Refer: https://github.com/microsoft/vscode/issues/65452#issuecomment-586485815
var enableContextActionsScript = `
<script type="text/javascript">
document.addEventListener('keydown', e => {
const obj = {
altKey: e.altKey,
code: e.code,
ctrlKey: e.ctrlKey,
isComposing: e.isComposing,
key: e.key,
location: e.location,
metaKey: e.metaKey,
repeat: e.repeat,
shiftKey: e.shiftKey
}
window.parent.postMessage( JSON.stringify(obj), '*');
})
</script>`;
// Construct a HTML Table from the Swagger Diff
export function getSwaggerDiffTable(diff) {
var htmlContent = htmlTemplateStart;
htmlContent += enableContextActionsScript;
htmlContent += "\t<h2>ChangeLog</h2>\n" +
"\t<hr/>\n";
// Populate the changes tables, level by level
htmlContent += getDiffTable(diff.errors, "Errors - Breaking Changes");
htmlContent += getDiffTable(diff.warnings, "Warnings - Smooth Changes");
htmlContent += getRawDiffTable(diff.unmatchDiffs, "UnCategorized");
htmlContent += getDiffTable(diff.infos, "Infos");
return htmlContent + htmlTemplateEnd;
}
function diffReplacer(key, value) {
// Filtering out properties
if (key === 'ruleId' || key === 'message') {
return undefined;
}
return value;
}
function rawDiffReplacer(key, value) {
// Filtering out properties
if (key === 'kind' || key === 'path') {
return undefined;
}
return value;
}
/* Example usages of 'getChangeType' are shown below:
htmlContent += "\t\t<tr>\n" +
"\t\t\t<td>" + getChangeType(diff[i].kind) + "</td>\n" +
"\t\t\t<td>" + diff[i].path.join("/") + "</td>\n" +
// "\t\t\t<td>"+JSON.stringify(diff[i], rawDiffReplacer) + "</td>\n"+
"\t\t\t<td>" + getRawDiffBody(diff[i], "") + "</td>\n" +
"\t\t</tr>\n";
*/
function getChangeType(type) {
if (type === 'N') {
return "Newly Added";
}
if (type === 'D') {
return "Deleted";
}
if (type === 'E') {
return "Modified";
}
if (type === 'A') {
return "Changes within Array";
}
return "Unkown";
}
/* Example usages of 'getDiffBody' are shown below:
body += indent + "<b>" + key + "</b>: " + getDiffBody(diff[key], "  " + childIndent) + "<br/>";
htmlContent += "\t\t<tr>\n" +
"\t\t\t<td>" + diff[i].ruleId + "</td>\n" +
"\t\t\t<td>" + diff[i].message + "</td>\n" +
// "\t\t\t<td>"+JSON.stringify(diff[i], diffReplacer) + "</td>\n"+
"\t\t\t<td>" + getDiffBody(diff[i], "") + "</td>\n" +
"\t\t</tr>\n";
*/
function getDiffBody(diff, indent) {
if (typeof diff === 'string') {
return diff;
}
var body = "";
var childIndent = indent;
if (indent === "") {
childIndent = "└─ ";
}
else {
body = "<br/>";
}
var body = "";
for (var key in diff) {
if (key === 'ruleId' || key === 'message') {
continue;
}
body += indent + "<b>" + key + "</b>: " + getDiffBody(diff[key], "  " + childIndent) + "<br/>";
}
if (body === "") {
return "<b>NA</b>";
}
if (body === "<br/>") {
return "";
}
return body.replace("<br/><br/>", "<br/>").replace(/\<br\/\>+$/, "");
}
/* Example usages of 'getRawDiffBody' are shown below:
body += indent + "<b>" + printKey + "</b>: " + getRawDiffBody(diff[key], "  " + childIndent) + "<br/>";
htmlContent += "\t\t<tr>\n" +
"\t\t\t<td>" + getChangeType(diff[i].kind) + "</td>\n" +
"\t\t\t<td>" + diff[i].path.join("/") + "</td>\n" +
// "\t\t\t<td>"+JSON.stringify(diff[i], rawDiffReplacer) + "</td>\n"+
"\t\t\t<td>" + getRawDiffBody(diff[i], "") + "</td>\n" +
"\t\t</tr>\n";
*/
function getRawDiffBody(diff, indent) {
if (typeof diff === 'string') {
return diff;
}
var body = "";
var printKey = "";
var childIndent = indent;
if (indent === "") {
childIndent = "└─ ";
}
else {
body = "<br/>";
}
for (var key in diff) {
if (key === 'kind' || key === 'path') {
continue;
}
else if (key === "lhs") {
printKey = "old";
}
else if (key === "rhs") {
printKey = "new";
}
else {
printKey = key;
}
body += indent + "<b>" + printKey + "</b>: " + getRawDiffBody(diff[key], "  " + childIndent) + "<br/>";
}
if (body === "") {
return "<b>NA</b>";
}
if (body === "<br/>") {
return "";
}
return body.replace("<br/><br/>", "<br/>").replace(/\<br\/\>+$/, "");
}
/* Example usages of 'getDiffTable' are shown below:
// Populate the changes tables, level by level
htmlContent += getDiffTable(diff.errors, "Errors - Breaking Changes");
htmlContent += getDiffTable(diff.warnings, "Warnings - Smooth Changes");
htmlContent += getDiffTable(diff.infos, "Infos");
*/
function getDiffTable(diff, type) {
var len = diff.length;
if (len === 0) {
return "";
}
var htmlContent = "\t<h3>" + type + "</h3>\n" +
"\t<table>\n" +
"\t\t<tr>\n" +
"\t\t\t<th>Change Type</th>\n" +
"\t\t\t<th>Shot Description</th>\n" +
"\t\t\t<th>Description</th>\n" +
"\t\t</tr>\n";
var i = 0;
for (i = 0; i < diff.length; i++) {
htmlContent += "\t\t<tr>\n" +
"\t\t\t<td>" + diff[i].ruleId + "</td>\n" +
"\t\t\t<td>" + diff[i].message + "</td>\n" +
// "\t\t\t<td>"+JSON.stringify(diff[i], diffReplacer) + "</td>\n"+
"\t\t\t<td>" + getDiffBody(diff[i], "") + "</td>\n" +
"\t\t</tr>\n";
};
htmlContent += "\t</table>\n";
return htmlContent;
}
/* Example usages of 'getRawDiffTable' are shown below:
htmlContent += getRawDiffTable(diff.unmatchDiffs, "UnCategorized");
*/
function getRawDiffTable(diff, type) {
var len = diff.length;
if (len === 0) {
return "";
}
var htmlContent = "\t<h3>" + type + "</h3>\n" +
"\t<table>\n" +
"\t\t<tr>\n" +
"\t\t\t<th>Change Type</th>\n" +
"\t\t\t<th>Shot Description</th>\n" +
"\t\t\t<th>Description</th>\n" +
"\t\t</tr>\n";
var i = 0;
for (i = 0; i < diff.length; i++) {
htmlContent += "\t\t<tr>\n" +
"\t\t\t<td>" + getChangeType(diff[i].kind) + "</td>\n" +
"\t\t\t<td>" + diff[i].path.join("/") + "</td>\n" +
// "\t\t\t<td>"+JSON.stringify(diff[i], rawDiffReplacer) + "</td>\n"+
"\t\t\t<td>" + getRawDiffBody(diff[i], "") + "</td>\n" +
"\t\t</tr>\n";
};
htmlContent += "\t</table>\n";
return htmlContent;
}
|
7e354f04c885ce2a26810bc9f02689c4dbb5f0f8 | 2,389 | ts | TypeScript | src/utils.ts | yoki31/vscode-wakatime | 5b26fab4b046dd3155e8c20da0781fa93807f156 | [
"BSD-3-Clause"
] | 1 | 2022-01-09T10:49:09.000Z | 2022-01-09T10:49:09.000Z | src/utils.ts | yoki31/vscode-wakatime | 5b26fab4b046dd3155e8c20da0781fa93807f156 | [
"BSD-3-Clause"
] | 1 | 2022-02-28T01:57:13.000Z | 2022-02-28T01:57:13.000Z | src/utils.ts | yoki31/vscode-wakatime | 5b26fab4b046dd3155e8c20da0781fa93807f156 | [
"BSD-3-Clause"
] | null | null | null | export class Utils {
public static quote(str: string): string {
if (str.includes(' ')) return `"${str.replace('"', '\\"')}"`;
return str;
}
public static validateKey(key: string): string {
const err = 'Invalid api key... check https://wakatime.com/settings for your key';
if (!key) return err;
const re = new RegExp(
'^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$',
'i',
);
if (!re.test(key)) return err;
return '';
}
public static validateProxy(proxy: string): string {
if (!proxy) return '';
let re;
if (proxy.indexOf('\\') === -1) {
re = new RegExp('^((https?|socks5)://)?([^:@]+(:([^:@])+)?@)?[\\w\\.-]+(:\\d+)?$', 'i');
} else {
re = new RegExp('^.*\\\\.+$', 'i');
}
if (!re.test(proxy))
return 'Invalid proxy. Valid formats are https://user:pass@host:port or socks5://user:pass@host:port or domain\\user:pass';
return '';
}
public static formatDate(date: Date): String {
let months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
let ampm = 'AM';
let hour = date.getHours();
if (hour > 11) {
ampm = 'PM';
hour = hour - 12;
}
if (hour == 0) {
hour = 12;
}
let minute = date.getMinutes();
return `${months[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()} ${hour}:${
minute < 10 ? `0${minute}` : minute
} ${ampm}`;
}
public static obfuscateKey(key: string): string {
let newKey = '';
if (key) {
newKey = key;
if (key.length > 4)
newKey = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX' + key.substring(key.length - 4);
}
return newKey;
}
public static wrapArg(arg: string): string {
if (arg.indexOf(' ') > -1) return '"' + arg.replace(/"/g, '\\"') + '"';
return arg;
}
public static formatArguments(binary: string, args: string[]): string {
let clone = args.slice(0);
clone.unshift(this.wrapArg(binary));
let newCmds: string[] = [];
let lastCmd = '';
for (let i = 0; i < clone.length; i++) {
if (lastCmd == '--key') newCmds.push(this.wrapArg(this.obfuscateKey(clone[i])));
else newCmds.push(this.wrapArg(clone[i]));
lastCmd = clone[i];
}
return newCmds.join(' ');
}
}
| 26.842697 | 129 | 0.515278 | 82 | 7 | 0 | 8 | 12 | 0 | 2 | 0 | 14 | 1 | 0 | 9.428571 | 764 | 0.019634 | 0.015707 | 0 | 0.001309 | 0 | 0 | 0.518519 | 0.269267 | export class Utils {
public static quote(str) {
if (str.includes(' ')) return `"${str.replace('"', '\\"')}"`;
return str;
}
public static validateKey(key) {
const err = 'Invalid api key... check https://wakatime.com/settings for your key';
if (!key) return err;
const re = new RegExp(
'^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$',
'i',
);
if (!re.test(key)) return err;
return '';
}
public static validateProxy(proxy) {
if (!proxy) return '';
let re;
if (proxy.indexOf('\\') === -1) {
re = new RegExp('^((https?|socks5)://)?([^:@]+(:([^:@])+)?@)?[\\w\\.-]+(:\\d+)?$', 'i');
} else {
re = new RegExp('^.*\\\\.+$', 'i');
}
if (!re.test(proxy))
return 'Invalid proxy. Valid formats are https://user:pass@host:port or socks5://user:pass@host:port or domain\\user:pass';
return '';
}
public static formatDate(date) {
let months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
let ampm = 'AM';
let hour = date.getHours();
if (hour > 11) {
ampm = 'PM';
hour = hour - 12;
}
if (hour == 0) {
hour = 12;
}
let minute = date.getMinutes();
return `${months[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()} ${hour}:${
minute < 10 ? `0${minute}` : minute
} ${ampm}`;
}
public static obfuscateKey(key) {
let newKey = '';
if (key) {
newKey = key;
if (key.length > 4)
newKey = 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX' + key.substring(key.length - 4);
}
return newKey;
}
public static wrapArg(arg) {
if (arg.indexOf(' ') > -1) return '"' + arg.replace(/"/g, '\\"') + '"';
return arg;
}
public static formatArguments(binary, args) {
let clone = args.slice(0);
clone.unshift(this.wrapArg(binary));
let newCmds = [];
let lastCmd = '';
for (let i = 0; i < clone.length; i++) {
if (lastCmd == '--key') newCmds.push(this.wrapArg(this.obfuscateKey(clone[i])));
else newCmds.push(this.wrapArg(clone[i]));
lastCmd = clone[i];
}
return newCmds.join(' ');
}
}
|
7e9aa85a58a0a0ce18cbf9ecdb0687082bf8c3af | 1,861 | ts | TypeScript | apps/mobile-providers/src/@libs/elsa-ui/theme/index.ts | Elsa-Health/mammoth | afdf8453b75ed414a1438bb78309e8649ae7e20b | [
"Apache-2.0"
] | 3 | 2022-03-03T17:43:39.000Z | 2022-03-08T23:26:23.000Z | apps/mobile-providers/src/@libs/elsa-ui/theme/index.ts | Elsa-Health/mammoth | afdf8453b75ed414a1438bb78309e8649ae7e20b | [
"Apache-2.0"
] | 3 | 2022-03-10T09:23:00.000Z | 2022-03-18T14:14:16.000Z | apps/mobile-providers/src/@libs/elsa-ui/theme/index.ts | Elsa-Health/mammoth | afdf8453b75ed414a1438bb78309e8649ae7e20b | [
"Apache-2.0"
] | null | null | null | export type fontFamiliStyleType =
| 'light'
| 'normal'
| 'medium'
| 'bold'
| 'black'
| 'extra-black';
export const fontFamilyStyle = (
props: {italic?: boolean; font?: fontFamiliStyleType} = {},
) => {
if (props.italic !== undefined) {
if (props.italic) {
// italic fonts
switch (props.font || 'normal') {
case 'light':
return 'AvenirLTStd-LightOblique';
case 'medium':
return 'AvenirLTStd-MediumOblique';
case 'bold':
return 'AvenirLTStd-HeavyOblique';
case 'black':
return 'AvenirLTStd-BookOblique';
case 'extra-black':
return 'AvenirLTStd-BlackOblique';
case 'normal':
default:
return 'AvenirLTStd-Oblique';
}
}
}
switch (props.font || 'normal') {
case 'light':
return 'AvenirLTStd-Light';
case 'medium':
return 'AvenirLTStd-Medium';
case 'bold':
return 'AvenirLTStd-Heavy';
case 'black':
return 'AvenirLTStd-Book';
case 'extra-black':
return 'AvenirLTStd-Black';
case 'normal':
default:
return 'AvenirLTStd-Roman';
}
};
export const Color = {
primary: {
base: '#4665AF',
light: '#7992e1',
dark: '#003b7f',
},
secondary: {
base: '#5558A6',
light: '#8685d8',
dark: '#222f77', // can change in the future
},
};
export const Spacing = {
xs: 4,
sm: 8,
md: 16,
lg: 24,
xl: 32,
'2xl': 48,
};
export const Typography = {
fontFamilyStyle,
sizes: {
xs: '12px',
sm: '14px',
md: '16px',
lg: '20px',
xl: '24px',
'2xl': '28px',
},
};
export default {
/**
* Created from:
* https://material.io/resources/color/#!/?view.left=0&view.right=1&primary.color=4666ae&secondary.color=00796B
*/
color: Color,
typography: Typography,
spacing: Spacing,
};
| 19.589474 | 113 | 0.559914 | 81 | 1 | 0 | 1 | 4 | 0 | 0 | 0 | 1 | 1 | 0 | 34 | 638 | 0.003135 | 0.00627 | 0 | 0.001567 | 0 | 0 | 0.166667 | 0.200275 | export type fontFamiliStyleType =
| 'light'
| 'normal'
| 'medium'
| 'bold'
| 'black'
| 'extra-black';
export /* Example usages of 'fontFamilyStyle' are shown below:
;
*/
const fontFamilyStyle = (
props = {},
) => {
if (props.italic !== undefined) {
if (props.italic) {
// italic fonts
switch (props.font || 'normal') {
case 'light':
return 'AvenirLTStd-LightOblique';
case 'medium':
return 'AvenirLTStd-MediumOblique';
case 'bold':
return 'AvenirLTStd-HeavyOblique';
case 'black':
return 'AvenirLTStd-BookOblique';
case 'extra-black':
return 'AvenirLTStd-BlackOblique';
case 'normal':
default:
return 'AvenirLTStd-Oblique';
}
}
}
switch (props.font || 'normal') {
case 'light':
return 'AvenirLTStd-Light';
case 'medium':
return 'AvenirLTStd-Medium';
case 'bold':
return 'AvenirLTStd-Heavy';
case 'black':
return 'AvenirLTStd-Book';
case 'extra-black':
return 'AvenirLTStd-Black';
case 'normal':
default:
return 'AvenirLTStd-Roman';
}
};
export const Color = {
primary: {
base: '#4665AF',
light: '#7992e1',
dark: '#003b7f',
},
secondary: {
base: '#5558A6',
light: '#8685d8',
dark: '#222f77', // can change in the future
},
};
export const Spacing = {
xs: 4,
sm: 8,
md: 16,
lg: 24,
xl: 32,
'2xl': 48,
};
export const Typography = {
fontFamilyStyle,
sizes: {
xs: '12px',
sm: '14px',
md: '16px',
lg: '20px',
xl: '24px',
'2xl': '28px',
},
};
export default {
/**
* Created from:
* https://material.io/resources/color/#!/?view.left=0&view.right=1&primary.color=4666ae&secondary.color=00796B
*/
color: Color,
typography: Typography,
spacing: Spacing,
};
|
7ef519413b872aeb3b35cf70a60bb014f3448ac9 | 1,275 | ts | TypeScript | admin/vue2/element-admin-v3/node_modules/@antv/path-util/src/catmull-rom-2-bezier.ts | wuximing/dsshop | a5893106bb50869d0acd68e85ac93bf3fd608219 | [
"MIT"
] | 1 | 2022-01-26T02:20:58.000Z | 2022-01-26T02:20:58.000Z | admin/vue2/element-admin-v3/node_modules/@antv/path-util/src/catmull-rom-2-bezier.ts | lianjie5664/dsshop | 431c4921698d5a150e510528bc3fd4b62d51abfb | [
"MIT"
] | null | null | null | admin/vue2/element-admin-v3/node_modules/@antv/path-util/src/catmull-rom-2-bezier.ts | lianjie5664/dsshop | 431c4921698d5a150e510528bc3fd4b62d51abfb | [
"MIT"
] | null | null | null | // http://schepers.cc/getting-to-the-point
export default function catmullRom2Bezier(crp: number[], z?: boolean): any[][] {
const d = [];
// @ts-ignore
for (let i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) {
const p = [ {
x: +crp[i - 2],
y: +crp[i - 1],
}, {
x: +crp[i],
y: +crp[i + 1],
}, {
x: +crp[i + 2],
y: +crp[i + 3],
}, {
x: +crp[i + 4],
y: +crp[i + 5],
} ];
if (z) {
if (!i) {
p[0] = {
x: +crp[iLen - 2],
y: +crp[iLen - 1],
};
} else if (iLen - 4 === i) {
p[3] = {
x: +crp[0],
y: +crp[1],
};
} else if (iLen - 2 === i) {
p[2] = {
x: +crp[0],
y: +crp[1],
};
p[3] = {
x: +crp[2],
y: +crp[3],
};
}
} else {
if (iLen - 4 === i) {
p[3] = p[2];
} else if (!i) {
p[0] = {
x: +crp[i],
y: +crp[i + 1],
};
}
}
d.push([ 'C',
(-p[0].x + 6 * p[1].x + p[2].x) / 6,
(-p[0].y + 6 * p[1].y + p[2].y) / 6,
(p[1].x + 6 * p[2].x - p[3].x) / 6,
(p[1].y + 6 * p[2].y - p[3].y) / 6,
p[2].x,
p[2].y,
]);
}
return d;
}
| 20.564516 | 80 | 0.29098 | 58 | 1 | 0 | 2 | 4 | 0 | 0 | 1 | 2 | 0 | 0 | 56 | 561 | 0.005348 | 0.00713 | 0 | 0 | 0 | 0.142857 | 0.285714 | 0.203417 | // http://schepers.cc/getting-to-the-point
export default function catmullRom2Bezier(crp, z?) {
const d = [];
// @ts-ignore
for (let i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) {
const p = [ {
x: +crp[i - 2],
y: +crp[i - 1],
}, {
x: +crp[i],
y: +crp[i + 1],
}, {
x: +crp[i + 2],
y: +crp[i + 3],
}, {
x: +crp[i + 4],
y: +crp[i + 5],
} ];
if (z) {
if (!i) {
p[0] = {
x: +crp[iLen - 2],
y: +crp[iLen - 1],
};
} else if (iLen - 4 === i) {
p[3] = {
x: +crp[0],
y: +crp[1],
};
} else if (iLen - 2 === i) {
p[2] = {
x: +crp[0],
y: +crp[1],
};
p[3] = {
x: +crp[2],
y: +crp[3],
};
}
} else {
if (iLen - 4 === i) {
p[3] = p[2];
} else if (!i) {
p[0] = {
x: +crp[i],
y: +crp[i + 1],
};
}
}
d.push([ 'C',
(-p[0].x + 6 * p[1].x + p[2].x) / 6,
(-p[0].y + 6 * p[1].y + p[2].y) / 6,
(p[1].x + 6 * p[2].x - p[3].x) / 6,
(p[1].y + 6 * p[2].y - p[3].y) / 6,
p[2].x,
p[2].y,
]);
}
return d;
}
|
6f7b7343b412f4bec5449a2de3e581e162e4a380 | 1,797 | ts | TypeScript | src/reqdata.ts | majo418/codecprox | d94d82ab235726e4e6ff1203e18d2051459d0aa2 | [
"MIT"
] | 4 | 2022-02-21T18:19:18.000Z | 2022-02-27T23:18:20.000Z | src/reqdata.ts | majo418/codecprox | d94d82ab235726e4e6ff1203e18d2051459d0aa2 | [
"MIT"
] | null | null | null | src/reqdata.ts | majo418/codecprox | d94d82ab235726e4e6ff1203e18d2051459d0aa2 | [
"MIT"
] | null | null | null |
export interface RequestData {
host: string,
path: string,
hostParts: string[],
pathParts: string[],
}
export const domainRegex = /^(?!-)[A-Za-z0-9-]+([\-\.]{1}[a-z0-9]+)*\.[A-Za-z]{2,6}$/g
export const domainWildcardRegex = /^(?!-)[A-Za-z0-9*-]+([\-\.]{1}[a-z0-9*]+)*\.[A-Za-z*]{2,6}$/g
export const ipv4Regex = /^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$/g
export const ipv6Regex = /^((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4}))*::((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4}))*|((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4})){7}$/g
export function parseRequestUrl(
host: string,
path: string,
): RequestData {
let hostParts: string[]
if (host.startsWith("[")) {
let portSeperatorIndex = host.lastIndexOf("]:")
if (portSeperatorIndex > 0) {
host = host.substring(1, portSeperatorIndex)
} else if (host.endsWith("]")) {
host = host.slice(1, -1)
}
if (!ipv6Regex.test(host)) {
hostParts = [host]
}
hostParts = host.split(".").reverse()
} else {
let portSeperatorIndex = host.lastIndexOf(":")
if (portSeperatorIndex > 0) {
host = host.substring(0, portSeperatorIndex)
}
if (ipv4Regex.test(host)) {
hostParts = [host]
} else {
hostParts = host.split(".").reverse()
}
}
let pathParts: string[] = path.split("/")
if (pathParts[0] == "") {
pathParts.shift()
}
if (hostParts[0] == "") {
hostParts.shift()
}
return {
host: host,
path: path,
hostParts: hostParts,
pathParts: pathParts,
}
}
| 32.089286 | 191 | 0.4936 | 51 | 1 | 0 | 2 | 8 | 4 | 0 | 0 | 8 | 1 | 0 | 36 | 666 | 0.004505 | 0.012012 | 0.006006 | 0.001502 | 0 | 0 | 0.533333 | 0.221681 |
export interface RequestData {
host,
path,
hostParts,
pathParts,
}
export const domainRegex = /^(?!-)[A-Za-z0-9-]+([\-\.]{1}[a-z0-9]+)*\.[A-Za-z]{2,6}$/g
export const domainWildcardRegex = /^(?!-)[A-Za-z0-9*-]+([\-\.]{1}[a-z0-9*]+)*\.[A-Za-z*]{2,6}$/g
export const ipv4Regex = /^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$/g
export const ipv6Regex = /^((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4}))*::((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4}))*|((?:[0-9A-Fa-f]{1,4}))((?::[0-9A-Fa-f]{1,4})){7}$/g
export function parseRequestUrl(
host,
path,
) {
let hostParts
if (host.startsWith("[")) {
let portSeperatorIndex = host.lastIndexOf("]:")
if (portSeperatorIndex > 0) {
host = host.substring(1, portSeperatorIndex)
} else if (host.endsWith("]")) {
host = host.slice(1, -1)
}
if (!ipv6Regex.test(host)) {
hostParts = [host]
}
hostParts = host.split(".").reverse()
} else {
let portSeperatorIndex = host.lastIndexOf(":")
if (portSeperatorIndex > 0) {
host = host.substring(0, portSeperatorIndex)
}
if (ipv4Regex.test(host)) {
hostParts = [host]
} else {
hostParts = host.split(".").reverse()
}
}
let pathParts = path.split("/")
if (pathParts[0] == "") {
pathParts.shift()
}
if (hostParts[0] == "") {
hostParts.shift()
}
return {
host: host,
path: path,
hostParts: hostParts,
pathParts: pathParts,
}
}
|
6fe76b5aaf422ac45ea3f391258b2aeb7c5ddf67 | 2,727 | ts | TypeScript | src/Hooks/Chat/RoomData.ts | callmenikk/JetChat | 6f5ba02f6d112ed11e48f08c1a30a1a40a42cf6d | [
"CC0-1.0"
] | 7 | 2022-02-22T06:58:56.000Z | 2022-03-14T11:40:10.000Z | src/Hooks/Chat/RoomData.ts | callmenikk/JetChat | 6f5ba02f6d112ed11e48f08c1a30a1a40a42cf6d | [
"CC0-1.0"
] | null | null | null | src/Hooks/Chat/RoomData.ts | callmenikk/JetChat | 6f5ba02f6d112ed11e48f08c1a30a1a40a42cf6d | [
"CC0-1.0"
] | null | null | null | export type State = {
room_id: string,
room_name: string,
room_icon: string,
owner_data: {
client_id: string,
client_name: string,
client_profile: string
}
active_clients: {
client_id: string,
client_name: string,
client_profile: string
}[]
}
const roomDefault: State = {
room_id: '',
room_name: '',
room_icon: '',
owner_data: {
client_id: '',
client_name: '',
client_profile: ''
},
active_clients: [],
}
type ActionType = "LOAD_ROOM_DATA" | "ROOM_BAN_ADD" | "ROOM_BAN_REMOVE" | "ROOM_MEMBER_UPDATE" | "ROOM_MEMBER_REMOVE" | "NEW_OWNER"| "CHANGE_ROOM" | "SET_ONLINE_MEMBERS"
type ActionPayload = {
ip?: string,
client_id?: string,
client_name?: string,
client_profile?: string
room_name?: string,
room_icon?: string,
room_id?: string
active_clients: {
client_id: string,
client_name: string,
client_profile: string
}[],
owner_data: {
client_id: string,
client_name: string,
client_profile: string
}
}
type Action = {
type: ActionType,
payload: ActionPayload
}
export const roomInfo = (state: State = roomDefault, action: Action): State => {
switch(action.type){
//LOAD ROOM DATA
case "LOAD_ROOM_DATA": {
const {room_icon, room_id, room_name, owner_data, active_clients} = action.payload
return {
room_id: room_id!,
room_name: room_name!,
room_icon: room_icon!,
owner_data: owner_data,
active_clients: active_clients,
}
}
//WHEN OWNER GIVES NEW MEMBER OWNERHOST
case "NEW_OWNER" : {
const {client_id, client_name, client_profile} = action.payload
return {
...state,
owner_data: {
client_id: client_id!,
client_name: client_name!,
client_profile: client_profile!
},
}
}
//MEMBER LEAVES ROOM
case "ROOM_MEMBER_REMOVE": {
const {client_id} = action.payload
const memberLeft = state.active_clients.filter(e => e.client_id !== client_id)
return {
...state,
active_clients: memberLeft
}
}
case "SET_ONLINE_MEMBERS": {
const {active_clients} = action.payload
return {
...state,
active_clients: active_clients
}
}
//MEMBER JOINS ROOM
case "ROOM_MEMBER_UPDATE": {
const {client_id, client_name, client_profile} = action.payload
const duplicateUser = state.active_clients.some(e => e.client_id === client_id)
if(duplicateUser) return state
return {
...state,
active_clients: [
...state.active_clients,
{
client_id: client_id!,
client_name: client_name!,
client_profile: client_profile!
}
]
}
}
case "CHANGE_ROOM": {
return {
...state,
room_name: action.payload.room_name!,
room_icon: action.payload.room_icon!
}
}
default: return state
}
} | 20.816794 | 169 | 0.666667 | 114 | 3 | 0 | 4 | 9 | 16 | 0 | 0 | 22 | 4 | 0 | 21.333333 | 950 | 0.007368 | 0.009474 | 0.016842 | 0.004211 | 0 | 0 | 0.6875 | 0.224195 | export type State = {
room_id,
room_name,
room_icon,
owner_data
active_clients
}
const roomDefault = {
room_id: '',
room_name: '',
room_icon: '',
owner_data: {
client_id: '',
client_name: '',
client_profile: ''
},
active_clients: [],
}
type ActionType = "LOAD_ROOM_DATA" | "ROOM_BAN_ADD" | "ROOM_BAN_REMOVE" | "ROOM_MEMBER_UPDATE" | "ROOM_MEMBER_REMOVE" | "NEW_OWNER"| "CHANGE_ROOM" | "SET_ONLINE_MEMBERS"
type ActionPayload = {
ip?,
client_id?,
client_name?,
client_profile?
room_name?,
room_icon?,
room_id?
active_clients,
owner_data
}
type Action = {
type,
payload
}
export const roomInfo = (state = roomDefault, action) => {
switch(action.type){
//LOAD ROOM DATA
case "LOAD_ROOM_DATA": {
const {room_icon, room_id, room_name, owner_data, active_clients} = action.payload
return {
room_id: room_id!,
room_name: room_name!,
room_icon: room_icon!,
owner_data: owner_data,
active_clients: active_clients,
}
}
//WHEN OWNER GIVES NEW MEMBER OWNERHOST
case "NEW_OWNER" : {
const {client_id, client_name, client_profile} = action.payload
return {
...state,
owner_data: {
client_id: client_id!,
client_name: client_name!,
client_profile: client_profile!
},
}
}
//MEMBER LEAVES ROOM
case "ROOM_MEMBER_REMOVE": {
const {client_id} = action.payload
const memberLeft = state.active_clients.filter(e => e.client_id !== client_id)
return {
...state,
active_clients: memberLeft
}
}
case "SET_ONLINE_MEMBERS": {
const {active_clients} = action.payload
return {
...state,
active_clients: active_clients
}
}
//MEMBER JOINS ROOM
case "ROOM_MEMBER_UPDATE": {
const {client_id, client_name, client_profile} = action.payload
const duplicateUser = state.active_clients.some(e => e.client_id === client_id)
if(duplicateUser) return state
return {
...state,
active_clients: [
...state.active_clients,
{
client_id: client_id!,
client_name: client_name!,
client_profile: client_profile!
}
]
}
}
case "CHANGE_ROOM": {
return {
...state,
room_name: action.payload.room_name!,
room_icon: action.payload.room_icon!
}
}
default: return state
}
} |
e49131127da2f7c13d35d2bf81883b6afaa38c2d | 3,418 | ts | TypeScript | lib/time/format-date.ts | edegiil/utils | c855c2bdb3b249912e8eafeba1ee3d86103c98e9 | [
"MIT"
] | null | null | null | lib/time/format-date.ts | edegiil/utils | c855c2bdb3b249912e8eafeba1ee3d86103c98e9 | [
"MIT"
] | 1 | 2022-03-13T14:09:54.000Z | 2022-03-13T14:09:54.000Z | lib/time/format-date.ts | edegiil/utils | c855c2bdb3b249912e8eafeba1ee3d86103c98e9 | [
"MIT"
] | null | null | null | /**
* format Date into string
* @param {Date} time time to format
* @param {string} format format (ex. YYYY-MM-DD A hh:mm:ss)
* @return {string} time string
*/
function formatDate(time: Date, format: string): string {
let year = time.getFullYear().toString();
let month = (time.getMonth() + 1).toString();
let date = time.getDate().toString();
let hour = time.getHours().toString();
let min = time.getMinutes().toString();
let sec = time.getSeconds().toString();
let a = '';
const year_regex = /Y{2,4}/g;
const month_regex = /M{1,2}/g;
const date_regex = /D{1,2}/g;
const hour_regex = /h{1,2}/g;
const min_regex = /m{1,2}/g;
const sec_regex = /s{1,2}/g;
const a_regex = /A{1}/g;
const matched_year = format.match(year_regex);
const matched_month = format.match(month_regex);
const matched_date = format.match(date_regex);
const matched_hour = format.match(hour_regex);
const matched_min = format.match(min_regex);
const matched_sec = format.match(sec_regex);
const matched_a = format.match(a_regex);
const is_valid_year = matched_year?.length === 1 && (matched_year[0]?.length === 2 || matched_year[0]?.length === 4);
const is_valid_month =
matched_month?.length === 1 && (matched_month[0]?.length === 1 || matched_month[0]?.length === 2);
const is_valid_date = matched_date?.length === 1 && (matched_date[0]?.length === 1 || matched_date[0]?.length === 2);
const is_valid_hour = matched_hour?.length === 1 && (matched_hour[0]?.length === 1 || matched_hour[0]?.length === 2);
const is_valid_min = matched_min?.length === 1 && (matched_min[0]?.length === 1 || matched_min[0]?.length === 2);
const is_valid_sec = matched_sec?.length === 1 && (matched_sec[0]?.length === 1 || matched_sec[0]?.length === 2);
const is_valid_a = matched_a?.length === 1 && matched_a[0] === 'A';
if (is_valid_year) {
const year_format_length = matched_year[0].length;
if (year_format_length === 2) {
year = year.slice(2, 4);
}
}
if (is_valid_month) {
const month_format_length = matched_month[0].length;
if (month_format_length === 2 && +month < 10) {
month = `0${month}`;
}
}
if (is_valid_date) {
const date_format_length = matched_date[0].length;
if (date_format_length === 2 && +date < 10) {
date = `0${date}`;
}
}
if (is_valid_hour) {
const hour_format_length = matched_hour[0].length;
if (is_valid_a) {
if (+hour < 12) a = '오전';
else {
a = '오후';
if (+hour > 12) hour = `${+hour - 12}`;
}
}
if (hour_format_length === 2 && +hour < 10) {
hour = `0${hour}`;
}
}
if (is_valid_min) {
const min_format_length = matched_min[0].length;
if (min_format_length === 2 && +min < 10) {
min = `0${min}`;
}
}
if (is_valid_sec) {
const sec_format_length = matched_sec[0].length;
if (sec_format_length === 2 && +sec < 10) {
sec = `0${sec}`;
}
}
let date_string = format;
date_string = date_string.replace(year_regex, year);
date_string = date_string.replace(month_regex, month);
date_string = date_string.replace(date_regex, date);
date_string = date_string.replace(hour_regex, hour);
date_string = date_string.replace(min_regex, min);
date_string = date_string.replace(sec_regex, sec);
date_string = date_string.replace(a_regex, a);
return date_string;
}
export default formatDate;
| 32.245283 | 119 | 0.632241 | 84 | 1 | 0 | 2 | 35 | 0 | 0 | 0 | 2 | 0 | 0 | 81 | 1,166 | 0.002573 | 0.030017 | 0 | 0 | 0 | 0 | 0.052632 | 0.274406 | /**
* format Date into string
* @param {Date} time time to format
* @param {string} format format (ex. YYYY-MM-DD A hh:mm:ss)
* @return {string} time string
*/
/* Example usages of 'formatDate' are shown below:
;
*/
function formatDate(time, format) {
let year = time.getFullYear().toString();
let month = (time.getMonth() + 1).toString();
let date = time.getDate().toString();
let hour = time.getHours().toString();
let min = time.getMinutes().toString();
let sec = time.getSeconds().toString();
let a = '';
const year_regex = /Y{2,4}/g;
const month_regex = /M{1,2}/g;
const date_regex = /D{1,2}/g;
const hour_regex = /h{1,2}/g;
const min_regex = /m{1,2}/g;
const sec_regex = /s{1,2}/g;
const a_regex = /A{1}/g;
const matched_year = format.match(year_regex);
const matched_month = format.match(month_regex);
const matched_date = format.match(date_regex);
const matched_hour = format.match(hour_regex);
const matched_min = format.match(min_regex);
const matched_sec = format.match(sec_regex);
const matched_a = format.match(a_regex);
const is_valid_year = matched_year?.length === 1 && (matched_year[0]?.length === 2 || matched_year[0]?.length === 4);
const is_valid_month =
matched_month?.length === 1 && (matched_month[0]?.length === 1 || matched_month[0]?.length === 2);
const is_valid_date = matched_date?.length === 1 && (matched_date[0]?.length === 1 || matched_date[0]?.length === 2);
const is_valid_hour = matched_hour?.length === 1 && (matched_hour[0]?.length === 1 || matched_hour[0]?.length === 2);
const is_valid_min = matched_min?.length === 1 && (matched_min[0]?.length === 1 || matched_min[0]?.length === 2);
const is_valid_sec = matched_sec?.length === 1 && (matched_sec[0]?.length === 1 || matched_sec[0]?.length === 2);
const is_valid_a = matched_a?.length === 1 && matched_a[0] === 'A';
if (is_valid_year) {
const year_format_length = matched_year[0].length;
if (year_format_length === 2) {
year = year.slice(2, 4);
}
}
if (is_valid_month) {
const month_format_length = matched_month[0].length;
if (month_format_length === 2 && +month < 10) {
month = `0${month}`;
}
}
if (is_valid_date) {
const date_format_length = matched_date[0].length;
if (date_format_length === 2 && +date < 10) {
date = `0${date}`;
}
}
if (is_valid_hour) {
const hour_format_length = matched_hour[0].length;
if (is_valid_a) {
if (+hour < 12) a = '오전';
else {
a = '오후';
if (+hour > 12) hour = `${+hour - 12}`;
}
}
if (hour_format_length === 2 && +hour < 10) {
hour = `0${hour}`;
}
}
if (is_valid_min) {
const min_format_length = matched_min[0].length;
if (min_format_length === 2 && +min < 10) {
min = `0${min}`;
}
}
if (is_valid_sec) {
const sec_format_length = matched_sec[0].length;
if (sec_format_length === 2 && +sec < 10) {
sec = `0${sec}`;
}
}
let date_string = format;
date_string = date_string.replace(year_regex, year);
date_string = date_string.replace(month_regex, month);
date_string = date_string.replace(date_regex, date);
date_string = date_string.replace(hour_regex, hour);
date_string = date_string.replace(min_regex, min);
date_string = date_string.replace(sec_regex, sec);
date_string = date_string.replace(a_regex, a);
return date_string;
}
export default formatDate;
|
e4d03cef3dbc28ce63d18957fd4779a2f080af09 | 2,424 | ts | TypeScript | src/FileParser.ts | alegemaate/allegrots | b041e90198d56453afc34ec4c90b2d277d316ca1 | [
"MIT"
] | null | null | null | src/FileParser.ts | alegemaate/allegrots | b041e90198d56453afc34ec4c90b2d277d316ca1 | [
"MIT"
] | 2 | 2022-01-15T07:26:47.000Z | 2022-03-31T23:01:09.000Z | src/FileParser.ts | alegemaate/allegrots | b041e90198d56453afc34ec4c90b2d277d316ca1 | [
"MIT"
] | null | null | null | /**
* File Parser
*/
export class FileParser {
// Data for parsing
private readonly data: DataView;
// File pointer
private pointer: number;
/**
* Constructor
*
* @param dataView - Data to use for parsing
*/
public constructor(dataView: DataView) {
this.data = dataView;
this.pointer = 0;
}
/**
* Move Pointer
*
* @param bytes - How many bytes to move by
*/
public movePointer(bytes: number): number {
// Move the pointer negative and positive direction
this.pointer += bytes;
return this.pointer;
}
/**
* Read an integer from buffer
*
* @param bytes - Number of bytes to read
*/
public readInt(bytes: number): number {
// Get integer from next bytes group (big-endian)
const clamp_bytes = Math.min(bytes, this.data.byteLength - this.pointer);
// EOF
if (clamp_bytes < 1) {
return -1;
}
let value = 0;
if (clamp_bytes > 1) {
for (let i = 1; i <= clamp_bytes - 1; i += 1) {
value += this.data.getUint8(this.pointer) * 256 ** (clamp_bytes - i);
this.pointer += 1;
}
}
value += this.data.getUint8(this.pointer);
this.pointer += 1;
return value;
}
/**
* Read a string from buffer
*
* @param bytes - Number of bytes to read
*/
public readStr(bytes: number): string {
// Read as ASCII chars, the followoing bytes
let text = "";
for (let char = 1; char <= bytes; char += 1)
text += String.fromCharCode(this.readInt(1));
return text;
}
/**
* Read a variable length value
*
* @param bytes - Number of bytes to read
*/
public readIntVLV(): number {
// Read a variable length value
let value = 0;
if (this.pointer >= this.data.byteLength) {
// EOF
return -1;
} else if (this.data.getUint8(this.pointer) < 128) {
// ...value in a single byte
value = this.readInt(1);
} else {
// ...value in multiple bytes
const FirstBytes: number[] = [];
while (this.data.getUint8(this.pointer) >= 128) {
FirstBytes.push(this.readInt(1) - 128);
}
const lastByte = this.readInt(1);
for (let dt = 1; dt <= FirstBytes.length; dt += 1) {
const num = FirstBytes[FirstBytes.length - dt];
if (typeof num === "number") {
value += num * 128 ** dt;
}
}
value += lastByte;
}
return value;
}
}
| 23.533981 | 77 | 0.569719 | 56 | 5 | 0 | 4 | 10 | 2 | 1 | 0 | 9 | 1 | 1 | 8.4 | 688 | 0.013081 | 0.014535 | 0.002907 | 0.001453 | 0.001453 | 0 | 0.428571 | 0.249967 | /**
* File Parser
*/
export class FileParser {
// Data for parsing
private readonly data;
// File pointer
private pointer;
/**
* Constructor
*
* @param dataView - Data to use for parsing
*/
public constructor(dataView) {
this.data = dataView;
this.pointer = 0;
}
/**
* Move Pointer
*
* @param bytes - How many bytes to move by
*/
public movePointer(bytes) {
// Move the pointer negative and positive direction
this.pointer += bytes;
return this.pointer;
}
/**
* Read an integer from buffer
*
* @param bytes - Number of bytes to read
*/
public readInt(bytes) {
// Get integer from next bytes group (big-endian)
const clamp_bytes = Math.min(bytes, this.data.byteLength - this.pointer);
// EOF
if (clamp_bytes < 1) {
return -1;
}
let value = 0;
if (clamp_bytes > 1) {
for (let i = 1; i <= clamp_bytes - 1; i += 1) {
value += this.data.getUint8(this.pointer) * 256 ** (clamp_bytes - i);
this.pointer += 1;
}
}
value += this.data.getUint8(this.pointer);
this.pointer += 1;
return value;
}
/**
* Read a string from buffer
*
* @param bytes - Number of bytes to read
*/
public readStr(bytes) {
// Read as ASCII chars, the followoing bytes
let text = "";
for (let char = 1; char <= bytes; char += 1)
text += String.fromCharCode(this.readInt(1));
return text;
}
/**
* Read a variable length value
*
* @param bytes - Number of bytes to read
*/
public readIntVLV() {
// Read a variable length value
let value = 0;
if (this.pointer >= this.data.byteLength) {
// EOF
return -1;
} else if (this.data.getUint8(this.pointer) < 128) {
// ...value in a single byte
value = this.readInt(1);
} else {
// ...value in multiple bytes
const FirstBytes = [];
while (this.data.getUint8(this.pointer) >= 128) {
FirstBytes.push(this.readInt(1) - 128);
}
const lastByte = this.readInt(1);
for (let dt = 1; dt <= FirstBytes.length; dt += 1) {
const num = FirstBytes[FirstBytes.length - dt];
if (typeof num === "number") {
value += num * 128 ** dt;
}
}
value += lastByte;
}
return value;
}
}
|
e4d360f3d4c1039bdb46a42d9a95cd24139f5154 | 2,962 | ts | TypeScript | src/namespaces/pathUtils.ts | gmetrixr/gdash | e2d3cacb7a34f83777a2aa333dc93397b153f6ae | [
"MIT"
] | null | null | null | src/namespaces/pathUtils.ts | gmetrixr/gdash | e2d3cacb7a34f83777a2aa333dc93397b153f6ae | [
"MIT"
] | null | null | null | src/namespaces/pathUtils.ts | gmetrixr/gdash | e2d3cacb7a34f83777a2aa333dc93397b153f6ae | [
"MIT"
] | 2 | 2022-02-28T10:42:13.000Z | 2022-03-25T05:25:54.000Z |
const imageFormats = ["png", "jpg", "jpeg", "webp"];
const videoFormats = ["mp4", "m4v"];
const audioFormats = ["aac", "mp3", "weba", "mpeg"];
const threeDFormats = ["glb", "gltf"];
const compressedFormats = ["zip", "rar", "tar", "gzip", "gz", "bz2", "7z"];
const gifFormats = ["gif"];
const pdfFormats = ["pdf"];
export const extensionWhitelist = [...imageFormats, ...videoFormats, ...audioFormats, ...threeDFormats, ...compressedFormats, ...gifFormats, ...pdfFormats];
export const disallowedFileExtensions = ["php", "php3", "php4", "phtml", "pl", "py", "jsp", "asp", "htm", "shtml", "sh", "cg"];
export const allowedMimeTypes = {
IMAGE: ["image/png", "image/jpg", "image/jpeg", "image/webp"],
VIDEO: ["video/mp4", "video/mpeg", "video/x-m4v"],
AUDIO: ["audio/aac", "audio/mp3", "audio/mpeg"],
COMPRESSED: ["application/zip", "application/vnd.rar", "application/x-tar", "application/gzip", "application/x-bzip2", "application/x-7z-compressed"],
THREED: ["model/gltf+binary", "model/gltf+json"],
GIF: ["image/gif"],
OTHER: ["application/pdf"],
PDF: ["application/pdf"],
SPRITE: ["application/zip", "application/vnd.rar", "application/x-tar", "application/gzip", "application/x-bzip2", "application/x-7z-compressed"],
SCORM: ["application/zip", "application/vnd.rar", "application/x-tar", "application/gzip", "application/x-bzip2", "application/x-7z-compressed"],
};
export enum FileType {
IMAGE = "IMAGE",
GIF = "GIF",
VIDEO = "VIDEO",
AUDIO = "AUDIO",
THREED = "THREED",
COMPRESSED = "COMPRESSED",
PDF = "PDF",
SCORM = "SCORM",
SPRITE = "SPRITE",
OTHER = "OTHER",
}
export const getFileType = (path: string): FileType => {
const extension = getExtension(path);
if (imageFormats.includes(extension)) {
return FileType.IMAGE;
} else if (videoFormats.includes(extension)) {
return FileType.VIDEO;
} else if (audioFormats.includes(extension)) {
return FileType.AUDIO;
} else if (threeDFormats.includes(extension)) {
return FileType.THREED;
} else if (compressedFormats.includes(extension)) {
return FileType.COMPRESSED;
} else if (gifFormats.includes(extension)) {
return FileType.GIF;
} else if (pdfFormats.includes(extension)) {
return FileType.PDF;
} else {
return FileType.OTHER;
}
}
export const getExtension = (path: string): string => {
// remove any query params that may be in the url
const q = path.split("?");
if (q.length >= 2) {
path = q[0];
}
const fullFileName: string = path.substring(path.lastIndexOf("/") + 1);
return fullFileName.substring(fullFileName.lastIndexOf(".") + 1).toLowerCase();
}
export function getFilenameWithoutExtension(path: string): string {
const fileName: string = path.substring(path.lastIndexOf("/") + 1);
return fileName.substring(0, fileName.lastIndexOf("."));
}
export function getFolderPathWithoutFilename(folderPath: string): string {
return folderPath.substring(0, folderPath.lastIndexOf("/"));
} | 38.973684 | 156 | 0.670493 | 68 | 4 | 0 | 4 | 16 | 0 | 1 | 0 | 9 | 0 | 0 | 6.75 | 881 | 0.009081 | 0.018161 | 0 | 0 | 0 | 0 | 0.375 | 0.250386 |
const imageFormats = ["png", "jpg", "jpeg", "webp"];
const videoFormats = ["mp4", "m4v"];
const audioFormats = ["aac", "mp3", "weba", "mpeg"];
const threeDFormats = ["glb", "gltf"];
const compressedFormats = ["zip", "rar", "tar", "gzip", "gz", "bz2", "7z"];
const gifFormats = ["gif"];
const pdfFormats = ["pdf"];
export const extensionWhitelist = [...imageFormats, ...videoFormats, ...audioFormats, ...threeDFormats, ...compressedFormats, ...gifFormats, ...pdfFormats];
export const disallowedFileExtensions = ["php", "php3", "php4", "phtml", "pl", "py", "jsp", "asp", "htm", "shtml", "sh", "cg"];
export const allowedMimeTypes = {
IMAGE: ["image/png", "image/jpg", "image/jpeg", "image/webp"],
VIDEO: ["video/mp4", "video/mpeg", "video/x-m4v"],
AUDIO: ["audio/aac", "audio/mp3", "audio/mpeg"],
COMPRESSED: ["application/zip", "application/vnd.rar", "application/x-tar", "application/gzip", "application/x-bzip2", "application/x-7z-compressed"],
THREED: ["model/gltf+binary", "model/gltf+json"],
GIF: ["image/gif"],
OTHER: ["application/pdf"],
PDF: ["application/pdf"],
SPRITE: ["application/zip", "application/vnd.rar", "application/x-tar", "application/gzip", "application/x-bzip2", "application/x-7z-compressed"],
SCORM: ["application/zip", "application/vnd.rar", "application/x-tar", "application/gzip", "application/x-bzip2", "application/x-7z-compressed"],
};
export enum FileType {
IMAGE = "IMAGE",
GIF = "GIF",
VIDEO = "VIDEO",
AUDIO = "AUDIO",
THREED = "THREED",
COMPRESSED = "COMPRESSED",
PDF = "PDF",
SCORM = "SCORM",
SPRITE = "SPRITE",
OTHER = "OTHER",
}
export const getFileType = (path) => {
const extension = getExtension(path);
if (imageFormats.includes(extension)) {
return FileType.IMAGE;
} else if (videoFormats.includes(extension)) {
return FileType.VIDEO;
} else if (audioFormats.includes(extension)) {
return FileType.AUDIO;
} else if (threeDFormats.includes(extension)) {
return FileType.THREED;
} else if (compressedFormats.includes(extension)) {
return FileType.COMPRESSED;
} else if (gifFormats.includes(extension)) {
return FileType.GIF;
} else if (pdfFormats.includes(extension)) {
return FileType.PDF;
} else {
return FileType.OTHER;
}
}
export /* Example usages of 'getExtension' are shown below:
getExtension(path);
*/
const getExtension = (path) => {
// remove any query params that may be in the url
const q = path.split("?");
if (q.length >= 2) {
path = q[0];
}
const fullFileName = path.substring(path.lastIndexOf("/") + 1);
return fullFileName.substring(fullFileName.lastIndexOf(".") + 1).toLowerCase();
}
export function getFilenameWithoutExtension(path) {
const fileName = path.substring(path.lastIndexOf("/") + 1);
return fileName.substring(0, fileName.lastIndexOf("."));
}
export function getFolderPathWithoutFilename(folderPath) {
return folderPath.substring(0, folderPath.lastIndexOf("/"));
} |
e4f02d917d41e269c23ef8617f6333001c7ae373 | 2,452 | ts | TypeScript | apps/kocoa/src/types/tree.ts | Julien-Pires/Latte | 69ca9a64d66f2924a3da4ecbf9e401c7ea29f5f9 | [
"MIT"
] | null | null | null | apps/kocoa/src/types/tree.ts | Julien-Pires/Latte | 69ca9a64d66f2924a3da4ecbf9e401c7ea29f5f9 | [
"MIT"
] | 12 | 2022-03-22T17:17:34.000Z | 2022-03-26T22:34:09.000Z | apps/kocoa/src/types/tree.ts | Julien-Pires/Latte | 69ca9a64d66f2924a3da4ecbf9e401c7ea29f5f9 | [
"MIT"
] | null | null | null | export interface Leaf<TLeaf> {
kind: 'leaf';
value: TLeaf;
}
export interface Node<TNode, TLeaf> {
kind: 'node';
childrens: (Node<TNode, TLeaf> | Leaf<TLeaf>)[];
name?: string;
value?: TNode;
}
export type Tree<TNode, TLeaf> = Node<TNode, TLeaf>;
export interface IntermediateNode<TNode> {
name: string;
value: TNode;
}
export const createTree = <TNode, TLeaf>(): Tree<TNode, TLeaf> => ({
kind: 'node',
childrens: []
});
export const findNode = <TNode, TLeaf>(
tree: Tree<TNode, TLeaf>,
path: readonly string[]
): Node<TNode, TLeaf> | undefined => {
const remainingPath = [...path];
remainingPath.reverse();
let node: string | undefined;
let previousNode = tree;
while ((node = remainingPath.pop())) {
const nextNode = previousNode.childrens
.filter((child): child is Node<TNode, TLeaf> => child.kind === 'node')
.find((child: Node<TNode, TLeaf>) => child.name === node);
if (!nextNode) {
return undefined;
}
previousNode = nextNode;
}
return previousNode;
};
export const insertNodes = <TNode, TLeaf>(
tree: Tree<TNode, TLeaf>,
nodes: readonly IntermediateNode<TNode>[]
): void => {
const remainingNodes = [...nodes];
remainingNodes.reverse();
let previousNode = tree;
while (remainingNodes.length > 0) {
const node = remainingNodes.pop();
if (!node) {
return undefined;
}
let nextNode = previousNode.childrens
.filter((child): child is Node<TNode, TLeaf> => child.kind === 'node')
.find((child: Node<TNode, TLeaf>) => child.name === node.name);
if (!nextNode) {
nextNode = {
kind: 'node',
name: node.name,
value: node.value,
childrens: []
};
previousNode.childrens.push(nextNode);
}
previousNode = nextNode;
}
};
export const insertLeaf = <TNode, TLeaf>(
tree: Tree<TNode, TLeaf>,
leaf: TLeaf,
nodes: readonly IntermediateNode<TNode>[]
): void => {
insertNodes(tree, nodes);
const lastParent = findNode(
tree,
nodes.map((node) => node.name)
);
if (!lastParent) {
throw new Error(`Failed to find parent node for leaf: ${leaf}`);
}
lastParent.childrens.push({
kind: 'leaf',
value: leaf
});
};
| 24.767677 | 82 | 0.56199 | 83 | 9 | 0 | 12 | 13 | 8 | 2 | 0 | 6 | 4 | 0 | 6.333333 | 673 | 0.031204 | 0.019316 | 0.011887 | 0.005944 | 0 | 0 | 0.142857 | 0.316096 | export interface Leaf<TLeaf> {
kind;
value;
}
export interface Node<TNode, TLeaf> {
kind;
childrens;
name?;
value?;
}
export type Tree<TNode, TLeaf> = Node<TNode, TLeaf>;
export interface IntermediateNode<TNode> {
name;
value;
}
export const createTree = <TNode, TLeaf>() => ({
kind: 'node',
childrens: []
});
export /* Example usages of 'findNode' are shown below:
findNode(tree, nodes.map((node) => node.name));
*/
const findNode = <TNode, TLeaf>(
tree,
path
) => {
const remainingPath = [...path];
remainingPath.reverse();
let node;
let previousNode = tree;
while ((node = remainingPath.pop())) {
const nextNode = previousNode.childrens
.filter((child): child is Node<TNode, TLeaf> => child.kind === 'node')
.find((child) => child.name === node);
if (!nextNode) {
return undefined;
}
previousNode = nextNode;
}
return previousNode;
};
export /* Example usages of 'insertNodes' are shown below:
insertNodes(tree, nodes);
*/
const insertNodes = <TNode, TLeaf>(
tree,
nodes
) => {
const remainingNodes = [...nodes];
remainingNodes.reverse();
let previousNode = tree;
while (remainingNodes.length > 0) {
const node = remainingNodes.pop();
if (!node) {
return undefined;
}
let nextNode = previousNode.childrens
.filter((child): child is Node<TNode, TLeaf> => child.kind === 'node')
.find((child) => child.name === node.name);
if (!nextNode) {
nextNode = {
kind: 'node',
name: node.name,
value: node.value,
childrens: []
};
previousNode.childrens.push(nextNode);
}
previousNode = nextNode;
}
};
export const insertLeaf = <TNode, TLeaf>(
tree,
leaf,
nodes
) => {
insertNodes(tree, nodes);
const lastParent = findNode(
tree,
nodes.map((node) => node.name)
);
if (!lastParent) {
throw new Error(`Failed to find parent node for leaf: ${leaf}`);
}
lastParent.childrens.push({
kind: 'leaf',
value: leaf
});
};
|
c44b47e8bba6fe1cbf7f0f6353c9bf40b7ebc1a4 | 1,074 | ts | TypeScript | src/client/src/complib/core/variables/variablesAnimation.ts | mimir-org/typelibrary | 493f332921098e014800f98baa0071907edc46d4 | [
"MIT"
] | 3 | 2022-01-26T12:55:10.000Z | 2022-03-08T15:07:49.000Z | src/client/src/complib/core/variables/variablesAnimation.ts | mimir-org/typelibrary | 493f332921098e014800f98baa0071907edc46d4 | [
"MIT"
] | 1 | 2022-03-07T12:59:37.000Z | 2022-03-07T12:59:37.000Z | src/client/src/complib/core/variables/variablesAnimation.ts | mimir-org/typelibrary | 493f332921098e014800f98baa0071907edc46d4 | [
"MIT"
] | null | null | null | export interface AnimationSystem {
fade: Record<string, unknown>,
scale: Record<string, unknown>,
selectHover: Record<string, unknown>,
from: (direction: "top" | "right" | "bottom" | "left", distance?: number) => Record<string, unknown>
}
export const animation: AnimationSystem = {
fade: {
initial: {
opacity: 0,
},
animate: {
opacity: 1,
},
exit: {
opacity: 0,
},
},
scale: {
initial: {
scale: 0.8,
},
animate: {
scale: 1,
},
exit: {
scale: 0.8,
},
},
from(direction: "top" | "right" | "bottom" | "left", distance = 10) {
const fromToMap = {
top: {
y: `-${distance}px`
},
right: {
x: `${distance}px`
},
bottom: {
y: `${distance}px`
},
left: {
x: `-${distance}px`
}
}
return {
initial: fromToMap[direction],
animate: {
x: 0,
y: 0,
},
exit: fromToMap[direction]
}
},
selectHover: {
whileHover: {
scale: 1.02
}
}
}
| 17.322581 | 102 | 0.470205 | 59 | 1 | 0 | 2 | 2 | 4 | 0 | 0 | 9 | 1 | 0 | 22 | 324 | 0.009259 | 0.006173 | 0.012346 | 0.003086 | 0 | 0 | 1 | 0.215622 | export interface AnimationSystem {
fade,
scale,
selectHover,
from
}
export const animation = {
fade: {
initial: {
opacity: 0,
},
animate: {
opacity: 1,
},
exit: {
opacity: 0,
},
},
scale: {
initial: {
scale: 0.8,
},
animate: {
scale: 1,
},
exit: {
scale: 0.8,
},
},
from(direction, distance = 10) {
const fromToMap = {
top: {
y: `-${distance}px`
},
right: {
x: `${distance}px`
},
bottom: {
y: `${distance}px`
},
left: {
x: `-${distance}px`
}
}
return {
initial: fromToMap[direction],
animate: {
x: 0,
y: 0,
},
exit: fromToMap[direction]
}
},
selectHover: {
whileHover: {
scale: 1.02
}
}
}
|
9903154e485c3be539adec65e2da193251d6c0be | 4,009 | ts | TypeScript | src/generator.ts | joelam789/ogm2d-js | 1c5b602134f553d9c9373d5a7a4fe8596028d900 | [
"Apache-2.0"
] | null | null | null | src/generator.ts | joelam789/ogm2d-js | 1c5b602134f553d9c9373d5a7a4fe8596028d900 | [
"Apache-2.0"
] | 1 | 2022-03-25T19:15:57.000Z | 2022-03-25T19:15:57.000Z | src/generator.ts | joelam789/ogm2d-js | 1c5b602134f553d9c9373d5a7a4fe8596028d900 | [
"Apache-2.0"
] | null | null | null |
export class RuntimeGenerator {
constructor() {
}
static genBasicGameJson() {
let json = {
script: false,
components:
{
display:
{
width: 640,
height: 480,
layers: ["bg", "map", "npc", "obj", "fog", "ui"]
},
event:
{
onInit: "onInit"
}
},
packs: [],
basics: ["display", "stage", "tween", "transition", "mouse", "keyboard", "gamepad", "event"],
scenes: ["scene1"]
}
return json;
}
static genBasicSceneJson() {
let json = {
script: false,
components:
{
display:
{
bgcolor: "#ffffff"
}
},
preload:
{
images: [],
musics: [],
sounds: [],
jsons: []
},
systems: ["motion"],
sprites: []
}
return json;
}
static genBasicPlotJson() {
let json = {
script: false,
components:
{
plot: true,
event:
{
onUpdate: "onUpdate"
}
}
}
return json;
}
static genBasicSpriteJson() {
let json = {
components:
{
graphic:
{
image: "bunny",
area:
{
x: 0,
y: 0,
width: 26,
height: 37
}
},
display:
{
layer: "npc",
x: 100,
y: 100,
anchor:
{
x: 0.5,
y: 0.5
}
}
}
}
return json;
}
static genBasicSpriteObjectJson(tpl: string = "") {
let json = {
active: true,
script: false,
template: tpl ? tpl : null,
components:
{
display:
{
x: 100,
y: 100,
angle: 0,
scale:
{
x: 1.0,
y: 1.0
},
anchor:
{
x: 0.5,
y: 0.5
}
}
}
}
return json;
}
static genBasicPanelObjectJson(tpl: string = "panel") {
let json = {
active: true,
script: false,
template: tpl ? tpl : null,
components:
{
display:
{
x: 10,
y: 10,
width: 120,
height: 60
}
}
}
return json;
}
static genBasicPlotObjectJson(tpl: string = "plot") {
let json = {
active: true,
script: true,
template: tpl ? tpl : null
}
return json;
}
static genBasicPlotObjectScript(tpl: string = "plot") {
let tscript = `
export class Plot1 {
* onUpdate(sprite) {
console.log("plot started - " + sprite.name);
console.log("plot ended - " + sprite.name);
sprite.active = false;
}
}
`;
return tscript;
}
static genEmptyClassScript(className: string = "Game1") {
let tscript = `
export class ` + className + ` {
}
`;
return tscript;
}
}
| 22.027473 | 105 | 0.305812 | 164 | 10 | 0 | 5 | 9 | 0 | 0 | 0 | 5 | 1 | 0 | 14.2 | 797 | 0.018821 | 0.011292 | 0 | 0.001255 | 0 | 0 | 0.208333 | 0.252758 |
export class RuntimeGenerator {
constructor() {
}
static genBasicGameJson() {
let json = {
script: false,
components:
{
display:
{
width: 640,
height: 480,
layers: ["bg", "map", "npc", "obj", "fog", "ui"]
},
event:
{
onInit: "onInit"
}
},
packs: [],
basics: ["display", "stage", "tween", "transition", "mouse", "keyboard", "gamepad", "event"],
scenes: ["scene1"]
}
return json;
}
static genBasicSceneJson() {
let json = {
script: false,
components:
{
display:
{
bgcolor: "#ffffff"
}
},
preload:
{
images: [],
musics: [],
sounds: [],
jsons: []
},
systems: ["motion"],
sprites: []
}
return json;
}
static genBasicPlotJson() {
let json = {
script: false,
components:
{
plot: true,
event:
{
onUpdate: "onUpdate"
}
}
}
return json;
}
static genBasicSpriteJson() {
let json = {
components:
{
graphic:
{
image: "bunny",
area:
{
x: 0,
y: 0,
width: 26,
height: 37
}
},
display:
{
layer: "npc",
x: 100,
y: 100,
anchor:
{
x: 0.5,
y: 0.5
}
}
}
}
return json;
}
static genBasicSpriteObjectJson(tpl = "") {
let json = {
active: true,
script: false,
template: tpl ? tpl : null,
components:
{
display:
{
x: 100,
y: 100,
angle: 0,
scale:
{
x: 1.0,
y: 1.0
},
anchor:
{
x: 0.5,
y: 0.5
}
}
}
}
return json;
}
static genBasicPanelObjectJson(tpl = "panel") {
let json = {
active: true,
script: false,
template: tpl ? tpl : null,
components:
{
display:
{
x: 10,
y: 10,
width: 120,
height: 60
}
}
}
return json;
}
static genBasicPlotObjectJson(tpl = "plot") {
let json = {
active: true,
script: true,
template: tpl ? tpl : null
}
return json;
}
static genBasicPlotObjectScript(tpl = "plot") {
let tscript = `
export class Plot1 {
* onUpdate(sprite) {
console.log("plot started - " + sprite.name);
console.log("plot ended - " + sprite.name);
sprite.active = false;
}
}
`;
return tscript;
}
static genEmptyClassScript(className = "Game1") {
let tscript = `
export class ` + className + ` {
}
`;
return tscript;
}
}
|
99499bc65b7cef3215108181962e99800a800b63 | 2,244 | ts | TypeScript | src/index.ts | jacobbubu/rngmt | 1a3766577482776801748c943fc9794e27e4c066 | [
"MIT"
] | null | null | null | src/index.ts | jacobbubu/rngmt | 1a3766577482776801748c943fc9794e27e4c066 | [
"MIT"
] | 2 | 2022-01-15T06:42:13.000Z | 2022-02-13T17:23:52.000Z | src/index.ts | jacobbubu/rngmt | 1a3766577482776801748c943fc9794e27e4c066 | [
"MIT"
] | null | null | null | /**
*/
function exists(x: any) {
return x !== null && x !== undefined
}
export class RNG {
private _index = 0
private _state: number[] = new Array(624)
constructor(private readonly _seed = (Math.random() * 0xffffffff) | 0) {
this._state[0] = _seed
const MT = this._state
for (let i = 1; i < 624; i++) {
MT[i] = MT[i - 1] ^ (MT[i - 1] >>> 30)
MT[i] = 0x6c078965 * MT[i] + i // 1812433253
MT[i] = MT[i] & ((MT[i] << 32) - 1)
}
}
/**
* Generate an array of 624 untempered numbers
* @returns: void
*/
private generateNumbers() {
let y
const MT = this._state
for (let i = 0; i < 624; i++) {
// Bit 31 (32nd bit) of MT[i]
y = MT[i] & 0x80000000
// Bits 0-30 (first 31 bits) of MT[...]
y = y + (MT[(i + 1) % 624] & 0x7fffffff)
// The new randomness
MT[i] = MT[(i + 397) % 624] ^ (y >>> 1)
// In case y is odd
if (y % 2 !== 0) {
MT[i] = MT[i] ^ 0x9908b0df // 2567483615
}
}
}
/**
* Returns a tempered pseudorandom number [0,1]
*
* @remarks
* Based on the index-th value, calling {@link #generateNumbers()} every 624 numbers
*
* @returns The pseudorandom integer between 0 and 1
*/
uniform() {
if (this._index === 0) this.generateNumbers()
let y = this._state[this._index]
y = y ^ (y >>> 11)
y = y ^ ((y << 7) & 0x9d2c5680) // 2636928640
y = y ^ ((y << 15) & 0xefc60000) // 4022730752
y = y ^ (y >>> 18)
this._index = (this._index + 1) % 624
return (y >>> 0) * (1.0 / 4294967296.0)
}
/**
* Returns a tempered pseudorandom number [0,1]
*
* @remarks
* Same as {@link #uniform()}, just to be
* compatible with the Math.random() style API
*
* @returns The pseudorandom integer between 0 and 1
*/
random() {
return this.uniform()
}
/**
* Returns a random integer in range [min,max]
* @param: min
* @param: max
* @returns The random integer between `min` and `max`
*/
range(min: number | null, max?: number) {
if (!exists(min)) {
return this.uniform()
} else if (!exists(max)) {
max = min!
min = 0
}
return min! + Math.floor(this.uniform() * (max! - min!))
}
}
| 23.375 | 86 | 0.526292 | 50 | 6 | 0 | 4 | 6 | 2 | 4 | 1 | 3 | 1 | 0 | 5.666667 | 875 | 0.011429 | 0.006857 | 0.002286 | 0.001143 | 0 | 0.055556 | 0.166667 | 0.220931 | /**
*/
/* Example usages of 'exists' are shown below:
!exists(min);
!exists(max);
*/
function exists(x) {
return x !== null && x !== undefined
}
export class RNG {
private _index = 0
private _state = new Array(624)
constructor(private readonly _seed = (Math.random() * 0xffffffff) | 0) {
this._state[0] = _seed
const MT = this._state
for (let i = 1; i < 624; i++) {
MT[i] = MT[i - 1] ^ (MT[i - 1] >>> 30)
MT[i] = 0x6c078965 * MT[i] + i // 1812433253
MT[i] = MT[i] & ((MT[i] << 32) - 1)
}
}
/**
* Generate an array of 624 untempered numbers
* @returns: void
*/
private generateNumbers() {
let y
const MT = this._state
for (let i = 0; i < 624; i++) {
// Bit 31 (32nd bit) of MT[i]
y = MT[i] & 0x80000000
// Bits 0-30 (first 31 bits) of MT[...]
y = y + (MT[(i + 1) % 624] & 0x7fffffff)
// The new randomness
MT[i] = MT[(i + 397) % 624] ^ (y >>> 1)
// In case y is odd
if (y % 2 !== 0) {
MT[i] = MT[i] ^ 0x9908b0df // 2567483615
}
}
}
/**
* Returns a tempered pseudorandom number [0,1]
*
* @remarks
* Based on the index-th value, calling {@link #generateNumbers()} every 624 numbers
*
* @returns The pseudorandom integer between 0 and 1
*/
uniform() {
if (this._index === 0) this.generateNumbers()
let y = this._state[this._index]
y = y ^ (y >>> 11)
y = y ^ ((y << 7) & 0x9d2c5680) // 2636928640
y = y ^ ((y << 15) & 0xefc60000) // 4022730752
y = y ^ (y >>> 18)
this._index = (this._index + 1) % 624
return (y >>> 0) * (1.0 / 4294967296.0)
}
/**
* Returns a tempered pseudorandom number [0,1]
*
* @remarks
* Same as {@link #uniform()}, just to be
* compatible with the Math.random() style API
*
* @returns The pseudorandom integer between 0 and 1
*/
random() {
return this.uniform()
}
/**
* Returns a random integer in range [min,max]
* @param: min
* @param: max
* @returns The random integer between `min` and `max`
*/
range(min, max?) {
if (!exists(min)) {
return this.uniform()
} else if (!exists(max)) {
max = min!
min = 0
}
return min! + Math.floor(this.uniform() * (max! - min!))
}
}
|
99d154e252b0bb2ef1c6de244cd4afd7a5ee21ec | 1,269 | ts | TypeScript | dlink-web/src/components/Studio/conf.ts | fforever14/dlink | 256be30d853c3d55e1a3814fd4c362eb419e0916 | [
"Apache-2.0"
] | 1 | 2022-02-14T08:37:13.000Z | 2022-02-14T08:37:13.000Z | dlink-web/src/components/Studio/conf.ts | fforever14/dlink | 256be30d853c3d55e1a3814fd4c362eb419e0916 | [
"Apache-2.0"
] | null | null | null | dlink-web/src/components/Studio/conf.ts | fforever14/dlink | 256be30d853c3d55e1a3814fd4c362eb419e0916 | [
"Apache-2.0"
] | null | null | null | export const RUN_MODE = {
LOCAL:'local',
STANDALONE:'standalone',
YARN_SESSION:'yarn-session',
YARN_PER_JOB:'yarn-per-job',
YARN_APPLICATION:'yarn-application',
KUBERNETES_SESSION:'kubernetes-session',
KUBERNETES_APPLICATION:'kubernetes-application',
};
export const DIALECT = {
FLINKSQL:'FlinkSql',
FLINKJAR:'FlinkJar',
FLINKSQLENV:'FlinkSqlEnv',
SQL:'Sql',
MYSQL:'Mysql',
ORACLE:'Oracle',
SQLSERVER:'SqlServer',
POSTGRESQL:'PostGreSql',
CLICKHOUSE:'ClickHouse',
DORIS:'Doris',
JAVA:'Java',
};
export const CHART = {
LINE:'折线图',
BAR:'条形图',
PIE:'饼图',
};
export const isSql = (dialect: string)=>{
switch (dialect){
case DIALECT.SQL:
case DIALECT.MYSQL:
case DIALECT.ORACLE:
case DIALECT.SQLSERVER:
case DIALECT.POSTGRESQL:
case DIALECT.CLICKHOUSE:
case DIALECT.DORIS:
return true;
default:
return false;
}
};
export const isOnline = (type: string)=>{
switch (type){
case RUN_MODE.LOCAL:
case RUN_MODE.STANDALONE:
case RUN_MODE.YARN_SESSION:
case RUN_MODE.KUBERNETES_SESSION:
return true;
default:
return false;
}
}
export const TASKSTEPS = {
UNKNOWN: 0,
CREATE: 1,
DEVELOP: 2,
DEBUG: 3,
RELEASE: 4,
ONLINE: 5,
CANCEL: 6,
};
| 18.661765 | 50 | 0.661151 | 61 | 2 | 0 | 2 | 6 | 0 | 0 | 0 | 2 | 0 | 0 | 10.5 | 434 | 0.009217 | 0.013825 | 0 | 0 | 0 | 0 | 0.2 | 0.23652 | export const RUN_MODE = {
LOCAL:'local',
STANDALONE:'standalone',
YARN_SESSION:'yarn-session',
YARN_PER_JOB:'yarn-per-job',
YARN_APPLICATION:'yarn-application',
KUBERNETES_SESSION:'kubernetes-session',
KUBERNETES_APPLICATION:'kubernetes-application',
};
export const DIALECT = {
FLINKSQL:'FlinkSql',
FLINKJAR:'FlinkJar',
FLINKSQLENV:'FlinkSqlEnv',
SQL:'Sql',
MYSQL:'Mysql',
ORACLE:'Oracle',
SQLSERVER:'SqlServer',
POSTGRESQL:'PostGreSql',
CLICKHOUSE:'ClickHouse',
DORIS:'Doris',
JAVA:'Java',
};
export const CHART = {
LINE:'折线图',
BAR:'条形图',
PIE:'饼图',
};
export const isSql = (dialect)=>{
switch (dialect){
case DIALECT.SQL:
case DIALECT.MYSQL:
case DIALECT.ORACLE:
case DIALECT.SQLSERVER:
case DIALECT.POSTGRESQL:
case DIALECT.CLICKHOUSE:
case DIALECT.DORIS:
return true;
default:
return false;
}
};
export const isOnline = (type)=>{
switch (type){
case RUN_MODE.LOCAL:
case RUN_MODE.STANDALONE:
case RUN_MODE.YARN_SESSION:
case RUN_MODE.KUBERNETES_SESSION:
return true;
default:
return false;
}
}
export const TASKSTEPS = {
UNKNOWN: 0,
CREATE: 1,
DEVELOP: 2,
DEBUG: 3,
RELEASE: 4,
ONLINE: 5,
CANCEL: 6,
};
|
99f9de6e41e1cea029674a5d388e456313b25cdf | 2,331 | ts | TypeScript | packages/iota/src/encoding/b1t6.ts | eike-hass/iota.js | 18ddf1ab7ffdd2ef59c6b345fe9ec70a4629bb48 | [
"Apache-2.0"
] | 1 | 2022-02-27T05:28:41.000Z | 2022-02-27T05:28:41.000Z | packages/iota/src/encoding/b1t6.ts | eike-hass/iota.js | 18ddf1ab7ffdd2ef59c6b345fe9ec70a4629bb48 | [
"Apache-2.0"
] | null | null | null | packages/iota/src/encoding/b1t6.ts | eike-hass/iota.js | 18ddf1ab7ffdd2ef59c6b345fe9ec70a4629bb48 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
/* eslint-disable no-bitwise */
/**
* Class implements the b1t6 encoding encoding which uses a group of 6 trits to encode each byte.
*/
export class B1T6 {
/**
* Trytes to trits lookup table.
* @internal
*/
private static readonly TRYTE_VALUE_TO_TRITS: number[][] = [
[-1, -1, -1],
[0, -1, -1],
[1, -1, -1],
[-1, 0, -1],
[0, 0, -1],
[1, 0, -1],
[-1, 1, -1],
[0, 1, -1],
[1, 1, -1],
[-1, -1, 0],
[0, -1, 0],
[1, -1, 0],
[-1, 0, 0],
[0, 0, 0],
[1, 0, 0],
[-1, 1, 0],
[0, 1, 0],
[1, 1, 0],
[-1, -1, 1],
[0, -1, 1],
[1, -1, 1],
[-1, 0, 1],
[0, 0, 1],
[1, 0, 1],
[-1, 1, 1],
[0, 1, 1],
[1, 1, 1]
];
/**
* Trites per tryte.
* @internal
*/
private static readonly TRITS_PER_TRYTE: number = 3;
/**
* The encoded length of the data.
* @param data The data.
* @returns The encoded length.
*/
public static encodedLen(data: Uint8Array): number {
return data.length * B1T6.TRITS_PER_TRYTE;
}
/**
* Encode a byte array into trits.
* @param dst The destination array.
* @param startIndex The start index to write in the array.
* @param src The source data.
* @returns The length of the encode.
*/
public static encode(dst: Int8Array, startIndex: number, src: Uint8Array): number {
let j = 0;
for (let i = 0; i < src.length; i++) {
// Convert to signed 8 bit value
const v = ((src[i] << 24) >> 24) + 364;
const rem = Math.trunc(v % 27);
const quo = Math.trunc(v / 27);
dst[startIndex + j] = B1T6.TRYTE_VALUE_TO_TRITS[rem][0];
dst[startIndex + j + 1] = B1T6.TRYTE_VALUE_TO_TRITS[rem][1];
dst[startIndex + j + 2] = B1T6.TRYTE_VALUE_TO_TRITS[rem][2];
dst[startIndex + j + 3] = B1T6.TRYTE_VALUE_TO_TRITS[quo][0];
dst[startIndex + j + 4] = B1T6.TRYTE_VALUE_TO_TRITS[quo][1];
dst[startIndex + j + 5] = B1T6.TRYTE_VALUE_TO_TRITS[quo][2];
j += 6;
}
return j;
}
}
| 27.423529 | 97 | 0.478335 | 51 | 2 | 0 | 4 | 5 | 2 | 0 | 0 | 5 | 1 | 0 | 7.5 | 840 | 0.007143 | 0.005952 | 0.002381 | 0.00119 | 0 | 0 | 0.384615 | 0.207608 | // Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
/* eslint-disable no-bitwise */
/**
* Class implements the b1t6 encoding encoding which uses a group of 6 trits to encode each byte.
*/
export class B1T6 {
/**
* Trytes to trits lookup table.
* @internal
*/
private static readonly TRYTE_VALUE_TO_TRITS = [
[-1, -1, -1],
[0, -1, -1],
[1, -1, -1],
[-1, 0, -1],
[0, 0, -1],
[1, 0, -1],
[-1, 1, -1],
[0, 1, -1],
[1, 1, -1],
[-1, -1, 0],
[0, -1, 0],
[1, -1, 0],
[-1, 0, 0],
[0, 0, 0],
[1, 0, 0],
[-1, 1, 0],
[0, 1, 0],
[1, 1, 0],
[-1, -1, 1],
[0, -1, 1],
[1, -1, 1],
[-1, 0, 1],
[0, 0, 1],
[1, 0, 1],
[-1, 1, 1],
[0, 1, 1],
[1, 1, 1]
];
/**
* Trites per tryte.
* @internal
*/
private static readonly TRITS_PER_TRYTE = 3;
/**
* The encoded length of the data.
* @param data The data.
* @returns The encoded length.
*/
public static encodedLen(data) {
return data.length * B1T6.TRITS_PER_TRYTE;
}
/**
* Encode a byte array into trits.
* @param dst The destination array.
* @param startIndex The start index to write in the array.
* @param src The source data.
* @returns The length of the encode.
*/
public static encode(dst, startIndex, src) {
let j = 0;
for (let i = 0; i < src.length; i++) {
// Convert to signed 8 bit value
const v = ((src[i] << 24) >> 24) + 364;
const rem = Math.trunc(v % 27);
const quo = Math.trunc(v / 27);
dst[startIndex + j] = B1T6.TRYTE_VALUE_TO_TRITS[rem][0];
dst[startIndex + j + 1] = B1T6.TRYTE_VALUE_TO_TRITS[rem][1];
dst[startIndex + j + 2] = B1T6.TRYTE_VALUE_TO_TRITS[rem][2];
dst[startIndex + j + 3] = B1T6.TRYTE_VALUE_TO_TRITS[quo][0];
dst[startIndex + j + 4] = B1T6.TRYTE_VALUE_TO_TRITS[quo][1];
dst[startIndex + j + 5] = B1T6.TRYTE_VALUE_TO_TRITS[quo][2];
j += 6;
}
return j;
}
}
|
7b0cf067eaba8170b5595b838be7eba6d5e3b2dc | 1,461 | ts | TypeScript | packages/store-github/src/github-data.ts | MeilCli/notion-db-notification | 285b7c564d28180c561cf2017eb286bf19e6b8fb | [
"MIT"
] | 1 | 2022-03-23T11:01:29.000Z | 2022-03-23T11:01:29.000Z | packages/store-github/src/github-data.ts | MeilCli/notion-db-notification | 285b7c564d28180c561cf2017eb286bf19e6b8fb | [
"MIT"
] | 9 | 2022-02-14T16:14:27.000Z | 2022-03-22T01:54:26.000Z | packages/store-github/src/github-data.ts | MeilCli/notion-db-notification | 285b7c564d28180c561cf2017eb286bf19e6b8fb | [
"MIT"
] | null | null | null | export interface GitHubData {
scheme: string;
timestamps: GitHubDataTimestamp[];
}
export interface GitHubDataTimestamp {
database: string;
lastWatchUnixTime: number;
lastWatchPageIds: string[];
}
export function equals(left: GitHubData | undefined, right: GitHubData | undefined): boolean {
if (left == undefined || right == undefined) {
return left == right;
}
if (left.scheme != right.scheme) {
return false;
}
if (left.timestamps.length != right.timestamps.length) {
return false;
}
for (const leftTimestamp of left.timestamps) {
if (contains(right.timestamps, leftTimestamp) == false) {
return false;
}
}
return true;
}
function contains(array: GitHubDataTimestamp[], value: GitHubDataTimestamp): boolean {
for (const a of array) {
if (a.database != value.database) {
continue;
}
if (a.lastWatchUnixTime != value.lastWatchUnixTime) {
continue;
}
if (arrayEquals(a.lastWatchPageIds, value.lastWatchPageIds) == false) {
continue;
}
return true;
}
return false;
}
function arrayEquals(left: string[], right: string[]): boolean {
if (left.length != right.length) {
return false;
}
for (const leftValue of left) {
if (right.includes(leftValue) == false) {
return false;
}
}
return true;
}
| 25.631579 | 94 | 0.59822 | 52 | 3 | 0 | 6 | 0 | 5 | 2 | 0 | 9 | 2 | 0 | 12.333333 | 357 | 0.02521 | 0 | 0.014006 | 0.005602 | 0 | 0 | 0.642857 | 0.237774 | export interface GitHubData {
scheme;
timestamps;
}
export interface GitHubDataTimestamp {
database;
lastWatchUnixTime;
lastWatchPageIds;
}
export function equals(left, right) {
if (left == undefined || right == undefined) {
return left == right;
}
if (left.scheme != right.scheme) {
return false;
}
if (left.timestamps.length != right.timestamps.length) {
return false;
}
for (const leftTimestamp of left.timestamps) {
if (contains(right.timestamps, leftTimestamp) == false) {
return false;
}
}
return true;
}
/* Example usages of 'contains' are shown below:
contains(right.timestamps, leftTimestamp) == false;
*/
function contains(array, value) {
for (const a of array) {
if (a.database != value.database) {
continue;
}
if (a.lastWatchUnixTime != value.lastWatchUnixTime) {
continue;
}
if (arrayEquals(a.lastWatchPageIds, value.lastWatchPageIds) == false) {
continue;
}
return true;
}
return false;
}
/* Example usages of 'arrayEquals' are shown below:
arrayEquals(a.lastWatchPageIds, value.lastWatchPageIds) == false;
*/
function arrayEquals(left, right) {
if (left.length != right.length) {
return false;
}
for (const leftValue of left) {
if (right.includes(leftValue) == false) {
return false;
}
}
return true;
}
|
7b6a001e2836a3661f9ceba920b7c88bd5a6252f | 2,225 | ts | TypeScript | generate-parentheses/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | 1 | 2022-03-30T11:10:14.000Z | 2022-03-30T11:10:14.000Z | generate-parentheses/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | null | null | null | generate-parentheses/index.ts | masx200/leetcode-test | bec83c7bc30fe3387a19bf8ae0c8685ed0aba2f4 | [
"MulanPSL-1.0"
] | null | null | null | export default function generateParenthesis(n: number): string[] {
if (n === 1) {
return ["()"];
}
if (n === 5) {
return [
"((((()))))",
"(((()())))",
"(((())()))",
"(((()))())",
"(((())))()",
"((()(())))",
"((()()()))",
"((()())())",
"((()()))()",
"((())(()))",
"((())()())",
"((())())()",
"((()))(())",
"((()))()()",
"(()((())))",
"(()(()()))",
"(()(())())",
"(()(()))()",
"(()()(()))",
"(()()()())",
"(()()())()",
"(()())(())",
"(()())()()",
"(())((()))",
"(())(()())",
"(())(())()",
"(())()(())",
"(())()()()",
"()(((())))",
"()((()()))",
"()((())())",
"()((()))()",
"()(()(()))",
"()(()()())",
"()(()())()",
"()(())(())",
"()(())()()",
"()()((()))",
"()()(()())",
"()()(())()",
"()()()(())",
"()()()()()",
];
}
if (n === 2) {
return ["(())", "()()"];
}
if (n === 3) {
return ["((()))", "(()())", "(())()", "()(())", "()()()"];
}
if (n === 4) {
return [
"(((())))",
"((()()))",
"((())())",
"((()))()",
"(()(()))",
"(()()())",
"(()())()",
"(())(())",
"(())()()",
"()((()))",
"()(()())",
"()(())()",
"()()(())",
"()()()()",
];
}
const cached = cache.get(n);
if (cached) {
return cached;
}
const set = new Set<string>();
for (const str of generateParenthesis(n - 1)) {
for (let i = 0; i <= str.length / 2; i++) {
set.add(str.slice(0, i) + "()" + str.slice(i, str.length));
}
}
const res = Array.from(set);
cache.set(n, res);
return res;
}
const cache = new Map<number, string[]>();
| 24.184783 | 71 | 0.14382 | 89 | 1 | 0 | 1 | 5 | 0 | 1 | 0 | 5 | 0 | 0 | 86 | 602 | 0.003322 | 0.008306 | 0 | 0 | 0 | 0 | 0.714286 | 0.204637 | export default /* Example usages of 'generateParenthesis' are shown below:
generateParenthesis(n - 1);
*/
function generateParenthesis(n) {
if (n === 1) {
return ["()"];
}
if (n === 5) {
return [
"((((()))))",
"(((()())))",
"(((())()))",
"(((()))())",
"(((())))()",
"((()(())))",
"((()()()))",
"((()())())",
"((()()))()",
"((())(()))",
"((())()())",
"((())())()",
"((()))(())",
"((()))()()",
"(()((())))",
"(()(()()))",
"(()(())())",
"(()(()))()",
"(()()(()))",
"(()()()())",
"(()()())()",
"(()())(())",
"(()())()()",
"(())((()))",
"(())(()())",
"(())(())()",
"(())()(())",
"(())()()()",
"()(((())))",
"()((()()))",
"()((())())",
"()((()))()",
"()(()(()))",
"()(()()())",
"()(()())()",
"()(())(())",
"()(())()()",
"()()((()))",
"()()(()())",
"()()(())()",
"()()()(())",
"()()()()()",
];
}
if (n === 2) {
return ["(())", "()()"];
}
if (n === 3) {
return ["((()))", "(()())", "(())()", "()(())", "()()()"];
}
if (n === 4) {
return [
"(((())))",
"((()()))",
"((())())",
"((()))()",
"(()(()))",
"(()()())",
"(()())()",
"(())(())",
"(())()()",
"()((()))",
"()(()())",
"()(())()",
"()()(())",
"()()()()",
];
}
const cached = cache.get(n);
if (cached) {
return cached;
}
const set = new Set<string>();
for (const str of generateParenthesis(n - 1)) {
for (let i = 0; i <= str.length / 2; i++) {
set.add(str.slice(0, i) + "()" + str.slice(i, str.length));
}
}
const res = Array.from(set);
cache.set(n, res);
return res;
}
const cache = new Map<number, string[]>();
|
7b7c1af774d2ff1a15db6a93ac3037cdbade5a75 | 3,222 | ts | TypeScript | src/base64/encoding.ts | ItalyPaleAle/arraybuffer | a2ef7d73a4706d84c5858734fc82307b7a4b2355 | [
"MIT"
] | 1 | 2022-01-03T03:21:50.000Z | 2022-01-03T03:21:50.000Z | src/base64/encoding.ts | ItalyPaleAle/arraybuffer | a2ef7d73a4706d84c5858734fc82307b7a4b2355 | [
"MIT"
] | 1 | 2022-01-03T03:32:57.000Z | 2022-01-03T09:17:01.000Z | src/base64/encoding.ts | ItalyPaleAle/arraybuffer | a2ef7d73a4706d84c5858734fc82307b7a4b2355 | [
"MIT"
] | null | null | null | /**
* Base64 encoding and decoding with a given charset and optional padding.
* This class can be used to create base64 encoders and decoders with custom charsets.
* @module base64/encoding
*/
export class Encoding {
private _charset: string
private _noPadding: boolean
private _valid: RegExp
/**
*
* @param charset Charset to use for base64 encoding. This must be 64-characters long.
* @param noPadding If true, encoded strings won't include padding.
*/
constructor(charset: string, noPadding?: boolean) {
if (!charset || charset.length != 64) {
throw Error('Charset must contain 64 characters')
}
this._charset = charset
this._noPadding = !!noPadding
this._valid = new RegExp('^[' + this._charset.replace('-', '\\-') + ']+={0,2}$')
}
/**
* Encode an ArrayBuffer to base64 in a string.
* @param ab Data to encode to base64
* @returns Base64-encoded string
*/
Encode(ab: ArrayBuffer): string {
const len = ab.byteLength
if (!len) {
return ''
}
const view = new Uint8Array(ab)
let res = ''
for (let i = 0; i < len; i += 3) {
res += this._charset[view[i] >> 2] +
this._charset[((view[i] & 3) << 4) | (view[i + 1] >> 4)] +
this._charset[((view[i + 1] & 15) << 2) | (view[i + 2] >> 6)] +
this._charset[view[i + 2] & 63]
}
if (len % 3 == 2) {
res = res.substring(0, res.length - 1)
if (!this._noPadding) {
res += '='
}
}
else if (len % 3 == 1) {
res = res.substring(0, res.length - 2)
if (!this._noPadding) {
res += '=='
}
}
return res
}
/**
* Decode a string from base64. Padding is always optional.
* @param str Base64-encoded string
* @returns Data decoded from the base64 string
*/
Decode(str: string): ArrayBuffer {
// Remove whitespaces
str = (str || '').replace(/[\s]/g, '')
// Decode to a buffer
if (!str) {
return new ArrayBuffer(0)
}
if (!this._valid.test(str)) {
throw Error('Invalid base64 input sequence')
}
let viewLen = Math.floor(str.length * 0.75)
if (str[str.length - 2] == '=') {
viewLen -= 2
}
else if (str[str.length - 1] == '=') {
viewLen--
}
const view = new Uint8Array(viewLen)
let enc1: number,
enc2: number,
enc3: number,
enc4: number,
i = 0,
j = 0
while (i < str.length * 0.75) {
enc1 = this._charset.indexOf(str.charAt(j++))
enc2 = this._charset.indexOf(str.charAt(j++))
enc3 = this._charset.indexOf(str.charAt(j++))
enc4 = this._charset.indexOf(str.charAt(j++))
view[i++] = (enc1 << 2) | (enc2 >> 4)
view[i++] = ((enc2 & 15) << 4) | (enc3 >> 2)
view[i++] = ((enc3 & 3) << 6) | enc4
}
return view.buffer
}
}
| 30.396226 | 90 | 0.487585 | 73 | 3 | 0 | 4 | 12 | 3 | 0 | 0 | 10 | 1 | 0 | 20.666667 | 897 | 0.007804 | 0.013378 | 0.003344 | 0.001115 | 0 | 0 | 0.454545 | 0.233273 | /**
* Base64 encoding and decoding with a given charset and optional padding.
* This class can be used to create base64 encoders and decoders with custom charsets.
* @module base64/encoding
*/
export class Encoding {
private _charset
private _noPadding
private _valid
/**
*
* @param charset Charset to use for base64 encoding. This must be 64-characters long.
* @param noPadding If true, encoded strings won't include padding.
*/
constructor(charset, noPadding?) {
if (!charset || charset.length != 64) {
throw Error('Charset must contain 64 characters')
}
this._charset = charset
this._noPadding = !!noPadding
this._valid = new RegExp('^[' + this._charset.replace('-', '\\-') + ']+={0,2}$')
}
/**
* Encode an ArrayBuffer to base64 in a string.
* @param ab Data to encode to base64
* @returns Base64-encoded string
*/
Encode(ab) {
const len = ab.byteLength
if (!len) {
return ''
}
const view = new Uint8Array(ab)
let res = ''
for (let i = 0; i < len; i += 3) {
res += this._charset[view[i] >> 2] +
this._charset[((view[i] & 3) << 4) | (view[i + 1] >> 4)] +
this._charset[((view[i + 1] & 15) << 2) | (view[i + 2] >> 6)] +
this._charset[view[i + 2] & 63]
}
if (len % 3 == 2) {
res = res.substring(0, res.length - 1)
if (!this._noPadding) {
res += '='
}
}
else if (len % 3 == 1) {
res = res.substring(0, res.length - 2)
if (!this._noPadding) {
res += '=='
}
}
return res
}
/**
* Decode a string from base64. Padding is always optional.
* @param str Base64-encoded string
* @returns Data decoded from the base64 string
*/
Decode(str) {
// Remove whitespaces
str = (str || '').replace(/[\s]/g, '')
// Decode to a buffer
if (!str) {
return new ArrayBuffer(0)
}
if (!this._valid.test(str)) {
throw Error('Invalid base64 input sequence')
}
let viewLen = Math.floor(str.length * 0.75)
if (str[str.length - 2] == '=') {
viewLen -= 2
}
else if (str[str.length - 1] == '=') {
viewLen--
}
const view = new Uint8Array(viewLen)
let enc1,
enc2,
enc3,
enc4,
i = 0,
j = 0
while (i < str.length * 0.75) {
enc1 = this._charset.indexOf(str.charAt(j++))
enc2 = this._charset.indexOf(str.charAt(j++))
enc3 = this._charset.indexOf(str.charAt(j++))
enc4 = this._charset.indexOf(str.charAt(j++))
view[i++] = (enc1 << 2) | (enc2 >> 4)
view[i++] = ((enc2 & 15) << 4) | (enc3 >> 2)
view[i++] = ((enc3 & 3) << 6) | enc4
}
return view.buffer
}
}
|
7bb3e1ece58d8db0c766aaa614e4e3db0fe075e0 | 3,749 | ts | TypeScript | algorithms/utils/number/string/vietnamese.ts | minhthinhls/Advanced-Competitive-Algorithms | df0a92299e4f94d601dec85afd616a59728039ad | [
"MIT"
] | 12 | 2022-02-24T19:24:39.000Z | 2022-02-28T14:39:16.000Z | app/utils/number/string/vietnamese.ts | minhthinhls/Egg-App-Boilerplate | 33e893ffefdbd9f2fe566825d4c45bb6ae43fa81 | [
"MIT"
] | null | null | null | app/utils/number/string/vietnamese.ts | minhthinhls/Egg-App-Boilerplate | 33e893ffefdbd9f2fe566825d4c45bb6ae43fa81 | [
"MIT"
] | null | null | null | export const NUMBER = ['không', 'một', 'hai', 'ba', 'bốn', 'năm', 'sáu', 'bảy', 'tám', 'chín'];
/**
** @see {@link https://timoday.edu.vn/chuyen-so-thanh-chuoi-bang-c/}
** @param {string | number} num
** @param {string} [unit]
** @returns {string}
**/
export const parse = (num: number, unit: string = ""): string => {
if (num < 0) {
throw new EvalError("Number cannot be less than zero =>");
}
if (num === 0) {
return ' ' + NUMBER[0];
}
/** Modulus factor of number by 1 billion for each loop !*/
let mod = 0;
let str = "";
let postfix = "";
while (num > 0) {
/** Lấy phần dư sau số hàng tỷ !*/
mod = num % 1_000_000_000;
/** Lấy số hàng tỷ !*/
num = Math.floor(num / 1_000_000_000);
if (num <= 0) {
break;
}
str = million(mod, true) + postfix + str;
/** Only insert postfix "Billion" when starting from the 2nd iteration !*/
postfix = " tỷ";
}
/** Most significant digits lays before billion postfix !*/
return million(mod, false).substring(1) + postfix + str + unit;
};
/**
** @see {@link https://timoday.edu.vn/chuyen-so-thanh-chuoi-bang-c/}
** @param {string | number} num
** @param {boolean} full
** @returns {string}
**/
const million = (num: number, full: boolean): string => {
let str = "";
/** Lấy số hàng triệu !*/
const million = Math.floor(num / 1_000_000);
/** Lấy phần dư sau số hàng triệu !*/
num = num % 1_000_000;
if (million > 0) {
str = hundred(million, full) + " triệu";
full = true;
}
/** Lấy số hàng nghìn !*/
const thousand = Math.floor(num / 1_000);
/** Lấy phần dư sau số hàng nghìn !*/
num = num % 1_000;
if (thousand > 0) {
str += hundred(thousand, full) + " nghìn";
full = true;
}
/** Số hàng trăm !*/
if (num > 0) {
str += hundred(num, full);
}
return str;
};
/**
** @see {@link https://timoday.edu.vn/chuyen-so-thanh-chuoi-bang-c/}
** @param {string | number} num
** @param {boolean} full
** @returns {string}
**/
const hundred = (num: number, full: boolean): string => {
/** Lấy số hàng trăm !*/
const hundred = Math.floor(num / 100);
/** Lấy phần dư sau số hàng trăm !*/
num = num % 100;
if (full || hundred > 0) {
return " " + NUMBER[hundred] + " trăm" + decimal(num, true);
}
return decimal(num, false);
};
/**
** @see {@link https://timoday.edu.vn/chuyen-so-thanh-chuoi-bang-c/}
** @param {string | number} num
** @param {boolean} full
** @returns {string}
**/
const decimal = (num: number, full: boolean): string => {
let str = "";
const decimal = Math.floor(num / 10);
const unit = num % 10;
/** Hai mươi [2x] -> Chín mươi [9x] !*/
if (decimal > 1) {
str = " " + NUMBER[decimal] + " mươi";
/** Hai mươi mốt [21], [31], [41], ... -> Chín mươi mốt [91] !*/
if (unit === 1) {
str += " mốt";
}
} else if (decimal === 1) {
/** Mười hai [12] -> Mười chín [19] !*/
str = " mười";
/** Mười một [11] !*/
if (unit === 1) {
str += " một";
}
} else if (full && unit > 0) {
/** Nếu hàng đơn vị khác 0 và có các số hàng trăm, ví dụ 101.
** Thì biến [full == true] => Vậy sẽ đọc một trăm lẻ một !*/
str = " lẻ";
}
if (unit === 5 && decimal >= 1) {
/** [Một, Hai, Ba, ..., Chín] trăm [mười, hai mươi, ba mươi, ..., chín mươi] lăm
** [115, 125, 135, ..., 195] && [115, 225, 335, ..., 995] !*/
str += " lăm";
} else if (unit > 1 || (unit === 1 && decimal === 0)) {
str += " " + NUMBER[unit];
}
return str;
};
| 30.233871 | 95 | 0.4996 | 73 | 4 | 0 | 8 | 15 | 0 | 3 | 0 | 12 | 0 | 0 | 16 | 1,527 | 0.007859 | 0.009823 | 0 | 0 | 0 | 0 | 0.444444 | 0.220743 | export const NUMBER = ['không', 'một', 'hai', 'ba', 'bốn', 'năm', 'sáu', 'bảy', 'tám', 'chín'];
/**
** @see {@link https://timoday.edu.vn/chuyen-so-thanh-chuoi-bang-c/}
** @param {string | number} num
** @param {string} [unit]
** @returns {string}
**/
export const parse = (num, unit = "") => {
if (num < 0) {
throw new EvalError("Number cannot be less than zero =>");
}
if (num === 0) {
return ' ' + NUMBER[0];
}
/** Modulus factor of number by 1 billion for each loop !*/
let mod = 0;
let str = "";
let postfix = "";
while (num > 0) {
/** Lấy phần dư sau số hàng tỷ !*/
mod = num % 1_000_000_000;
/** Lấy số hàng tỷ !*/
num = Math.floor(num / 1_000_000_000);
if (num <= 0) {
break;
}
str = million(mod, true) + postfix + str;
/** Only insert postfix "Billion" when starting from the 2nd iteration !*/
postfix = " tỷ";
}
/** Most significant digits lays before billion postfix !*/
return million(mod, false).substring(1) + postfix + str + unit;
};
/**
** @see {@link https://timoday.edu.vn/chuyen-so-thanh-chuoi-bang-c/}
** @param {string | number} num
** @param {boolean} full
** @returns {string}
**/
/* Example usages of 'million' are shown below:
str = million(mod, true) + postfix + str;
million(mod, false).substring(1) + postfix + str + unit;
var million = Math.floor(num / 1000000);
million > 0;
str = hundred(million, full) + " triệu";
*/
const million = (num, full) => {
let str = "";
/** Lấy số hàng triệu !*/
const million = Math.floor(num / 1_000_000);
/** Lấy phần dư sau số hàng triệu !*/
num = num % 1_000_000;
if (million > 0) {
str = hundred(million, full) + " triệu";
full = true;
}
/** Lấy số hàng nghìn !*/
const thousand = Math.floor(num / 1_000);
/** Lấy phần dư sau số hàng nghìn !*/
num = num % 1_000;
if (thousand > 0) {
str += hundred(thousand, full) + " nghìn";
full = true;
}
/** Số hàng trăm !*/
if (num > 0) {
str += hundred(num, full);
}
return str;
};
/**
** @see {@link https://timoday.edu.vn/chuyen-so-thanh-chuoi-bang-c/}
** @param {string | number} num
** @param {boolean} full
** @returns {string}
**/
/* Example usages of 'hundred' are shown below:
str = hundred(million, full) + " triệu";
str += hundred(thousand, full) + " nghìn";
str += hundred(num, full);
var hundred = Math.floor(num / 100);
full || hundred > 0;
" " + NUMBER[hundred] + " trăm" + decimal(num, true);
*/
const hundred = (num, full) => {
/** Lấy số hàng trăm !*/
const hundred = Math.floor(num / 100);
/** Lấy phần dư sau số hàng trăm !*/
num = num % 100;
if (full || hundred > 0) {
return " " + NUMBER[hundred] + " trăm" + decimal(num, true);
}
return decimal(num, false);
};
/**
** @see {@link https://timoday.edu.vn/chuyen-so-thanh-chuoi-bang-c/}
** @param {string | number} num
** @param {boolean} full
** @returns {string}
**/
/* Example usages of 'decimal' are shown below:
" " + NUMBER[hundred] + " trăm" + decimal(num, true);
decimal(num, false);
var decimal = Math.floor(num / 10);
decimal > 1;
str = " " + NUMBER[decimal] + " mươi";
decimal === 1;
unit === 5 && decimal >= 1;
unit === 1 && decimal === 0;
*/
const decimal = (num, full) => {
let str = "";
const decimal = Math.floor(num / 10);
const unit = num % 10;
/** Hai mươi [2x] -> Chín mươi [9x] !*/
if (decimal > 1) {
str = " " + NUMBER[decimal] + " mươi";
/** Hai mươi mốt [21], [31], [41], ... -> Chín mươi mốt [91] !*/
if (unit === 1) {
str += " mốt";
}
} else if (decimal === 1) {
/** Mười hai [12] -> Mười chín [19] !*/
str = " mười";
/** Mười một [11] !*/
if (unit === 1) {
str += " một";
}
} else if (full && unit > 0) {
/** Nếu hàng đơn vị khác 0 và có các số hàng trăm, ví dụ 101.
** Thì biến [full == true] => Vậy sẽ đọc một trăm lẻ một !*/
str = " lẻ";
}
if (unit === 5 && decimal >= 1) {
/** [Một, Hai, Ba, ..., Chín] trăm [mười, hai mươi, ba mươi, ..., chín mươi] lăm
** [115, 125, 135, ..., 195] && [115, 225, 335, ..., 995] !*/
str += " lăm";
} else if (unit > 1 || (unit === 1 && decimal === 0)) {
str += " " + NUMBER[unit];
}
return str;
};
|
7bbf1560d10fe751769466953676b463a5c10ea8 | 1,483 | ts | TypeScript | node_modules/@nomiclabs/hardhat-etherscan/src/etherscan/EtherscanVerifyContractRequest.ts | fkochan/opyn-vaults | a366bf03cc394f02c8daefcd604c3434a9d0e684 | [
"MIT"
] | 1 | 2022-03-29T17:43:15.000Z | 2022-03-29T17:43:15.000Z | node_modules/@nomiclabs/hardhat-etherscan/src/etherscan/EtherscanVerifyContractRequest.ts | fkochan/opyn-vaults | a366bf03cc394f02c8daefcd604c3434a9d0e684 | [
"MIT"
] | null | null | null | node_modules/@nomiclabs/hardhat-etherscan/src/etherscan/EtherscanVerifyContractRequest.ts | fkochan/opyn-vaults | a366bf03cc394f02c8daefcd604c3434a9d0e684 | [
"MIT"
] | null | null | null | export interface EtherscanRequest {
apikey: string;
module: "contract";
action: string;
}
export interface EtherscanVerifyRequest extends EtherscanRequest {
action: "verifysourcecode";
contractaddress: string;
sourceCode: string;
codeformat: "solidity-standard-json-input";
contractname: string;
compilerversion: string;
// This is misspelt in Etherscan's actual API parameters.
// See: https://etherscan.io/apis#contracts
constructorArguements: string;
}
export interface EtherscanCheckStatusRequest extends EtherscanRequest {
action: "checkverifystatus";
guid: string;
}
export function toVerifyRequest(params: {
apiKey: string;
contractAddress: string;
sourceCode: string;
sourceName: string;
contractName: string;
compilerVersion: string;
constructorArguments: string;
}): EtherscanVerifyRequest {
return {
apikey: params.apiKey,
module: "contract",
action: "verifysourcecode",
contractaddress: params.contractAddress,
sourceCode: params.sourceCode,
codeformat: "solidity-standard-json-input",
contractname: `${params.sourceName}:${params.contractName}`,
compilerversion: params.compilerVersion,
constructorArguements: params.constructorArguments,
};
}
export function toCheckStatusRequest(params: {
apiKey: string;
guid: string;
}): EtherscanCheckStatusRequest {
return {
apikey: params.apiKey,
module: "contract",
action: "checkverifystatus",
guid: params.guid,
};
}
| 26.017544 | 71 | 0.742414 | 50 | 2 | 0 | 2 | 0 | 12 | 0 | 0 | 17 | 3 | 0 | 8.5 | 382 | 0.010471 | 0 | 0.031414 | 0.007853 | 0 | 0 | 1.0625 | 0.205837 | export interface EtherscanRequest {
apikey;
module;
action;
}
export interface EtherscanVerifyRequest extends EtherscanRequest {
action;
contractaddress;
sourceCode;
codeformat;
contractname;
compilerversion;
// This is misspelt in Etherscan's actual API parameters.
// See: https://etherscan.io/apis#contracts
constructorArguements;
}
export interface EtherscanCheckStatusRequest extends EtherscanRequest {
action;
guid;
}
export function toVerifyRequest(params) {
return {
apikey: params.apiKey,
module: "contract",
action: "verifysourcecode",
contractaddress: params.contractAddress,
sourceCode: params.sourceCode,
codeformat: "solidity-standard-json-input",
contractname: `${params.sourceName}:${params.contractName}`,
compilerversion: params.compilerVersion,
constructorArguements: params.constructorArguments,
};
}
export function toCheckStatusRequest(params) {
return {
apikey: params.apiKey,
module: "contract",
action: "checkverifystatus",
guid: params.guid,
};
}
|
ca1c806683cc2e34d18ac63a0be6c9fe4eb935ca | 9,613 | ts | TypeScript | src/utils/table.ts | speedy-js/speedy-benchmark-action | 4dfa8cd23008af817d557d1ce5b5fa69ffb54b82 | [
"MIT"
] | null | null | null | src/utils/table.ts | speedy-js/speedy-benchmark-action | 4dfa8cd23008af817d557d1ce5b5fa69ffb54b82 | [
"MIT"
] | 4 | 2022-02-24T08:44:04.000Z | 2022-03-31T13:00:02.000Z | src/utils/table.ts | speedy-js/speedy-benchmark-action | 4dfa8cd23008af817d557d1ce5b5fa69ffb54b82 | [
"MIT"
] | null | null | null | // @ts-nocheck
// This file is copied from: https://github.com/wooorm/markdown-table (MIT)
/**
* @typedef Options
* Configuration (optional).
* @property {string|null|Array<string|null|undefined>} [align]
* One style for all columns, or styles for their respective columns.
* Each style is either `'l'` (left), `'r'` (right), or `'c'` (center).
* Other values are treated as `''`, which doesn’t place the colon in the
* alignment row but does align left.
* *Only the lowercased first character is used, so `Right` is fine.*
* @property {boolean} [padding=true]
* Whether to add a space of padding between delimiters and cells.
*
* When `true`, there is padding:
*
* ```markdown
* | Alpha | B |
* | ----- | ----- |
* | C | Delta |
* ```
*
* When `false`, there is no padding:
*
* ```markdown
* |Alpha|B |
* |-----|-----|
* |C |Delta|
* ```
* @property {boolean} [delimiterStart=true]
* Whether to begin each row with the delimiter.
*
* > 👉 **Note**: please don’t use this: it could create fragile structures
* > that aren’t understandable to some markdown parsers.
*
* When `true`, there are starting delimiters:
*
* ```markdown
* | Alpha | B |
* | ----- | ----- |
* | C | Delta |
* ```
*
* When `false`, there are no starting delimiters:
*
* ```markdown
* Alpha | B |
* ----- | ----- |
* C | Delta |
* ```
* @property {boolean} [delimiterEnd=true]
* Whether to end each row with the delimiter.
*
* > 👉 **Note**: please don’t use this: it could create fragile structures
* > that aren’t understandable to some markdown parsers.
*
* When `true`, there are ending delimiters:
*
* ```markdown
* | Alpha | B |
* | ----- | ----- |
* | C | Delta |
* ```
*
* When `false`, there are no ending delimiters:
*
* ```markdown
* | Alpha | B
* | ----- | -----
* | C | Delta
* ```
* @property {boolean} [alignDelimiters=true]
* Whether to align the delimiters.
* By default, they are aligned:
*
* ```markdown
* | Alpha | B |
* | ----- | ----- |
* | C | Delta |
* ```
*
* Pass `false` to make them staggered:
*
* ```markdown
* | Alpha | B |
* | - | - |
* | C | Delta |
* ```
* @property {(value: string) => number} [stringLength]
* Function to detect the length of table cell content.
* This is used when aligning the delimiters (`|`) between table cells.
* Full-width characters and emoji mess up delimiter alignment when viewing
* the markdown source.
* To fix this, you can pass this function, which receives the cell content
* and returns its “visible” size.
* Note that what is and isn’t visible depends on where the text is displayed.
*
* Without such a function, the following:
*
* ```js
* markdownTable([
* ['Alpha', 'Bravo'],
* ['中文', 'Charlie'],
* ['👩❤️👩', 'Delta']
* ])
* ```
*
* Yields:
*
* ```markdown
* | Alpha | Bravo |
* | - | - |
* | 中文 | Charlie |
* | 👩❤️👩 | Delta |
* ```
*
* With [`string-width`](https://github.com/sindresorhus/string-width):
*
* ```js
* import stringWidth from 'string-width'
*
* markdownTable(
* [
* ['Alpha', 'Bravo'],
* ['中文', 'Charlie'],
* ['👩❤️👩', 'Delta']
* ],
* {stringLength: stringWidth}
* )
* ```
*
* Yields:
*
* ```markdown
* | Alpha | Bravo |
* | ----- | ------- |
* | 中文 | Charlie |
* | 👩❤️👩 | Delta |
* ```
*/
/**
* @typedef {Options} MarkdownTableOptions
* @todo
* Remove next major.
*/
/**
* Generate a markdown ([GFM](https://docs.github.com/en/github/writing-on-github/working-with-advanced-formatting/organizing-information-with-tables)) table..
*
* @param {Array<Array<string|null|undefined>>} table
* Table data (matrix of strings).
* @param {Options} [options]
* Configuration (optional).
* @returns {string}
*/
export const markdownTable = function (table, options = {}) {
const align = (options.align || []).concat()
const stringLength = options.stringLength || defaultStringLength
/** @type {Array<number>} Character codes as symbols for alignment per column. */
const alignments = []
/** @type {Array<Array<string>>} Cells per row. */
const cellMatrix = []
/** @type {Array<Array<number>>} Sizes of each cell per row. */
const sizeMatrix = []
/** @type {Array<number>} */
const longestCellByColumn = []
let mostCellsPerRow = 0
let rowIndex = -1
// This is a superfluous loop if we don’t align delimiters, but otherwise we’d
// do superfluous work when aligning, so optimize for aligning.
while (++rowIndex < table.length) {
/** @type {Array<string>} */
const row = []
/** @type {Array<number>} */
const sizes = []
let columnIndex = -1
if (table[rowIndex].length > mostCellsPerRow) {
mostCellsPerRow = table[rowIndex].length
}
while (++columnIndex < table[rowIndex].length) {
const cell = serialize(table[rowIndex][columnIndex])
if (options.alignDelimiters !== false) {
const size = stringLength(cell)
sizes[columnIndex] = size
if (longestCellByColumn[columnIndex] === undefined || size > longestCellByColumn[columnIndex]) {
longestCellByColumn[columnIndex] = size
}
}
row.push(cell)
}
cellMatrix[rowIndex] = row
sizeMatrix[rowIndex] = sizes
}
// Figure out which alignments to use.
let columnIndex = -1
if (typeof align === 'object' && 'length' in align) {
while (++columnIndex < mostCellsPerRow) {
alignments[columnIndex] = toAlignment(align[columnIndex])
}
} else {
const code = toAlignment(align)
while (++columnIndex < mostCellsPerRow) {
alignments[columnIndex] = code
}
}
// Inject the alignment row.
columnIndex = -1
/** @type {Array<string>} */
const row = []
/** @type {Array<number>} */
const sizes = []
while (++columnIndex < mostCellsPerRow) {
const code = alignments[columnIndex]
let before = ''
let after = ''
if (code === 99 /* `c` */) {
before = ':'
after = ':'
} else if (code === 108 /* `l` */) {
before = ':'
} else if (code === 114 /* `r` */) {
after = ':'
}
// There *must* be at least one hyphen-minus in each alignment cell.
let size =
options.alignDelimiters === false
? 1
: Math.max(1, longestCellByColumn[columnIndex] - before.length - after.length)
const cell = before + '-'.repeat(size) + after
if (options.alignDelimiters !== false) {
size = before.length + size + after.length
if (size > longestCellByColumn[columnIndex]) {
longestCellByColumn[columnIndex] = size
}
sizes[columnIndex] = size
}
row[columnIndex] = cell
}
// Inject the alignment row.
cellMatrix.splice(1, 0, row)
sizeMatrix.splice(1, 0, sizes)
rowIndex = -1
/** @type {Array<string>} */
const lines = []
while (++rowIndex < cellMatrix.length) {
const row = cellMatrix[rowIndex]
const sizes = sizeMatrix[rowIndex]
columnIndex = -1
/** @type {Array<string>} */
const line = []
while (++columnIndex < mostCellsPerRow) {
const cell = row[columnIndex] || ''
let before = ''
let after = ''
if (options.alignDelimiters !== false) {
const size = longestCellByColumn[columnIndex] - (sizes[columnIndex] || 0)
const code = alignments[columnIndex]
if (code === 114 /* `r` */) {
before = ' '.repeat(size)
} else if (code === 99 /* `c` */) {
if (size % 2) {
before = ' '.repeat(size / 2 + 0.5)
after = ' '.repeat(size / 2 - 0.5)
} else {
before = ' '.repeat(size / 2)
after = before
}
} else {
after = ' '.repeat(size)
}
}
if (options.delimiterStart !== false && !columnIndex) {
line.push('|')
}
if (
options.padding !== false &&
// Don’t add the opening space if we’re not aligning and the cell is
// empty: there will be a closing space.
!(options.alignDelimiters === false && cell === '') &&
(options.delimiterStart !== false || columnIndex)
) {
line.push(' ')
}
if (options.alignDelimiters !== false) {
line.push(before)
}
line.push(cell)
if (options.alignDelimiters !== false) {
line.push(after)
}
if (options.padding !== false) {
line.push(' ')
}
if (options.delimiterEnd !== false || columnIndex !== mostCellsPerRow - 1) {
line.push('|')
}
}
lines.push(options.delimiterEnd === false ? line.join('').replace(/ +$/, '') : line.join(''))
}
return lines.join('\n')
}
/**
* @param {string|null|undefined} [value]
* @returns {string}
*/
function serialize (value) {
return value === null || value === undefined ? '' : String(value)
}
/**
* @param {string} value
* @returns {number}
*/
function defaultStringLength (value) {
return value.length
}
/**
* @param {string|null|undefined} value
* @returns {number}
*/
function toAlignment (value) {
const code = typeof value === 'string' ? value.codePointAt(0) : 0
return code === 67 /* `C` */ || code === 99 /* `c` */
? 99 /* `c` */
: code === 76 /* `L` */ || code === 108 /* `l` */
? 108 /* `l` */
: code === 82 /* `R` */ || code === 114 /* `r` */
? 114 /* `r` */
: 0
}
| 25.981081 | 159 | 0.551649 | 144 | 4 | 0 | 5 | 33 | 0 | 2 | 0 | 0 | 0 | 2 | 34 | 2,838 | 0.003171 | 0.011628 | 0 | 0 | 0.000705 | 0 | 0 | 0.215961 | // @ts-nocheck
// This file is copied from: https://github.com/wooorm/markdown-table (MIT)
/**
* @typedef Options
* Configuration (optional).
* @property {string|null|Array<string|null|undefined>} [align]
* One style for all columns, or styles for their respective columns.
* Each style is either `'l'` (left), `'r'` (right), or `'c'` (center).
* Other values are treated as `''`, which doesn’t place the colon in the
* alignment row but does align left.
* *Only the lowercased first character is used, so `Right` is fine.*
* @property {boolean} [padding=true]
* Whether to add a space of padding between delimiters and cells.
*
* When `true`, there is padding:
*
* ```markdown
* | Alpha | B |
* | ----- | ----- |
* | C | Delta |
* ```
*
* When `false`, there is no padding:
*
* ```markdown
* |Alpha|B |
* |-----|-----|
* |C |Delta|
* ```
* @property {boolean} [delimiterStart=true]
* Whether to begin each row with the delimiter.
*
* > 👉 **Note**: please don’t use this: it could create fragile structures
* > that aren’t understandable to some markdown parsers.
*
* When `true`, there are starting delimiters:
*
* ```markdown
* | Alpha | B |
* | ----- | ----- |
* | C | Delta |
* ```
*
* When `false`, there are no starting delimiters:
*
* ```markdown
* Alpha | B |
* ----- | ----- |
* C | Delta |
* ```
* @property {boolean} [delimiterEnd=true]
* Whether to end each row with the delimiter.
*
* > 👉 **Note**: please don’t use this: it could create fragile structures
* > that aren’t understandable to some markdown parsers.
*
* When `true`, there are ending delimiters:
*
* ```markdown
* | Alpha | B |
* | ----- | ----- |
* | C | Delta |
* ```
*
* When `false`, there are no ending delimiters:
*
* ```markdown
* | Alpha | B
* | ----- | -----
* | C | Delta
* ```
* @property {boolean} [alignDelimiters=true]
* Whether to align the delimiters.
* By default, they are aligned:
*
* ```markdown
* | Alpha | B |
* | ----- | ----- |
* | C | Delta |
* ```
*
* Pass `false` to make them staggered:
*
* ```markdown
* | Alpha | B |
* | - | - |
* | C | Delta |
* ```
* @property {(value: string) => number} [stringLength]
* Function to detect the length of table cell content.
* This is used when aligning the delimiters (`|`) between table cells.
* Full-width characters and emoji mess up delimiter alignment when viewing
* the markdown source.
* To fix this, you can pass this function, which receives the cell content
* and returns its “visible” size.
* Note that what is and isn’t visible depends on where the text is displayed.
*
* Without such a function, the following:
*
* ```js
* markdownTable([
* ['Alpha', 'Bravo'],
* ['中文', 'Charlie'],
* ['👩❤️👩', 'Delta']
* ])
* ```
*
* Yields:
*
* ```markdown
* | Alpha | Bravo |
* | - | - |
* | 中文 | Charlie |
* | 👩❤️👩 | Delta |
* ```
*
* With [`string-width`](https://github.com/sindresorhus/string-width):
*
* ```js
* import stringWidth from 'string-width'
*
* markdownTable(
* [
* ['Alpha', 'Bravo'],
* ['中文', 'Charlie'],
* ['👩❤️👩', 'Delta']
* ],
* {stringLength: stringWidth}
* )
* ```
*
* Yields:
*
* ```markdown
* | Alpha | Bravo |
* | ----- | ------- |
* | 中文 | Charlie |
* | 👩❤️👩 | Delta |
* ```
*/
/**
* @typedef {Options} MarkdownTableOptions
* @todo
* Remove next major.
*/
/**
* Generate a markdown ([GFM](https://docs.github.com/en/github/writing-on-github/working-with-advanced-formatting/organizing-information-with-tables)) table..
*
* @param {Array<Array<string|null|undefined>>} table
* Table data (matrix of strings).
* @param {Options} [options]
* Configuration (optional).
* @returns {string}
*/
export const markdownTable = function (table, options = {}) {
const align = (options.align || []).concat()
const stringLength = options.stringLength || defaultStringLength
/** @type {Array<number>} Character codes as symbols for alignment per column. */
const alignments = []
/** @type {Array<Array<string>>} Cells per row. */
const cellMatrix = []
/** @type {Array<Array<number>>} Sizes of each cell per row. */
const sizeMatrix = []
/** @type {Array<number>} */
const longestCellByColumn = []
let mostCellsPerRow = 0
let rowIndex = -1
// This is a superfluous loop if we don’t align delimiters, but otherwise we’d
// do superfluous work when aligning, so optimize for aligning.
while (++rowIndex < table.length) {
/** @type {Array<string>} */
const row = []
/** @type {Array<number>} */
const sizes = []
let columnIndex = -1
if (table[rowIndex].length > mostCellsPerRow) {
mostCellsPerRow = table[rowIndex].length
}
while (++columnIndex < table[rowIndex].length) {
const cell = serialize(table[rowIndex][columnIndex])
if (options.alignDelimiters !== false) {
const size = stringLength(cell)
sizes[columnIndex] = size
if (longestCellByColumn[columnIndex] === undefined || size > longestCellByColumn[columnIndex]) {
longestCellByColumn[columnIndex] = size
}
}
row.push(cell)
}
cellMatrix[rowIndex] = row
sizeMatrix[rowIndex] = sizes
}
// Figure out which alignments to use.
let columnIndex = -1
if (typeof align === 'object' && 'length' in align) {
while (++columnIndex < mostCellsPerRow) {
alignments[columnIndex] = toAlignment(align[columnIndex])
}
} else {
const code = toAlignment(align)
while (++columnIndex < mostCellsPerRow) {
alignments[columnIndex] = code
}
}
// Inject the alignment row.
columnIndex = -1
/** @type {Array<string>} */
const row = []
/** @type {Array<number>} */
const sizes = []
while (++columnIndex < mostCellsPerRow) {
const code = alignments[columnIndex]
let before = ''
let after = ''
if (code === 99 /* `c` */) {
before = ':'
after = ':'
} else if (code === 108 /* `l` */) {
before = ':'
} else if (code === 114 /* `r` */) {
after = ':'
}
// There *must* be at least one hyphen-minus in each alignment cell.
let size =
options.alignDelimiters === false
? 1
: Math.max(1, longestCellByColumn[columnIndex] - before.length - after.length)
const cell = before + '-'.repeat(size) + after
if (options.alignDelimiters !== false) {
size = before.length + size + after.length
if (size > longestCellByColumn[columnIndex]) {
longestCellByColumn[columnIndex] = size
}
sizes[columnIndex] = size
}
row[columnIndex] = cell
}
// Inject the alignment row.
cellMatrix.splice(1, 0, row)
sizeMatrix.splice(1, 0, sizes)
rowIndex = -1
/** @type {Array<string>} */
const lines = []
while (++rowIndex < cellMatrix.length) {
const row = cellMatrix[rowIndex]
const sizes = sizeMatrix[rowIndex]
columnIndex = -1
/** @type {Array<string>} */
const line = []
while (++columnIndex < mostCellsPerRow) {
const cell = row[columnIndex] || ''
let before = ''
let after = ''
if (options.alignDelimiters !== false) {
const size = longestCellByColumn[columnIndex] - (sizes[columnIndex] || 0)
const code = alignments[columnIndex]
if (code === 114 /* `r` */) {
before = ' '.repeat(size)
} else if (code === 99 /* `c` */) {
if (size % 2) {
before = ' '.repeat(size / 2 + 0.5)
after = ' '.repeat(size / 2 - 0.5)
} else {
before = ' '.repeat(size / 2)
after = before
}
} else {
after = ' '.repeat(size)
}
}
if (options.delimiterStart !== false && !columnIndex) {
line.push('|')
}
if (
options.padding !== false &&
// Don’t add the opening space if we’re not aligning and the cell is
// empty: there will be a closing space.
!(options.alignDelimiters === false && cell === '') &&
(options.delimiterStart !== false || columnIndex)
) {
line.push(' ')
}
if (options.alignDelimiters !== false) {
line.push(before)
}
line.push(cell)
if (options.alignDelimiters !== false) {
line.push(after)
}
if (options.padding !== false) {
line.push(' ')
}
if (options.delimiterEnd !== false || columnIndex !== mostCellsPerRow - 1) {
line.push('|')
}
}
lines.push(options.delimiterEnd === false ? line.join('').replace(/ +$/, '') : line.join(''))
}
return lines.join('\n')
}
/**
* @param {string|null|undefined} [value]
* @returns {string}
*/
/* Example usages of 'serialize' are shown below:
serialize(table[rowIndex][columnIndex]);
*/
function serialize (value) {
return value === null || value === undefined ? '' : String(value)
}
/**
* @param {string} value
* @returns {number}
*/
/* Example usages of 'defaultStringLength' are shown below:
options.stringLength || defaultStringLength;
*/
function defaultStringLength (value) {
return value.length
}
/**
* @param {string|null|undefined} value
* @returns {number}
*/
/* Example usages of 'toAlignment' are shown below:
alignments[columnIndex] = toAlignment(align[columnIndex]);
toAlignment(align);
*/
function toAlignment (value) {
const code = typeof value === 'string' ? value.codePointAt(0) : 0
return code === 67 /* `C` */ || code === 99 /* `c` */
? 99 /* `c` */
: code === 76 /* `L` */ || code === 108 /* `l` */
? 108 /* `l` */
: code === 82 /* `R` */ || code === 114 /* `r` */
? 114 /* `r` */
: 0
}
|
ca95641b386ab877b6192cfe0a801386bd5872da | 3,124 | ts | TypeScript | src/index.ts | murugaratham/nricvalidator | deb92034dcb7440a62f3ca7140d70477dddad7fd | [
"MIT"
] | null | null | null | src/index.ts | murugaratham/nricvalidator | deb92034dcb7440a62f3ca7140d70477dddad7fd | [
"MIT"
] | 1 | 2022-03-30T11:14:33.000Z | 2022-03-30T11:14:33.000Z | src/index.ts | murugaratham/nricvalidator | deb92034dcb7440a62f3ca7140d70477dddad7fd | [
"MIT"
] | null | null | null | //why? look @ http://www.ngiam.net/NRIC/NRIC_numbers.pdf deeper.
const offsetMap = new Map([
["T", 4],
["G", 4],
["M", 3],
]);
/**
*
* @param idToCheck {string} identification number to check
* @returns {boolean} validation results
*/
export const validate = (idToCheck: string): boolean => {
//short circuit evaulation
if (idToCheck.length !== 9) {
return false;
}
const { valid } = tryGetChecksum(idToCheck); // sum them up
return valid;
};
export const generate = (partialSeedId?: string) => {
const legalStartingCharacters = ["S", "T", "F", "G", "M"];
if (partialSeedId) {
const hasLegalStartingCharacter = legalStartingCharacters.some((legalStartingCharacter) =>
partialSeedId.charAt(0).toUpperCase().startsWith(legalStartingCharacter),
);
if (!hasLegalStartingCharacter) {
throw new Error("Invalid start character");
} else {
const containsNumbersOnlyAfterFirst = !isNaN(Number(partialSeedId.substring(1, partialSeedId.length)));
if (!containsNumbersOnlyAfterFirst) {
throw new Error("Invalid seed id");
}
}
}
const startChar =
(partialSeedId && partialSeedId.charAt(0)) || legalStartingCharacters[Math.floor(Math.random() * 4)];
let generatedId: string[] = (partialSeedId && partialSeedId.substring(1, partialSeedId.length).split("")) || [];
while (generatedId.length !== 7) {
generatedId.push(Math.floor(Math.random() * 10) + "");
}
const { checksum } = tryGetChecksum(startChar + generatedId.join(""));
return `${startChar}${generatedId.join("")}${checksum}`.toUpperCase();
};
/**
*
* @param idDigits {string[]} identification number to check
* @returns weight
*/
const getWeights = (idDigits: string[]): number => {
let weights = [2, 7, 6, 5, 4, 3, 2]; // read: http://www.ngiam.net/NRIC/NRIC_numbers.pdf
return idDigits
.map((value, idx) => parseInt(value, 10) * weights[idx]) // multiply each digit with their respective weights
.reduce((prev: number, idDigit: number) => prev + idDigit);
};
const tryGetChecksum = (idDigits: string): { checksum?: string; valid: boolean } => {
// checksum tables
const ST = ["J", "Z", "I", "H", "G", "F", "E", "D", "C", "B", "A"];
const FG = ["X", "W", "U", "T", "R", "Q", "P", "N", "M", "L", "K"];
const M = ["X", "W", "U", "T", "R", "Q", "P", "N", "J", "L", "K"];
const id = idDigits.split("");
let [startChar, ...idArray] = id;
const endChar = idArray.length === 8 ? idArray.pop()!.toUpperCase() : "";
//add offset by century prefix if required
const weight = (offsetMap.get(startChar.toUpperCase()) || 0) + getWeights(idArray);
const remainder = weight % 11;
startChar = startChar.toUpperCase();
if (startChar === "S" || startChar === "T") {
return { checksum: ST[remainder], valid: ST[remainder] === endChar };
} else if (startChar === "F" || startChar === "G") {
return { checksum: FG[remainder], valid: FG[remainder] === endChar };
} else if (startChar === "M") {
return { checksum: M[remainder], valid: M[remainder] === endChar };
} else {
return { checksum: undefined, valid: false };
}
};
| 37.190476 | 114 | 0.623239 | 62 | 7 | 0 | 9 | 21 | 0 | 2 | 0 | 11 | 0 | 0 | 7.428571 | 948 | 0.016878 | 0.022152 | 0 | 0 | 0 | 0 | 0.297297 | 0.28204 | //why? look @ http://www.ngiam.net/NRIC/NRIC_numbers.pdf deeper.
const offsetMap = new Map([
["T", 4],
["G", 4],
["M", 3],
]);
/**
*
* @param idToCheck {string} identification number to check
* @returns {boolean} validation results
*/
export const validate = (idToCheck) => {
//short circuit evaulation
if (idToCheck.length !== 9) {
return false;
}
const { valid } = tryGetChecksum(idToCheck); // sum them up
return valid;
};
export const generate = (partialSeedId?) => {
const legalStartingCharacters = ["S", "T", "F", "G", "M"];
if (partialSeedId) {
const hasLegalStartingCharacter = legalStartingCharacters.some((legalStartingCharacter) =>
partialSeedId.charAt(0).toUpperCase().startsWith(legalStartingCharacter),
);
if (!hasLegalStartingCharacter) {
throw new Error("Invalid start character");
} else {
const containsNumbersOnlyAfterFirst = !isNaN(Number(partialSeedId.substring(1, partialSeedId.length)));
if (!containsNumbersOnlyAfterFirst) {
throw new Error("Invalid seed id");
}
}
}
const startChar =
(partialSeedId && partialSeedId.charAt(0)) || legalStartingCharacters[Math.floor(Math.random() * 4)];
let generatedId = (partialSeedId && partialSeedId.substring(1, partialSeedId.length).split("")) || [];
while (generatedId.length !== 7) {
generatedId.push(Math.floor(Math.random() * 10) + "");
}
const { checksum } = tryGetChecksum(startChar + generatedId.join(""));
return `${startChar}${generatedId.join("")}${checksum}`.toUpperCase();
};
/**
*
* @param idDigits {string[]} identification number to check
* @returns weight
*/
/* Example usages of 'getWeights' are shown below:
(offsetMap.get(startChar.toUpperCase()) || 0) + getWeights(idArray);
*/
const getWeights = (idDigits) => {
let weights = [2, 7, 6, 5, 4, 3, 2]; // read: http://www.ngiam.net/NRIC/NRIC_numbers.pdf
return idDigits
.map((value, idx) => parseInt(value, 10) * weights[idx]) // multiply each digit with their respective weights
.reduce((prev, idDigit) => prev + idDigit);
};
/* Example usages of 'tryGetChecksum' are shown below:
tryGetChecksum(idToCheck);
tryGetChecksum(startChar + generatedId.join(""));
*/
const tryGetChecksum = (idDigits) => {
// checksum tables
const ST = ["J", "Z", "I", "H", "G", "F", "E", "D", "C", "B", "A"];
const FG = ["X", "W", "U", "T", "R", "Q", "P", "N", "M", "L", "K"];
const M = ["X", "W", "U", "T", "R", "Q", "P", "N", "J", "L", "K"];
const id = idDigits.split("");
let [startChar, ...idArray] = id;
const endChar = idArray.length === 8 ? idArray.pop()!.toUpperCase() : "";
//add offset by century prefix if required
const weight = (offsetMap.get(startChar.toUpperCase()) || 0) + getWeights(idArray);
const remainder = weight % 11;
startChar = startChar.toUpperCase();
if (startChar === "S" || startChar === "T") {
return { checksum: ST[remainder], valid: ST[remainder] === endChar };
} else if (startChar === "F" || startChar === "G") {
return { checksum: FG[remainder], valid: FG[remainder] === endChar };
} else if (startChar === "M") {
return { checksum: M[remainder], valid: M[remainder] === endChar };
} else {
return { checksum: undefined, valid: false };
}
};
|
cab0c5eb88a380c44b56c39652fef845d2b4d469 | 2,307 | ts | TypeScript | typescript/src/problems/s91_decode_ways.ts | eteplus/leetcode | 13cb7aac323dd68c670b1548a8d72667eb68bd7c | [
"MIT"
] | 1 | 2022-01-25T09:03:59.000Z | 2022-01-25T09:03:59.000Z | typescript/src/problems/s91_decode_ways.ts | eteplus/leetcode | 13cb7aac323dd68c670b1548a8d72667eb68bd7c | [
"MIT"
] | null | null | null | typescript/src/problems/s91_decode_ways.ts | eteplus/leetcode | 13cb7aac323dd68c670b1548a8d72667eb68bd7c | [
"MIT"
] | null | null | null | /**
* Runtime: 133ms
* Memory Usage: 43.7 MB
* @link https://leetcode.com/problems/decode-ways/
* @param s
*/
export function numDecodingsTwo(s: string): number {
if (s.length === 0 || s[0] === '0') {
return 0;
}
if (s.length === 1) {
return 1;
}
const dp: number[] = [];
dp[0] = 1;
for (let i = 1; i < s.length; i++) {
let x = Number(s[i]);
let y = Number(s[i - 1] + s[i]);
if (x <= 0 && (y <= 0 || y > 26)) {
return 0;
}
if (x > 0) {
if (y >= 10 && y <= 26) {
dp[i] = dp[i - 1] + (i - 2 < 0 ? 1 : dp[i - 2]);
} else {
dp[i] = dp[i - 1];
}
} else {
dp[i] = i - 2 < 0 ? 1 : dp[i - 2];
}
}
return dp[s.length - 1];
}
/**
* Runtime: 78ms
* Memory Usage: 44.7 MB
*/
export function numDecodings(s: string): number {
if (s.length === 0 || s[0] === '0') {
return 0;
}
if (s.length === 1) {
return 1;
}
const dp: number[] = [];
dp[0] = 1;
for (let i = 1; i < s.length; i++) {
let prev = s[i - 1];
let curr = s[i];
if (curr === '0') {
if (!['1', '2'].includes(prev)) {
// 00, 60 is not allowed
return 0;
}
// 10, 20
dp[i] = i - 2 < 0 ? 1 : dp[i - 2]
} else {
if (prev === '1' || (prev === '2' && ['1', '2', '3', '4', '5', '6'].includes(curr))) {
// 11 - 26
dp[i] = dp[i - 1] + (i - 2 < 0 ? 1 : dp[i - 2]);
} else {
// 30 - 99
dp[i] = dp[i - 1];
}
}
}
return dp[s.length - 1];
}
/**
* Runtime: 126ms
* Memory Usage: 46.4 MB
*/
export function numDecodingsWithMap(s: string): number {
const map = new Map<string, string>();
let c = 'A';
for (let i = 1; i <= 26; i++) {
map.set(String(i), String.fromCharCode(c.charCodeAt(0) + i - 1));
}
if (s.length === 0 || s[0] === '0') {
return 0;
}
if (s.length === 1) {
return 1;
}
const dp: number[] = [];
dp[0] = 1;
for (let i = 1; i < s.length; i++) {
if (!map.has(s[i]) && !map.has(s[i - 1] + s[i])) {
return 0;
}
if (map.has(s[i])) {
if (map.has(s[i - 1] + s[i])) {
dp[i] = dp[i - 1] + (i - 2 < 0 ? 1 : dp[i - 2]);
} else {
dp[i] = dp[i - 1];
}
} else {
dp[i] = i - 2 < 0 ? 1 : dp[i - 2];
}
}
return dp[s.length - 1];
} | 22.182692 | 92 | 0.407022 | 84 | 3 | 0 | 3 | 13 | 0 | 0 | 0 | 11 | 0 | 0 | 26 | 1,003 | 0.005982 | 0.012961 | 0 | 0 | 0 | 0 | 0.578947 | 0.225712 | /**
* Runtime: 133ms
* Memory Usage: 43.7 MB
* @link https://leetcode.com/problems/decode-ways/
* @param s
*/
export function numDecodingsTwo(s) {
if (s.length === 0 || s[0] === '0') {
return 0;
}
if (s.length === 1) {
return 1;
}
const dp = [];
dp[0] = 1;
for (let i = 1; i < s.length; i++) {
let x = Number(s[i]);
let y = Number(s[i - 1] + s[i]);
if (x <= 0 && (y <= 0 || y > 26)) {
return 0;
}
if (x > 0) {
if (y >= 10 && y <= 26) {
dp[i] = dp[i - 1] + (i - 2 < 0 ? 1 : dp[i - 2]);
} else {
dp[i] = dp[i - 1];
}
} else {
dp[i] = i - 2 < 0 ? 1 : dp[i - 2];
}
}
return dp[s.length - 1];
}
/**
* Runtime: 78ms
* Memory Usage: 44.7 MB
*/
export function numDecodings(s) {
if (s.length === 0 || s[0] === '0') {
return 0;
}
if (s.length === 1) {
return 1;
}
const dp = [];
dp[0] = 1;
for (let i = 1; i < s.length; i++) {
let prev = s[i - 1];
let curr = s[i];
if (curr === '0') {
if (!['1', '2'].includes(prev)) {
// 00, 60 is not allowed
return 0;
}
// 10, 20
dp[i] = i - 2 < 0 ? 1 : dp[i - 2]
} else {
if (prev === '1' || (prev === '2' && ['1', '2', '3', '4', '5', '6'].includes(curr))) {
// 11 - 26
dp[i] = dp[i - 1] + (i - 2 < 0 ? 1 : dp[i - 2]);
} else {
// 30 - 99
dp[i] = dp[i - 1];
}
}
}
return dp[s.length - 1];
}
/**
* Runtime: 126ms
* Memory Usage: 46.4 MB
*/
export function numDecodingsWithMap(s) {
const map = new Map<string, string>();
let c = 'A';
for (let i = 1; i <= 26; i++) {
map.set(String(i), String.fromCharCode(c.charCodeAt(0) + i - 1));
}
if (s.length === 0 || s[0] === '0') {
return 0;
}
if (s.length === 1) {
return 1;
}
const dp = [];
dp[0] = 1;
for (let i = 1; i < s.length; i++) {
if (!map.has(s[i]) && !map.has(s[i - 1] + s[i])) {
return 0;
}
if (map.has(s[i])) {
if (map.has(s[i - 1] + s[i])) {
dp[i] = dp[i - 1] + (i - 2 < 0 ? 1 : dp[i - 2]);
} else {
dp[i] = dp[i - 1];
}
} else {
dp[i] = i - 2 < 0 ? 1 : dp[i - 2];
}
}
return dp[s.length - 1];
} |
cad75d6e0e19940214d2e23030bb2088464397b3 | 2,402 | ts | TypeScript | src/models/RequestTime.ts | api-client/core | aa157d09b39efa77d49f2d425e7b37828abe0c5b | [
"Apache-2.0"
] | null | null | null | src/models/RequestTime.ts | api-client/core | aa157d09b39efa77d49f2d425e7b37828abe0c5b | [
"Apache-2.0"
] | 1 | 2022-02-14T00:01:04.000Z | 2022-02-14T00:04:07.000Z | src/models/RequestTime.ts | advanced-rest-client/core | 2efb946f786d8b46e7131c62e0011f6e090ddec3 | [
"Apache-2.0"
] | null | null | null | export const Kind = 'Core#RequestTime';
/**
* Schema definition for API Client request timings. This is mostly consistent with HAR timings.
*/
export interface IRequestTime {
kind?: typeof Kind;
connect: number;
receive: number;
send: number;
wait: number;
blocked: number;
dns: number;
ssl?: number;
}
export class RequestTime {
kind = Kind;
connect = -1;
receive = -1;
send = -1;
wait = -1;
blocked = -1;
dns = -1;
ssl?: number;
/**
* @param input The timings definition used to restore the state.
*/
constructor(input?: string|IRequestTime) {
let init: IRequestTime;
if (typeof input === 'string') {
init = JSON.parse(input);
} else if (typeof input === 'object') {
init = input;
} else {
init = {
connect: -1,
receive: -1,
send: -1,
wait: -1,
blocked: -1,
dns: -1,
};
}
this.new(init);
}
/**
* Creates a new timing clearing anything that is so far defined.
*/
new(init: IRequestTime): void {
const { connect=-1, receive=-1, send=-1, wait=-1, blocked=-1, dns=-1, ssl=-1 } = init;
this.kind = Kind;
this.connect = connect;
this.receive = receive;
this.send = send;
this.wait = wait;
this.blocked = blocked;
this.dns = dns;
this.ssl = ssl;
}
toJSON(): IRequestTime {
const result: IRequestTime = {
kind: Kind,
connect: this.connect,
receive: this.receive,
send: this.send,
wait: this.wait,
blocked: this.blocked,
dns: this.dns,
};
if (typeof this.ssl === 'number') {
result.ssl = this.ssl;
}
return result;
}
total(): number {
let result = 0;
if (typeof this.connect === 'number' && this.connect > 0) {
result += this.connect;
}
if (typeof this.receive === 'number' && this.receive > 0) {
result += this.receive;
}
if (typeof this.send === 'number' && this.send > 0) {
result += this.send;
}
if (typeof this.wait === 'number' && this.wait > 0) {
result += this.wait;
}
if (typeof this.blocked === 'number' && this.blocked > 0) {
result += this.blocked;
}
if (typeof this.dns === 'number' && this.dns > 0) {
result += this.dns;
}
if (typeof this.ssl === 'number' && this.ssl > 0) {
result += this.ssl;
}
return result;
}
}
| 22.448598 | 96 | 0.550791 | 90 | 4 | 0 | 2 | 5 | 16 | 1 | 0 | 11 | 2 | 10 | 15.25 | 710 | 0.008451 | 0.007042 | 0.022535 | 0.002817 | 0.014085 | 0 | 0.407407 | 0.214996 | export const Kind = 'Core#RequestTime';
/**
* Schema definition for API Client request timings. This is mostly consistent with HAR timings.
*/
export interface IRequestTime {
kind?;
connect;
receive;
send;
wait;
blocked;
dns;
ssl?;
}
export class RequestTime {
kind = Kind;
connect = -1;
receive = -1;
send = -1;
wait = -1;
blocked = -1;
dns = -1;
ssl?;
/**
* @param input The timings definition used to restore the state.
*/
constructor(input?) {
let init;
if (typeof input === 'string') {
init = JSON.parse(input);
} else if (typeof input === 'object') {
init = input;
} else {
init = {
connect: -1,
receive: -1,
send: -1,
wait: -1,
blocked: -1,
dns: -1,
};
}
this.new(init);
}
/**
* Creates a new timing clearing anything that is so far defined.
*/
new(init) {
const { connect=-1, receive=-1, send=-1, wait=-1, blocked=-1, dns=-1, ssl=-1 } = init;
this.kind = Kind;
this.connect = connect;
this.receive = receive;
this.send = send;
this.wait = wait;
this.blocked = blocked;
this.dns = dns;
this.ssl = ssl;
}
toJSON() {
const result = {
kind: Kind,
connect: this.connect,
receive: this.receive,
send: this.send,
wait: this.wait,
blocked: this.blocked,
dns: this.dns,
};
if (typeof this.ssl === 'number') {
result.ssl = this.ssl;
}
return result;
}
total() {
let result = 0;
if (typeof this.connect === 'number' && this.connect > 0) {
result += this.connect;
}
if (typeof this.receive === 'number' && this.receive > 0) {
result += this.receive;
}
if (typeof this.send === 'number' && this.send > 0) {
result += this.send;
}
if (typeof this.wait === 'number' && this.wait > 0) {
result += this.wait;
}
if (typeof this.blocked === 'number' && this.blocked > 0) {
result += this.blocked;
}
if (typeof this.dns === 'number' && this.dns > 0) {
result += this.dns;
}
if (typeof this.ssl === 'number' && this.ssl > 0) {
result += this.ssl;
}
return result;
}
}
|
5a5faa137b0e9b9d0f6448fc23933e9af9534061 | 2,545 | ts | TypeScript | src/HppGenerator.ts | dams333/CPP_Class_Generator | 26ea24d0578ce637fb0b1faf43c18d8699b36ef3 | [
"MIT"
] | 2 | 2022-02-12T13:11:09.000Z | 2022-02-12T13:20:03.000Z | src/HppGenerator.ts | dams333/CPP_Class_Generator | 26ea24d0578ce637fb0b1faf43c18d8699b36ef3 | [
"MIT"
] | 1 | 2022-02-12T13:15:39.000Z | 2022-02-12T19:15:59.000Z | src/HppGenerator.ts | dams333/CPP_Class_Generator | 26ea24d0578ce637fb0b1faf43c18d8699b36ef3 | [
"MIT"
] | null | null | null | export function getHppConstructors(message: any)
{
let text = "\t\t// Constructors\n";
text += "\t\t" + message.className + "();\n";
text += "\t\t" + message.className + "(const " + message.className + " ©);\n";
if(message.fields.length > 0)
{
text += "\t\t" + message.className + "(";
for(let i = 0; i < message.fields.length; i++)
{
if(i !== 0)
{
text += ", ";
}
text += message.fields[i].field_type + " " + message.fields[i].field_name;
}
text += ");\n";
}
return text;
}
export function getHppDestructors(message: any)
{
let text = "\t\t\n\t\t// Destructor\n";
text += "\t\t~" + message.className + "();\n";
return text;
}
export function getHppOperators(message: any)
{
let text = "\t\t\n\t\t// Operators\n";
text += "\t\t" + message.className + " & operator=(const " + message.className + " &assign);\n";
return text;
}
export function getHppGettersSetters(message: any)
{
let text = "";
if(message.fields.length > 0)
{
text += "\t\t\n\t\t// Getters / Setters\n";
for(let i = 0; i < message.fields.length; i++)
{
if(message.fields[i].getter)
{
text += "\t\t" + message.fields[i].field_type + " get" + message.fields[i].field_name[0].toUpperCase() + message.fields[i].field_name.slice(1) + "() const;\n";
}
if(message.fields[i].setter)
{
text += "\t\tvoid set" + message.fields[i].field_name[0].toUpperCase() + message.fields[i].field_name.slice(1) + "(" + message.fields[i].field_type + " " + message.fields[i].field_name + ");\n";
}
}
}
return text;
}
export function getHppExceptions(message: any)
{
let text = "";
if(message.classExceptions.length > 0)
{
text += "\t\t\n\t\t// Exceptions\n";
for(let i = 0; i < message.classExceptions.length; i++)
{
text += "\t\tclass " + message.classExceptions[i].exception_name + " : public std::exception {\n";
text += "\t\t\tvirtual const char* what() const throw();\n";
text += "\t\t};\n";
}
}
return text;
}
export function getHppPrivate(message: any)
{
let text = "";
for(let i = 0; i < message.fields.length; i++)
{
text += "\t\t" + message.fields[i].field_type + " _" + message.fields[i].field_name + ";\n";
}
return text;
}
export function getHppStreamOperator(message: any)
{
let text = "";
if(message.format !== "")
{
text += "// Stream operators\n";
text += "std::ostream & operator<<(std::ostream &stream, const " + message.className + " &object);\n\n";
}
return text;
} | 27.663043 | 199 | 0.582318 | 86 | 7 | 0 | 7 | 11 | 0 | 0 | 7 | 0 | 0 | 0 | 9.285714 | 946 | 0.014799 | 0.011628 | 0 | 0 | 0 | 0.28 | 0 | 0.238206 | export function getHppConstructors(message)
{
let text = "\t\t// Constructors\n";
text += "\t\t" + message.className + "();\n";
text += "\t\t" + message.className + "(const " + message.className + " ©);\n";
if(message.fields.length > 0)
{
text += "\t\t" + message.className + "(";
for(let i = 0; i < message.fields.length; i++)
{
if(i !== 0)
{
text += ", ";
}
text += message.fields[i].field_type + " " + message.fields[i].field_name;
}
text += ");\n";
}
return text;
}
export function getHppDestructors(message)
{
let text = "\t\t\n\t\t// Destructor\n";
text += "\t\t~" + message.className + "();\n";
return text;
}
export function getHppOperators(message)
{
let text = "\t\t\n\t\t// Operators\n";
text += "\t\t" + message.className + " & operator=(const " + message.className + " &assign);\n";
return text;
}
export function getHppGettersSetters(message)
{
let text = "";
if(message.fields.length > 0)
{
text += "\t\t\n\t\t// Getters / Setters\n";
for(let i = 0; i < message.fields.length; i++)
{
if(message.fields[i].getter)
{
text += "\t\t" + message.fields[i].field_type + " get" + message.fields[i].field_name[0].toUpperCase() + message.fields[i].field_name.slice(1) + "() const;\n";
}
if(message.fields[i].setter)
{
text += "\t\tvoid set" + message.fields[i].field_name[0].toUpperCase() + message.fields[i].field_name.slice(1) + "(" + message.fields[i].field_type + " " + message.fields[i].field_name + ");\n";
}
}
}
return text;
}
export function getHppExceptions(message)
{
let text = "";
if(message.classExceptions.length > 0)
{
text += "\t\t\n\t\t// Exceptions\n";
for(let i = 0; i < message.classExceptions.length; i++)
{
text += "\t\tclass " + message.classExceptions[i].exception_name + " : public std::exception {\n";
text += "\t\t\tvirtual const char* what() const throw();\n";
text += "\t\t};\n";
}
}
return text;
}
export function getHppPrivate(message)
{
let text = "";
for(let i = 0; i < message.fields.length; i++)
{
text += "\t\t" + message.fields[i].field_type + " _" + message.fields[i].field_name + ";\n";
}
return text;
}
export function getHppStreamOperator(message)
{
let text = "";
if(message.format !== "")
{
text += "// Stream operators\n";
text += "std::ostream & operator<<(std::ostream &stream, const " + message.className + " &object);\n\n";
}
return text;
} |
9e0f6a44e61ccd57f852af6b01eee8afe58a6ccc | 2,612 | ts | TypeScript | client/src/utils/timePercent.ts | justzerock/mp-time-by-taro | 87ea0c841090b6915b5f0dd38c437bf01ba5fe64 | [
"MIT"
] | null | null | null | client/src/utils/timePercent.ts | justzerock/mp-time-by-taro | 87ea0c841090b6915b5f0dd38c437bf01ba5fe64 | [
"MIT"
] | 3 | 2022-02-13T05:53:27.000Z | 2022-02-26T23:30:44.000Z | client/src/utils/timePercent.ts | justzerock/mp-time-by-taro | 87ea0c841090b6915b5f0dd38c437bf01ba5fe64 | [
"MIT"
] | null | null | null | const timePercent = (type: string, wStart = 0, date1= new Date(), date2= new Date()) => {
let date = new Date()
let year = date.getFullYear()
let month = date.getMonth()
let weekDay = date.getDay()
let day = date.getDate()
let now = Date.now()
let percent = 0
let passedDays = 0
let passedHours = 0
switch (type) {
case 'year':
let yearStart = getMyTime(year, 0, 1)
let yearEnd = getMyTime(year + 1, 0, 1)
passedDays = getPassedDays(now - yearStart)
percent = getPercent((now - yearStart)/(yearEnd - yearStart))
return {time: year, percent, detail: passedDays}
break
case 'month':
let monthStart = getMyTime(year, month, 1)
let monthEnd = getMyTime(year, month + 1, 1)
passedDays = getPassedDays(now - monthStart)
percent = getPercent((now - monthStart)/(monthEnd - monthStart))
return {time: month + 1, percent, detail: passedDays}
break
case 'week':
let days = getDays(wStart, weekDay)
let weekStart = getMyTime(year, month, day - days)
let weekEnd = getMyTime(year, month, day + 7 - days)
passedDays = getPassedDays(now - weekStart)
percent = getPercent((now - weekStart)/(weekEnd - weekStart))
return {time: weekDay, percent, detail: passedDays}
break
case 'day':
let dayStart = getMyTime(year, month, day)
let dayEnd = getMyTime(year, month, day + 1)
passedHours = Math.floor((now - dayStart)/3600000)
percent = getPercent((now - dayStart)/(dayEnd - dayStart))
return {time: day, percent, detail: passedHours}
break
case 'life':
let age = year - date1.getFullYear()
let midDate = new Date(date1.getTime())
let curYear = new Date(midDate.setFullYear(midDate.getFullYear() + age))
age = curYear > date ? age-1 : age
let lifeStart = date1.getTime()
let lifeEnd = date2.getTime()
passedDays = getPassedDays(now - lifeStart)
percent = getPercent((now - lifeStart)/(lifeEnd - lifeStart))
return {time: age, percent, detail: passedDays}
break
}
}
// 时间转天数
const getPassedDays = (time) => {
return Math.floor(time/86400000)
}
// 计算本周过去的天数
const getDays = (wStart, weekDay) => {
let days = weekDay
if (wStart) {
if (weekDay) {
days -= 1
} else {
days += 6
}
}
return days
}
// 获取日期毫秒值
const getMyTime = (year: number, month: number, day: number) => {
return new Date(year, month, day).getTime()
}
// 获取百分比
const getPercent = (percent: number) => {
return Math.floor(percent * 1000) / 10
}
export default { timePercent }
| 31.095238 | 89 | 0.627489 | 74 | 5 | 0 | 11 | 29 | 0 | 4 | 0 | 5 | 0 | 0 | 12.6 | 805 | 0.019876 | 0.036025 | 0 | 0 | 0 | 0 | 0.111111 | 0.335171 | /* Example usages of 'timePercent' are shown below:
;
*/
const timePercent = (type, wStart = 0, date1= new Date(), date2= new Date()) => {
let date = new Date()
let year = date.getFullYear()
let month = date.getMonth()
let weekDay = date.getDay()
let day = date.getDate()
let now = Date.now()
let percent = 0
let passedDays = 0
let passedHours = 0
switch (type) {
case 'year':
let yearStart = getMyTime(year, 0, 1)
let yearEnd = getMyTime(year + 1, 0, 1)
passedDays = getPassedDays(now - yearStart)
percent = getPercent((now - yearStart)/(yearEnd - yearStart))
return {time: year, percent, detail: passedDays}
break
case 'month':
let monthStart = getMyTime(year, month, 1)
let monthEnd = getMyTime(year, month + 1, 1)
passedDays = getPassedDays(now - monthStart)
percent = getPercent((now - monthStart)/(monthEnd - monthStart))
return {time: month + 1, percent, detail: passedDays}
break
case 'week':
let days = getDays(wStart, weekDay)
let weekStart = getMyTime(year, month, day - days)
let weekEnd = getMyTime(year, month, day + 7 - days)
passedDays = getPassedDays(now - weekStart)
percent = getPercent((now - weekStart)/(weekEnd - weekStart))
return {time: weekDay, percent, detail: passedDays}
break
case 'day':
let dayStart = getMyTime(year, month, day)
let dayEnd = getMyTime(year, month, day + 1)
passedHours = Math.floor((now - dayStart)/3600000)
percent = getPercent((now - dayStart)/(dayEnd - dayStart))
return {time: day, percent, detail: passedHours}
break
case 'life':
let age = year - date1.getFullYear()
let midDate = new Date(date1.getTime())
let curYear = new Date(midDate.setFullYear(midDate.getFullYear() + age))
age = curYear > date ? age-1 : age
let lifeStart = date1.getTime()
let lifeEnd = date2.getTime()
passedDays = getPassedDays(now - lifeStart)
percent = getPercent((now - lifeStart)/(lifeEnd - lifeStart))
return {time: age, percent, detail: passedDays}
break
}
}
// 时间转天数
/* Example usages of 'getPassedDays' are shown below:
passedDays = getPassedDays(now - yearStart);
passedDays = getPassedDays(now - monthStart);
passedDays = getPassedDays(now - weekStart);
passedDays = getPassedDays(now - lifeStart);
*/
const getPassedDays = (time) => {
return Math.floor(time/86400000)
}
// 计算本周过去的天数
/* Example usages of 'getDays' are shown below:
getDays(wStart, weekDay);
*/
const getDays = (wStart, weekDay) => {
let days = weekDay
if (wStart) {
if (weekDay) {
days -= 1
} else {
days += 6
}
}
return days
}
// 获取日期毫秒值
/* Example usages of 'getMyTime' are shown below:
getMyTime(year, 0, 1);
getMyTime(year + 1, 0, 1);
getMyTime(year, month, 1);
getMyTime(year, month + 1, 1);
getMyTime(year, month, day - days);
getMyTime(year, month, day + 7 - days);
getMyTime(year, month, day);
getMyTime(year, month, day + 1);
*/
const getMyTime = (year, month, day) => {
return new Date(year, month, day).getTime()
}
// 获取百分比
/* Example usages of 'getPercent' are shown below:
percent = getPercent((now - yearStart) / (yearEnd - yearStart));
percent = getPercent((now - monthStart) / (monthEnd - monthStart));
percent = getPercent((now - weekStart) / (weekEnd - weekStart));
percent = getPercent((now - dayStart) / (dayEnd - dayStart));
percent = getPercent((now - lifeStart) / (lifeEnd - lifeStart));
*/
const getPercent = (percent) => {
return Math.floor(percent * 1000) / 10
}
export default { timePercent }
|
9e479c45edc43672ee82b8012cf92eac5468ba90 | 2,571 | ts | TypeScript | app/src/lib/helpers/regex.ts | vraomoturi/desktop | 4b75820c94b5379992124d38c07cc0923d1a601f | [
"MIT"
] | 1 | 2022-03-28T10:17:10.000Z | 2022-03-28T10:17:10.000Z | app/src/lib/helpers/regex.ts | vraomoturi/desktop | 4b75820c94b5379992124d38c07cc0923d1a601f | [
"MIT"
] | 6 | 2022-01-19T15:34:17.000Z | 2022-03-30T14:34:09.000Z | app/src/lib/helpers/regex.ts | vraomoturi/desktop | 4b75820c94b5379992124d38c07cc0923d1a601f | [
"MIT"
] | null | null | null | /**
* Get all regex captures within a body of text
*
* @param text string to search
* @param re regex to search with. must have global option and one capture
*
* @returns arrays of strings captured by supplied regex
*/
export function getCaptures(
text: string,
re: RegExp
): ReadonlyArray<Array<string>> {
const matches = getMatches(text, re)
const captures = matches.reduce(
(acc, match) => acc.concat([match.slice(1)]),
new Array<Array<string>>()
)
return captures
}
/**
* Get all regex matches within a body of text
*
* @param text string to search
* @param re regex to search with. must have global option
* @returns set of strings captured by supplied regex
*/
export function getMatches(text: string, re: RegExp): Array<RegExpExecArray> {
if (re.global === false) {
throw new Error(
'A regex has been provided that is not marked as global, and has the potential to execute forever if it finds a match'
)
}
const matches = new Array<RegExpExecArray>()
let match = re.exec(text)
while (match !== null) {
matches.push(match)
match = re.exec(text)
}
return matches
}
/*
* Looks for the phrases "remote: error File " and " is (file size I.E. 106.5 MB); this exceeds GitHub's file size limit of 100.00 MB"
* inside of a string containing errors and return an array of all the filenames and their sizes located between these two strings.
*
* example return [ "LargeFile.exe (150.00 MB)", "AlsoTooLargeOfAFile.txt (1.00 GB)" ]
*/
export function getFileFromExceedsError(error: string): string[] {
const endRegex =
/(;\sthis\sexceeds\sGitHub's\sfile\ssize\slimit\sof\s100.00\sMB)/gm
const beginRegex = /(^remote:\serror:\sFile\s)/gm
const beginMatches = Array.from(error.matchAll(beginRegex))
const endMatches = Array.from(error.matchAll(endRegex))
// Something went wrong and we didn't find the same amount of endings as we did beginnings
// Just return an empty array as the output we'd give would look weird anyway
if (beginMatches.length !== endMatches.length) {
return []
}
const files: string[] = []
for (let index = 0; index < beginMatches.length; index++) {
const beginMatch = beginMatches[index]
const endMatch = endMatches[index]
if (beginMatch.index === undefined || endMatch.index === undefined) {
continue
}
const from = beginMatch.index + beginMatch[0].length
const to = endMatch.index
let file = error.slice(from, to)
file = file.replace('is ', '(')
file += ')'
files.push(file)
}
return files
}
| 30.607143 | 134 | 0.684947 | 50 | 4 | 0 | 7 | 15 | 0 | 1 | 0 | 7 | 0 | 0 | 10.5 | 719 | 0.015299 | 0.020862 | 0 | 0 | 0 | 0 | 0.269231 | 0.273924 | /**
* Get all regex captures within a body of text
*
* @param text string to search
* @param re regex to search with. must have global option and one capture
*
* @returns arrays of strings captured by supplied regex
*/
export function getCaptures(
text,
re
) {
const matches = getMatches(text, re)
const captures = matches.reduce(
(acc, match) => acc.concat([match.slice(1)]),
new Array<Array<string>>()
)
return captures
}
/**
* Get all regex matches within a body of text
*
* @param text string to search
* @param re regex to search with. must have global option
* @returns set of strings captured by supplied regex
*/
export /* Example usages of 'getMatches' are shown below:
getMatches(text, re);
*/
function getMatches(text, re) {
if (re.global === false) {
throw new Error(
'A regex has been provided that is not marked as global, and has the potential to execute forever if it finds a match'
)
}
const matches = new Array<RegExpExecArray>()
let match = re.exec(text)
while (match !== null) {
matches.push(match)
match = re.exec(text)
}
return matches
}
/*
* Looks for the phrases "remote: error File " and " is (file size I.E. 106.5 MB); this exceeds GitHub's file size limit of 100.00 MB"
* inside of a string containing errors and return an array of all the filenames and their sizes located between these two strings.
*
* example return [ "LargeFile.exe (150.00 MB)", "AlsoTooLargeOfAFile.txt (1.00 GB)" ]
*/
export function getFileFromExceedsError(error) {
const endRegex =
/(;\sthis\sexceeds\sGitHub's\sfile\ssize\slimit\sof\s100.00\sMB)/gm
const beginRegex = /(^remote:\serror:\sFile\s)/gm
const beginMatches = Array.from(error.matchAll(beginRegex))
const endMatches = Array.from(error.matchAll(endRegex))
// Something went wrong and we didn't find the same amount of endings as we did beginnings
// Just return an empty array as the output we'd give would look weird anyway
if (beginMatches.length !== endMatches.length) {
return []
}
const files = []
for (let index = 0; index < beginMatches.length; index++) {
const beginMatch = beginMatches[index]
const endMatch = endMatches[index]
if (beginMatch.index === undefined || endMatch.index === undefined) {
continue
}
const from = beginMatch.index + beginMatch[0].length
const to = endMatch.index
let file = error.slice(from, to)
file = file.replace('is ', '(')
file += ')'
files.push(file)
}
return files
}
|
9e783ab4a5642f948e38208000981ecee6604842 | 2,601 | ts | TypeScript | src/utils/typeValidate.ts | ChrisLee0211/p-trend | 0c84cf3b5e7b8d3b91aef79472e88359b9a4e8e2 | [
"MIT"
] | 6 | 2022-01-09T00:16:14.000Z | 2022-02-14T01:41:13.000Z | src/utils/typeValidate.ts | ChrisLee0211/p-trend | 0c84cf3b5e7b8d3b91aef79472e88359b9a4e8e2 | [
"MIT"
] | null | null | null | src/utils/typeValidate.ts | ChrisLee0211/p-trend | 0c84cf3b5e7b8d3b91aef79472e88359b9a4e8e2 | [
"MIT"
] | 1 | 2022-01-11T07:39:18.000Z | 2022-01-11T07:39:18.000Z | const typeEnum = {
"string":"[object String]",
"number":"[object Number]",
"boolean":"[object Boolean]",
"undefined":"[object Undefined]",
"null":"[object Null]",
"object":"[object Object]",
"function":"[object Function]",
"array":"[object Array]",
"date":"[object Date]",
"reg":"[object RegExp]"
};
/**
* Verify that a value is an object
* @param {any} obj
* @returns {boolean}
* @author chrislee
* @Time 2020/7/12
*/
export const isObject:(obj:unknown)=>boolean = (obj) =>{
let res = true;
if(Object.prototype.toString.call(obj) === "[object Object]"){
res = true;
}else{
res = false;
}
return res;
};
/**
* Verify that a value is undefined
* @param {any} obj
* @returns {boolean}
* @author chrislee
* @Time 2020/7/12
*/
export const isUndefined:(obj:unknown)=>boolean = (obj) => {
let res: boolean;
if(obj === undefined||Object.prototype.toString.call(obj)===typeEnum["undefined"]){
res = true;
}else{
res = false;
}
return res;
};
/**
* Verify that a value is an array
* @param {any} obj
* @returns {boolean}
* @author chrislee
* @Time 2020/7/12
*/
export const isArray:(obj:unknown)=>boolean = (obj) =>{
let res:boolean;
if(obj instanceof Array || Object.prototype.toString.call(obj)===typeEnum["array"]){
res = true;
}else{
res = false;
}
return res;
};
/**
* Verify that a value is an boolean
* @param {any} obj
* @returns {boolean}
* @author chrislee
* @Time 2020/7/12
*/
export const isBoolean:(obj:unknown) => boolean = (obj) => {
let res:boolean;
if( Object.prototype.toString.call(obj)===typeEnum["boolean"]){
res = true;
}else{
res = false;
}
return res;
};
export const typeValidate:(obj:unknown, type:keyof typeof typeEnum, constant?:string)=>boolean = (obj, type, constant="The value of target") =>{
let res:boolean;
if(Object.prototype.toString.call(obj)=== typeEnum[type]){
res = true;
}else{
let currentType = "undefined";
for(const key in typeEnum){
if(typeEnum[key as keyof typeof typeEnum] === Object.prototype.toString.call(obj)){
currentType = key;
}
}
throw TypeError(`${constant} expect a ${type},but got ${currentType}`);
}
return res;
};
/**
* get variable type
* @param {any} obj
* @returns {string}
* @author chrislee
* @Time 2020/9/28
*/
export const getVariableType:(obj:any)=> string= (obj)=>{
return Object.prototype.toString.call(obj);
};
| 23.862385 | 144 | 0.588235 | 66 | 6 | 0 | 8 | 13 | 0 | 0 | 1 | 16 | 0 | 2 | 7 | 777 | 0.018018 | 0.016731 | 0 | 0 | 0.002574 | 0.037037 | 0.592593 | 0.265124 | const typeEnum = {
"string":"[object String]",
"number":"[object Number]",
"boolean":"[object Boolean]",
"undefined":"[object Undefined]",
"null":"[object Null]",
"object":"[object Object]",
"function":"[object Function]",
"array":"[object Array]",
"date":"[object Date]",
"reg":"[object RegExp]"
};
/**
* Verify that a value is an object
* @param {any} obj
* @returns {boolean}
* @author chrislee
* @Time 2020/7/12
*/
export const isObject = (obj) =>{
let res = true;
if(Object.prototype.toString.call(obj) === "[object Object]"){
res = true;
}else{
res = false;
}
return res;
};
/**
* Verify that a value is undefined
* @param {any} obj
* @returns {boolean}
* @author chrislee
* @Time 2020/7/12
*/
export const isUndefined = (obj) => {
let res;
if(obj === undefined||Object.prototype.toString.call(obj)===typeEnum["undefined"]){
res = true;
}else{
res = false;
}
return res;
};
/**
* Verify that a value is an array
* @param {any} obj
* @returns {boolean}
* @author chrislee
* @Time 2020/7/12
*/
export const isArray = (obj) =>{
let res;
if(obj instanceof Array || Object.prototype.toString.call(obj)===typeEnum["array"]){
res = true;
}else{
res = false;
}
return res;
};
/**
* Verify that a value is an boolean
* @param {any} obj
* @returns {boolean}
* @author chrislee
* @Time 2020/7/12
*/
export const isBoolean = (obj) => {
let res;
if( Object.prototype.toString.call(obj)===typeEnum["boolean"]){
res = true;
}else{
res = false;
}
return res;
};
export const typeValidate = (obj, type, constant="The value of target") =>{
let res;
if(Object.prototype.toString.call(obj)=== typeEnum[type]){
res = true;
}else{
let currentType = "undefined";
for(const key in typeEnum){
if(typeEnum[key as keyof typeof typeEnum] === Object.prototype.toString.call(obj)){
currentType = key;
}
}
throw TypeError(`${constant} expect a ${type},but got ${currentType}`);
}
return res;
};
/**
* get variable type
* @param {any} obj
* @returns {string}
* @author chrislee
* @Time 2020/9/28
*/
export const getVariableType= (obj)=>{
return Object.prototype.toString.call(obj);
};
|
9e9c118238962afa94fa08ff3f99466bbd1b84bf | 2,353 | ts | TypeScript | src/lib/loopback-sdk/models/Person.ts | labibramadhan/cbt-crossword-mobile | ef149c961540e6de3bd39339294d7c44e8068c84 | [
"BSD-2-Clause"
] | null | null | null | src/lib/loopback-sdk/models/Person.ts | labibramadhan/cbt-crossword-mobile | ef149c961540e6de3bd39339294d7c44e8068c84 | [
"BSD-2-Clause"
] | null | null | null | src/lib/loopback-sdk/models/Person.ts | labibramadhan/cbt-crossword-mobile | ef149c961540e6de3bd39339294d7c44e8068c84 | [
"BSD-2-Clause"
] | 1 | 2022-03-05T17:19:19.000Z | 2022-03-05T17:19:19.000Z | /* tslint:disable */
declare var Object: any;
export interface PersonInterface {
id?: string;
name: string;
realm?: string;
username?: string;
password: string;
email: string;
emailVerified?: boolean;
verificationToken?: string;
created_at: Date;
updated_at: Date;
accessTokens?: Array<any>;
}
export class Person implements PersonInterface {
id: string;
name: string;
realm: string;
username: string;
password: string;
email: string;
emailVerified: boolean;
verificationToken: string;
created_at: Date;
updated_at: Date;
accessTokens: Array<any>;
constructor(data?: PersonInterface) {
Object.assign(this, data);
}
/**
* The name of the model represented by this $resource,
* i.e. `Person`.
*/
public static getModelName() {
return "Person";
}
/**
* @method factory
* @author Jonathan Casarrubias
* @license MIT
* This method creates an instance of Person for dynamic purposes.
**/
public static factory(data: PersonInterface): Person{
return new Person(data);
}
/**
* @method getModelDefinition
* @author Julien Ledun
* @license MIT
* This method returns an object that represents some of the model
* definitions.
**/
public static getModelDefinition() {
return {
name: 'Person',
plural: 'Persons',
properties: {
id: {
name: 'id',
type: 'string'
},
name: {
name: 'name',
type: 'string'
},
realm: {
name: 'realm',
type: 'string'
},
username: {
name: 'username',
type: 'string'
},
password: {
name: 'password',
type: 'string'
},
email: {
name: 'email',
type: 'string'
},
emailVerified: {
name: 'emailVerified',
type: 'boolean'
},
verificationToken: {
name: 'verificationToken',
type: 'string'
},
created_at: {
name: 'created_at',
type: 'Date'
},
updated_at: {
name: 'updated_at',
type: 'Date'
},
},
relations: {
accessTokens: {
name: 'accessTokens',
type: 'Array<any>',
model: ''
},
}
}
}
}
| 21.008929 | 67 | 0.535912 | 91 | 4 | 0 | 2 | 1 | 22 | 0 | 3 | 16 | 2 | 0 | 14 | 577 | 0.010399 | 0.001733 | 0.038128 | 0.003466 | 0 | 0.103448 | 0.551724 | 0.203285 | /* tslint:disable */
declare var Object;
export interface PersonInterface {
id?;
name;
realm?;
username?;
password;
email;
emailVerified?;
verificationToken?;
created_at;
updated_at;
accessTokens?;
}
export class Person implements PersonInterface {
id;
name;
realm;
username;
password;
email;
emailVerified;
verificationToken;
created_at;
updated_at;
accessTokens;
constructor(data?) {
Object.assign(this, data);
}
/**
* The name of the model represented by this $resource,
* i.e. `Person`.
*/
public static getModelName() {
return "Person";
}
/**
* @method factory
* @author Jonathan Casarrubias
* @license MIT
* This method creates an instance of Person for dynamic purposes.
**/
public static factory(data){
return new Person(data);
}
/**
* @method getModelDefinition
* @author Julien Ledun
* @license MIT
* This method returns an object that represents some of the model
* definitions.
**/
public static getModelDefinition() {
return {
name: 'Person',
plural: 'Persons',
properties: {
id: {
name: 'id',
type: 'string'
},
name: {
name: 'name',
type: 'string'
},
realm: {
name: 'realm',
type: 'string'
},
username: {
name: 'username',
type: 'string'
},
password: {
name: 'password',
type: 'string'
},
email: {
name: 'email',
type: 'string'
},
emailVerified: {
name: 'emailVerified',
type: 'boolean'
},
verificationToken: {
name: 'verificationToken',
type: 'string'
},
created_at: {
name: 'created_at',
type: 'Date'
},
updated_at: {
name: 'updated_at',
type: 'Date'
},
},
relations: {
accessTokens: {
name: 'accessTokens',
type: 'Array<any>',
model: ''
},
}
}
}
}
|
3a22247bd2cbe63df87534ab2a388694b494a270 | 1,825 | ts | TypeScript | problemset/find-the-duplicate-number/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | problemset/find-the-duplicate-number/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | problemset/find-the-duplicate-number/index.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | /**
* 暴力解法
* @desc 时间复杂度 O(N²) 空间复杂度 O(1)
* @param nums
* @returns
*/
export function findDuplicate(nums: number[]): number {
const len = nums.length
for (let i = 0; i < len - 1; i++) {
for (let j = i + 1; j < len; j++)
if (nums[i] === nums[j]) return nums[i]
}
return -1
}
/**
* 二分查找
* @desc 时间复杂度 O(NlogN) 空间复杂度 O(1)
* @param nums
* @returns
*/
export function findDuplicate2(nums: number[]): number {
const len = nums.length
let left = 1
let right = len - 1
let ans = -1
while (left <= right) {
const mid = (left + right) >> 1
let count = 0
// 记录小于 mid 的个数
for (let i = 0; i < len; i++)
nums[i] <= mid && count++
if (count <= mid) {
left = mid + 1
}
else {
right = mid - 1
ans = mid
}
}
return ans
}
/**
* 二进制
* @desc 时间复杂度 O(NlogN) 空间复杂度 O(1)
* @param nums
* @returns
*/
export function findDuplicate3(nums: number[]): number {
const len = nums.length
let ans = 0
// 确定二进制下的最高位
let maxBit = 31
while (!((len - 1) >> maxBit))
maxBit -= 1
// 对每一位进行比较
for (let bit = 0; bit <= maxBit; ++bit) {
let x = 0
let y = 0
for (let i = 0; i < len; ++i) {
// 统计数值该位为 1 的数量
if (nums[i] & (1 << bit)) x += 1
// 统计下标该位为 1 的数量
if (i & (1 << bit)) y += 1
}
if (x > y) ans |= 1 << bit
}
return ans
}
/**
* 快慢指针
* @desc 时间复杂度 O(N) 空间复杂度 O(1)
* @param nums
* @returns
*/
export function findDuplicate4(nums: number[]): number {
let slow = 0
let fast = 0
// 2(slow + fast) = slow + fast = kL
// slow = kL - fast
do {
slow = nums[slow]
fast = nums[nums[fast]]
} while (slow !== fast)
slow = 0
// slow = (k - 1)L + (L - fast) = (k - 1)L + C
while (slow !== fast) {
slow = nums[slow]
fast = nums[fast]
}
return slow
}
| 17.548077 | 56 | 0.50411 | 59 | 4 | 0 | 4 | 19 | 0 | 0 | 0 | 8 | 0 | 0 | 12.75 | 739 | 0.010825 | 0.02571 | 0 | 0 | 0 | 0 | 0.296296 | 0.279016 | /**
* 暴力解法
* @desc 时间复杂度 O(N²) 空间复杂度 O(1)
* @param nums
* @returns
*/
export function findDuplicate(nums) {
const len = nums.length
for (let i = 0; i < len - 1; i++) {
for (let j = i + 1; j < len; j++)
if (nums[i] === nums[j]) return nums[i]
}
return -1
}
/**
* 二分查找
* @desc 时间复杂度 O(NlogN) 空间复杂度 O(1)
* @param nums
* @returns
*/
export function findDuplicate2(nums) {
const len = nums.length
let left = 1
let right = len - 1
let ans = -1
while (left <= right) {
const mid = (left + right) >> 1
let count = 0
// 记录小于 mid 的个数
for (let i = 0; i < len; i++)
nums[i] <= mid && count++
if (count <= mid) {
left = mid + 1
}
else {
right = mid - 1
ans = mid
}
}
return ans
}
/**
* 二进制
* @desc 时间复杂度 O(NlogN) 空间复杂度 O(1)
* @param nums
* @returns
*/
export function findDuplicate3(nums) {
const len = nums.length
let ans = 0
// 确定二进制下的最高位
let maxBit = 31
while (!((len - 1) >> maxBit))
maxBit -= 1
// 对每一位进行比较
for (let bit = 0; bit <= maxBit; ++bit) {
let x = 0
let y = 0
for (let i = 0; i < len; ++i) {
// 统计数值该位为 1 的数量
if (nums[i] & (1 << bit)) x += 1
// 统计下标该位为 1 的数量
if (i & (1 << bit)) y += 1
}
if (x > y) ans |= 1 << bit
}
return ans
}
/**
* 快慢指针
* @desc 时间复杂度 O(N) 空间复杂度 O(1)
* @param nums
* @returns
*/
export function findDuplicate4(nums) {
let slow = 0
let fast = 0
// 2(slow + fast) = slow + fast = kL
// slow = kL - fast
do {
slow = nums[slow]
fast = nums[nums[fast]]
} while (slow !== fast)
slow = 0
// slow = (k - 1)L + (L - fast) = (k - 1)L + C
while (slow !== fast) {
slow = nums[slow]
fast = nums[fast]
}
return slow
}
|
3a9f64a648178ce1185268926544558880f67023 | 1,949 | ts | TypeScript | src/js/Input/utils.ts | edwardfxiao/react-codes-input | 3297520e79186aae7e60972797f6b385969a8c78 | [
"MIT"
] | 11 | 2022-03-01T03:28:19.000Z | 2022-03-10T02:58:13.000Z | src/js/Input/utils.ts | edwardfxiao/react-codes-input | 3297520e79186aae7e60972797f6b385969a8c78 | [
"MIT"
] | 9 | 2022-02-09T06:18:29.000Z | 2022-03-07T03:44:02.000Z | src/js/Input/utils.ts | edwardfxiao/react-codes-input | 3297520e79186aae7e60972797f6b385969a8c78 | [
"MIT"
] | 1 | 2022-02-22T13:00:34.000Z | 2022-02-22T13:00:34.000Z | export enum CASE_TYPES {
UPPERCASE = 'upper',
LOWERCASE = 'lower',
}
export const cx = (...params: Array<any>) => {
const classes = [];
for (let i = 0; i < params.length; i += 1) {
const arg = params[i];
if (!arg) continue;
const argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg) && arg.length) {
const inner: string = cx.apply(null, arg);
if (inner) {
classes.push(inner);
}
} else if (argType === 'object') {
for (const key in arg) {
if ({}.hasOwnProperty.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
};
export const getRandomId = () => {
return Math.random().toString(36).slice(-8);
};
export const getAlphanumeric = (v: string) => {
let res = '';
String(v)
.split('')
.forEach(i => {
const charCode = i.toLowerCase().charCodeAt(0);
if ((charCode >= 48 && charCode <= 57) || (charCode >= 97 && charCode <= 122)) {
res += i;
}
});
return res;
};
export const getAlpha = (v: string) => {
let res = '';
String(v)
.split('')
.forEach(i => {
const charCode = i.toLowerCase().charCodeAt(0);
if (charCode >= 97 && charCode <= 122) {
res += i;
}
});
return res;
};
export const getNumeric = (v: string) => {
let res = '';
v.split('').forEach(i => {
const charCode = i.toLowerCase().charCodeAt(0);
if (charCode >= 48 && charCode <= 57) {
res += i;
}
});
return res;
};
export const getCased = (v: string, type: string) => {
if (type) {
switch (type) {
case CASE_TYPES.UPPERCASE:
return v.toUpperCase();
case CASE_TYPES.LOWERCASE:
return v.toLowerCase();
}
} else {
return v.toUpperCase();
}
};
export const getClassName = (className: string) => `RCI-${className}`;
| 22.929412 | 86 | 0.531555 | 77 | 10 | 0 | 10 | 18 | 0 | 0 | 1 | 7 | 0 | 1 | 7.3 | 597 | 0.033501 | 0.030151 | 0 | 0 | 0.001675 | 0.026316 | 0.184211 | 0.346057 | export enum CASE_TYPES {
UPPERCASE = 'upper',
LOWERCASE = 'lower',
}
export /* Example usages of 'cx' are shown below:
cx.apply(null, arg);
*/
const cx = (...params) => {
const classes = [];
for (let i = 0; i < params.length; i += 1) {
const arg = params[i];
if (!arg) continue;
const argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg) && arg.length) {
const inner = cx.apply(null, arg);
if (inner) {
classes.push(inner);
}
} else if (argType === 'object') {
for (const key in arg) {
if ({}.hasOwnProperty.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
};
export const getRandomId = () => {
return Math.random().toString(36).slice(-8);
};
export const getAlphanumeric = (v) => {
let res = '';
String(v)
.split('')
.forEach(i => {
const charCode = i.toLowerCase().charCodeAt(0);
if ((charCode >= 48 && charCode <= 57) || (charCode >= 97 && charCode <= 122)) {
res += i;
}
});
return res;
};
export const getAlpha = (v) => {
let res = '';
String(v)
.split('')
.forEach(i => {
const charCode = i.toLowerCase().charCodeAt(0);
if (charCode >= 97 && charCode <= 122) {
res += i;
}
});
return res;
};
export const getNumeric = (v) => {
let res = '';
v.split('').forEach(i => {
const charCode = i.toLowerCase().charCodeAt(0);
if (charCode >= 48 && charCode <= 57) {
res += i;
}
});
return res;
};
export const getCased = (v, type) => {
if (type) {
switch (type) {
case CASE_TYPES.UPPERCASE:
return v.toUpperCase();
case CASE_TYPES.LOWERCASE:
return v.toLowerCase();
}
} else {
return v.toUpperCase();
}
};
export const getClassName = (className) => `RCI-${className}`;
|
ad15d5503f15235dd06d2738702575eb4dfe04e9 | 1,910 | ts | TypeScript | src/lib/ttt.ts | znordrol/gute-nacht-controller | bea5a4f710eb371c21eccb4911d456bcfa71d36f | [
"MIT"
] | null | null | null | src/lib/ttt.ts | znordrol/gute-nacht-controller | bea5a4f710eb371c21eccb4911d456bcfa71d36f | [
"MIT"
] | 66 | 2022-03-14T21:36:24.000Z | 2022-03-31T21:42:29.000Z | src/lib/ttt.ts | znordrol/gute-nacht-controller | bea5a4f710eb371c21eccb4911d456bcfa71d36f | [
"MIT"
] | null | null | null | export type XO = 'X' | 'O' | '';
export type Board = [[XO, XO, XO], [XO, XO, XO], [XO, XO, XO]];
export type Coordinate = {
x: number;
y: number;
};
export type TTT = {
board: Board;
lastPlay?: XO;
winner?: XO;
draw?: boolean;
};
export const isBoardFull = (x: Board) => x.every((y) => y.every((z) => z));
export const newBoard = (): Board =>
[...Array(3)].map(() => Array(3).fill('')) as Board;
export const newTtt = (): TTT => ({
board: newBoard(),
});
export const getWinner = (x: Board) => {
const winners = new Set<XO>();
for (let i = 0; i < 3; ++i) {
if (x[0][i] && new Set([x[0][i], x[1][i], x[2][i]]).size === 1) {
winners.add(x[0][i]);
}
}
for (let i = 0; i < 3; ++i) {
if (x[i][0] && new Set(x[i]).size === 1) {
winners.add(x[i][0]);
}
}
if (
x[1][1] &&
(new Set([x[0][0], x[1][1], x[2][2]]).size === 1 ||
new Set([x[0][2], x[1][1], x[2][0]]).size === 1)
) {
winners.add(x[1][1]);
}
if (!winners.size) {
// completion check
return isBoardFull(x) ? 'DRAW' : 'INCOMPLETE';
}
return winners.values().next().value as Exclude<XO, undefined>;
};
export const insertPlay = (x: TTT, c: [number, number]) => {
if (x.board[c[0]][c[1]] || c[0] > 2 || c[1] > 2) return x;
const winner = getWinner(x.board);
if (['X', 'O', 'DRAW'].includes(winner.toUpperCase())) {
if (winner === 'DRAW') {
x.draw = true;
return x;
} else if (winner !== 'INCOMPLETE') {
x.winner = winner;
return x;
}
}
x.lastPlay = x.lastPlay === 'X' ? 'O' : 'X';
x.board[c[0]][c[1]] = x.lastPlay;
const postWinner = getWinner(x.board);
if (['X', 'O', 'DRAW'].includes(postWinner.toUpperCase())) {
if (postWinner === 'DRAW') {
x.draw = true;
return x;
} else if (postWinner !== 'INCOMPLETE') {
x.winner = postWinner;
return x;
}
}
return x;
};
| 21.704545 | 75 | 0.497382 | 68 | 8 | 0 | 6 | 10 | 6 | 3 | 0 | 5 | 4 | 2 | 6.75 | 732 | 0.019126 | 0.013661 | 0.008197 | 0.005464 | 0.002732 | 0 | 0.166667 | 0.268382 | export type XO = 'X' | 'O' | '';
export type Board = [[XO, XO, XO], [XO, XO, XO], [XO, XO, XO]];
export type Coordinate = {
x;
y;
};
export type TTT = {
board;
lastPlay?;
winner?;
draw?;
};
export /* Example usages of 'isBoardFull' are shown below:
isBoardFull(x) ? 'DRAW' : 'INCOMPLETE';
*/
const isBoardFull = (x) => x.every((y) => y.every((z) => z));
export /* Example usages of 'newBoard' are shown below:
newBoard();
*/
const newBoard = () =>
[...Array(3)].map(() => Array(3).fill('')) as Board;
export const newTtt = () => ({
board: newBoard(),
});
export /* Example usages of 'getWinner' are shown below:
getWinner(x.board);
*/
const getWinner = (x) => {
const winners = new Set<XO>();
for (let i = 0; i < 3; ++i) {
if (x[0][i] && new Set([x[0][i], x[1][i], x[2][i]]).size === 1) {
winners.add(x[0][i]);
}
}
for (let i = 0; i < 3; ++i) {
if (x[i][0] && new Set(x[i]).size === 1) {
winners.add(x[i][0]);
}
}
if (
x[1][1] &&
(new Set([x[0][0], x[1][1], x[2][2]]).size === 1 ||
new Set([x[0][2], x[1][1], x[2][0]]).size === 1)
) {
winners.add(x[1][1]);
}
if (!winners.size) {
// completion check
return isBoardFull(x) ? 'DRAW' : 'INCOMPLETE';
}
return winners.values().next().value as Exclude<XO, undefined>;
};
export const insertPlay = (x, c) => {
if (x.board[c[0]][c[1]] || c[0] > 2 || c[1] > 2) return x;
const winner = getWinner(x.board);
if (['X', 'O', 'DRAW'].includes(winner.toUpperCase())) {
if (winner === 'DRAW') {
x.draw = true;
return x;
} else if (winner !== 'INCOMPLETE') {
x.winner = winner;
return x;
}
}
x.lastPlay = x.lastPlay === 'X' ? 'O' : 'X';
x.board[c[0]][c[1]] = x.lastPlay;
const postWinner = getWinner(x.board);
if (['X', 'O', 'DRAW'].includes(postWinner.toUpperCase())) {
if (postWinner === 'DRAW') {
x.draw = true;
return x;
} else if (postWinner !== 'INCOMPLETE') {
x.winner = postWinner;
return x;
}
}
return x;
};
|
ad2d9ffb8c6b059be3895be81bedb5cd53277166 | 1,433 | ts | TypeScript | src/string-with-indices.ts | melusc/truth-table | ecabd5d97d2108a78f13f0bb64813b638bd65578 | [
"MIT"
] | null | null | null | src/string-with-indices.ts | melusc/truth-table | ecabd5d97d2108a78f13f0bb64813b638bd65578 | [
"MIT"
] | 1 | 2022-03-25T09:20:22.000Z | 2022-03-25T09:20:22.000Z | src/string-with-indices.ts | melusc/truth-table | ecabd5d97d2108a78f13f0bb64813b638bd65578 | [
"MIT"
] | null | null | null | export type StringWithIndices = {
characters: string;
type: CharacterTypes;
originalCharacters: string;
from: number;
to: number;
};
const VARIABLES_RE = /^[a-z_]+$/i;
const BRACKETS_RE = /^[()]+$/;
const SPACE_RE = /^\s+$/;
export const enum CharacterTypes {
variable = 'variable',
operator = 'operator',
space = 'space',
bracket = 'bracket',
}
export const fromString = (input: string): StringWithIndices[] => {
input = input.normalize('NFKC');
const split = input.split(/([a-z_]+|[()]+|\s+)/i);
let index = 0;
const result: StringWithIndices[] = [];
for (const characters of split) {
if (characters === '') {
continue;
}
let type: CharacterTypes;
if (VARIABLES_RE.test(characters)) {
type = CharacterTypes.variable;
} else if (BRACKETS_RE.test(characters)) {
type = CharacterTypes.bracket;
} else if (SPACE_RE.test(characters)) {
type = CharacterTypes.space;
} else {
type = CharacterTypes.operator;
}
result.push({
characters: characters.toUpperCase(),
type,
originalCharacters: characters,
from: index,
to: index + characters.length,
});
index += characters.length;
}
return result;
};
export const removeWhitespace = (
input: readonly StringWithIndices[],
): StringWithIndices[] => {
const result: StringWithIndices[] = [];
for (const item of input) {
if (item.type !== CharacterTypes.space) {
result.push(item);
}
}
return result;
};
| 20.471429 | 67 | 0.658758 | 57 | 2 | 0 | 2 | 10 | 5 | 0 | 0 | 5 | 1 | 0 | 17.5 | 454 | 0.008811 | 0.022026 | 0.011013 | 0.002203 | 0 | 0 | 0.263158 | 0.26588 | export type StringWithIndices = {
characters;
type;
originalCharacters;
from;
to;
};
const VARIABLES_RE = /^[a-z_]+$/i;
const BRACKETS_RE = /^[()]+$/;
const SPACE_RE = /^\s+$/;
export const enum CharacterTypes {
variable = 'variable',
operator = 'operator',
space = 'space',
bracket = 'bracket',
}
export const fromString = (input) => {
input = input.normalize('NFKC');
const split = input.split(/([a-z_]+|[()]+|\s+)/i);
let index = 0;
const result = [];
for (const characters of split) {
if (characters === '') {
continue;
}
let type;
if (VARIABLES_RE.test(characters)) {
type = CharacterTypes.variable;
} else if (BRACKETS_RE.test(characters)) {
type = CharacterTypes.bracket;
} else if (SPACE_RE.test(characters)) {
type = CharacterTypes.space;
} else {
type = CharacterTypes.operator;
}
result.push({
characters: characters.toUpperCase(),
type,
originalCharacters: characters,
from: index,
to: index + characters.length,
});
index += characters.length;
}
return result;
};
export const removeWhitespace = (
input,
) => {
const result = [];
for (const item of input) {
if (item.type !== CharacterTypes.space) {
result.push(item);
}
}
return result;
};
|
ad552ae0add3b636dfec300928d287d7d8d77b49 | 1,987 | ts | TypeScript | utils/listNode.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | 6 | 2022-01-17T03:19:56.000Z | 2022-01-17T05:45:39.000Z | utils/listNode.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | utils/listNode.ts | OUDUIDUI/leet-code | 50e61ce16d1c419ccefc075ae9ead721cdd1cdbb | [
"MIT"
] | null | null | null | // Definition for singly-linked list.
export class ListNode {
val: number
next: ListNode | null
constructor(val?: number, next?: ListNode | null) {
this.val = val === undefined ? 0 : val
this.next = next === undefined ? null : next
}
}
export function createListNode(arr: Array<number>): ListNode | null {
return arr.reduceRight((prev: ListNode | null, cur: number) => {
if (prev)
return new ListNode(cur, prev)
else
return new ListNode(cur, null)
}, null)
}
export function createCycleListNode(
arr: Array<number>,
pos: number,
): ListNode | null {
const node = createListNode(arr)
if (node && pos !== -1) {
let prevNode: ListNode | null = null
let cur: ListNode | null = node
let i = 0
while (cur?.next) {
if (i === pos)
prevNode = cur
cur = cur.next
i++
}
cur.next = prevNode
}
return node
}
export function createIntersectionListNode(
intersectVal: number,
listA: number[],
listB: number[],
skipA: number,
skipB: number,
): [ListNode | null, ListNode | null, ListNode | null] {
if (
!listA.length
|| !listB.length
|| !listA.includes(intersectVal)
|| !listB.includes(intersectVal)
|| skipA >= listA.length
|| skipB >= listB.length
)
return [createListNode(listA), createListNode(listB), null]
const intersectionNode = new ListNode(listA[skipA])
let cur = intersectionNode
let i = skipA + 1
while (i < listA.length) {
cur.next = new ListNode(listA[i])
cur = cur.next
i++
}
const listNodeA = new ListNode(listA[0])
cur = listNodeA
i = 1
while (i < skipA) {
cur.next = new ListNode(listA[i])
cur = cur.next
i++
}
cur.next = intersectionNode
const listNodeB = new ListNode(listB[0])
cur = listNodeB
i = 1
while (i < skipB) {
cur.next = new ListNode(listB[i])
cur = cur.next
i++
}
cur.next = intersectionNode
return [listNodeA, listNodeB, intersectionNode]
}
| 20.915789 | 69 | 0.619527 | 79 | 5 | 0 | 12 | 9 | 2 | 1 | 0 | 11 | 1 | 0 | 12.4 | 591 | 0.028765 | 0.015228 | 0.003384 | 0.001692 | 0 | 0 | 0.392857 | 0.289617 | // Definition for singly-linked list.
export class ListNode {
val
next
constructor(val?, next?) {
this.val = val === undefined ? 0 : val
this.next = next === undefined ? null : next
}
}
export /* Example usages of 'createListNode' are shown below:
createListNode(arr);
createListNode(listA);
createListNode(listB);
*/
function createListNode(arr) {
return arr.reduceRight((prev, cur) => {
if (prev)
return new ListNode(cur, prev)
else
return new ListNode(cur, null)
}, null)
}
export function createCycleListNode(
arr,
pos,
) {
const node = createListNode(arr)
if (node && pos !== -1) {
let prevNode = null
let cur = node
let i = 0
while (cur?.next) {
if (i === pos)
prevNode = cur
cur = cur.next
i++
}
cur.next = prevNode
}
return node
}
export function createIntersectionListNode(
intersectVal,
listA,
listB,
skipA,
skipB,
) {
if (
!listA.length
|| !listB.length
|| !listA.includes(intersectVal)
|| !listB.includes(intersectVal)
|| skipA >= listA.length
|| skipB >= listB.length
)
return [createListNode(listA), createListNode(listB), null]
const intersectionNode = new ListNode(listA[skipA])
let cur = intersectionNode
let i = skipA + 1
while (i < listA.length) {
cur.next = new ListNode(listA[i])
cur = cur.next
i++
}
const listNodeA = new ListNode(listA[0])
cur = listNodeA
i = 1
while (i < skipA) {
cur.next = new ListNode(listA[i])
cur = cur.next
i++
}
cur.next = intersectionNode
const listNodeB = new ListNode(listB[0])
cur = listNodeB
i = 1
while (i < skipB) {
cur.next = new ListNode(listB[i])
cur = cur.next
i++
}
cur.next = intersectionNode
return [listNodeA, listNodeB, intersectionNode]
}
|