blob_id
large_stringlengths 40
40
| language
large_stringclasses 1
value | repo_name
large_stringlengths 5
119
| path
large_stringlengths 4
271
| score
float64 2.52
4.84
| int_score
int64 3
5
| text
stringlengths 26
4.09M
|
|---|---|---|---|---|---|---|
da0208264926dcade5279af992c0440cb0469065
|
TypeScript
|
jujunjun110/ts-test
|
/src/js/my_mod.ts
| 3.46875
| 3
|
export default class MyMod {
message(): string {
return 'hello'
}
extract_number(text: string): number | null {
const res = text.match(/\d{1}/g)
return res === null ? null : parseFloat(res.join(''))
}
fib(num: number): number {
function fib_inner(counter: number, p1: number, p2: number): number {
return counter === 0 ? p1 : fib_inner(counter - 1, p1 + p2, p1)
}
return fib_inner(num, 0, 1)
}
fib2(num: number): number {
if (num === 0 || num === 1) {
return num
}
const fibArray: Array<number> = [0, 1]
for (let i = 2; i <= num; i++) {
fibArray.push(fibArray[i - 1] + fibArray[i - 2])
}
return fibArray[num]
}
}
|
4bba5b28b0b5a76248a980b3705720935e24bf81
|
TypeScript
|
ycllz/renderer
|
/lib/filters/tasks/Filter3DHBlurTask.ts
| 2.578125
| 3
|
import Image2D = require("awayjs-core/lib/data/Image2D");
import Camera = require("awayjs-display/lib/entities/Camera");
import ContextGLProgramType = require("awayjs-stagegl/lib/base/ContextGLProgramType");
import Stage = require("awayjs-stagegl/lib/base/Stage");
import Filter3DTaskBase = require("awayjs-renderergl/lib/filters/tasks/Filter3DTaskBase");
class Filter3DHBlurTask extends Filter3DTaskBase
{
private static MAX_AUTO_SAMPLES:number = 15;
private _amount:number;
private _data:Float32Array;
private _stepSize:number = 1;
private _realStepSize:number;
/**
* Creates a new Filter3DHDepthOfFFieldTask
* @param amount The maximum amount of blur to apply in pixels at the most out-of-focus areas
* @param stepSize The distance between samples. Set to -1 to autodetect with acceptable quality.
*/
constructor(amount:number, stepSize:number = -1)
{
super();
this._amount = amount;
this._data = new Float32Array([0, 0, 0, 1]);
this.stepSize = stepSize;
}
public get amount():number
{
return this._amount;
}
public set amount(value:number)
{
if (this._amount == value)
return;
this._amount = value;
this.invalidateProgram();
this.updateBlurData();
this.calculateStepSize();
}
public get stepSize():number
{
return this._stepSize;
}
public set stepSize(value:number)
{
if (this._stepSize == value)
return;
this._stepSize = value;
this.calculateStepSize();
this.invalidateProgram();
this.updateBlurData();
}
public getFragmentCode():string
{
var code:string;
var numSamples:number = 1;
code = "mov ft0, v0 \n" +
"sub ft0.x, v0.x, fc0.x\n";
code += "tex ft1, ft0, fs0 <2d,linear,clamp>\n";
for (var x:number = this._realStepSize; x <= this._amount; x += this._realStepSize) {
code += "add ft0.x, ft0.x, fc0.y\n" +
"tex ft2, ft0, fs0 <2d,linear,clamp>\n" +
"add ft1, ft1, ft2\n";
++numSamples;
}
code += "mul oc, ft1, fc0.z\n";
this._data[2] = 1/numSamples;
return code;
}
public activate(stage:Stage, camera3D:Camera, depthTexture:Image2D)
{
stage.context.setProgramConstantsFromArray(ContextGLProgramType.FRAGMENT, 0, this._data, 1);
}
public updateTextures(stage:Stage)
{
super.updateTextures(stage);
this.updateBlurData();
}
private updateBlurData()
{
// todo: must be normalized using view size ratio instead of texture
var invW:number = 1/this._textureWidth;
this._data[0] = this._amount*.5*invW;
this._data[1] = this._realStepSize*invW;
}
private calculateStepSize()
{
this._realStepSize = this._stepSize > 0? this._stepSize : this._amount > Filter3DHBlurTask.MAX_AUTO_SAMPLES? this._amount/Filter3DHBlurTask.MAX_AUTO_SAMPLES : 1;
}
}
export = Filter3DHBlurTask;
|
01fadfde23c2f3ef297faa12388900af85310fe8
|
TypeScript
|
kyleschaeffer/binary-search
|
/src/binary-search.ts
| 4.03125
| 4
|
import { SortedList } from './sorted-list';
/**
* Search a sorted list for an item using binary search algorithm
* - Performant: O(log n)
*/
export function binarySearch<T>(haystack: SortedList<T>, needle: T): number|undefined {
// Initial search params
let min: number = 0;
let max: number = haystack.length - 1;
let guess;
// Search for the needle
while (min <= max) {
// Guess halfway between min and max
guess = Math.floor((min + max) / 2);
// Found it!
if (haystack.items[guess] === needle) return guess;
// Update min and max to search left or right of guess
if (needle > haystack.items[guess]) min = guess + 1;
else max = guess - 1;
}
// Not found
return undefined;
}
|
24f6c439a878f5e6c97aed6d47d558433544017d
|
TypeScript
|
Denilisium/uzd
|
/src/renderer/common/utils.ts
| 3.09375
| 3
|
export function groupBy<T>(array: T[], key: string): { [key: string]: T[] } {
return array.reduce((prev, curr) => {
(prev[curr[key]] = prev[curr[key]] || []).push(curr);
return prev;
}, {});
}
export function orderByDesc<T>(array: T[], key: string): T[] {
return array.sort((a, b) => {
return a[key] - b[key];
});
}
|
d91797e93c50da71d97b34ece908351d1a9b49fd
|
TypeScript
|
panxvpeng1/Learning-TS
|
/examples/interface/index.ts
| 3.78125
| 4
|
// //参数接口
// interface labelvalue {
// label:string;
// }
// function printLabel(labelobj:labelvalue){
// console.log(labelobj.label);
// }
// let myobj = {size:100,label:'ppaa'}
// printLabel(myobj);
// //可选属性
// interface squareconfig {
// color?:string;
// width?:number;
// }
// function createsquare(config:squareconfig):{color:string;area:number} {
// let newsquare = {color:'white',area:1200};
// if(config.color){
// newsquare.color = config.color
// }
// if(config.width){
// newsquare.area = config.width*config.width
// }
// return newsquare;
// }
// let mysquare = createsquare({color:'white'});
// console.log(mysquare)
// //只读属性
// interface point {
// readonly x:number;
// readonly y:number;
// }
// let p1:point = {x:10,y:20};//p1.x=5 //error
// let a:number[] = [1,2,3,4];
// let or:ReadonlyArray<number> = a;//ro[0] = 12 // error Cannot find name 'ro'
// //额外的属性检查
// interface squareconfig {
// color?:string;
// width?:number;
// [index:string]:any;//索引签名
// }
// function createsquare(config:squareconfig):{color:string;area:number} {
// let newsquare = {color:'white',area:1200};
// if(config.color){
// newsquare.color = config.color
// }
// if(config.width){
// newsquare.area = config.width*config.width
// }
// return newsquare;
// }
// let mysquare = createsquare({coluor:'white1'});//coluor既不是color也不是width,通过索引签名来解决报错
// console.log(mysquare)
// //函数类型
// interface searchfun {
// (source:string,substring:string):boolean;
// }
// let mysearch:searchfun;
// mysearch = function(source:string,substring:string) {//函数中的参数名不需要和接口中定义的相同
// let result = source.search(substring);
// return result > -1;
// }
// console.log(mysearch('123nihao你好','你'));
// //可索引类型
// interface stringarray {
// [index:number]:string;
// }
// let myarray:stringarray;
// myarray = ['nijhao','wo','zala'];
// let mystr:string;
// mystr = myarray[1]
// console.log(mystr);
// // class animal {
// // name:string;
// // }
// // class dog extends animal {
// // breed:string;
// // }
// // interface Notokay {//error 错误原因:数字索引的返回值必须是字符串索引返回值类型的子类型
// // [x:number]:animal;
// // [x:string]:dog;
// // }
// // interface NumberDictionary {
// // [index:string]:number;
// // length:number;
// // name:string;//error 错误原因:name的类型和索引返回值类型不匹配
// // }
// // interface ReadonlyStringArray {
// // readonly [index:number]:string;
// // }
// // let myarray:ReadonlyStringArray;
// // myarray = ["pxp"];
// // myarray[0] = '1'// error 错误原因:readonly类型不可修改值
// //类 类型 实现接口
// interface clockinterface {
// currenttime:Date;
// settime(d:Date);
// }
// class clock implements clockinterface {
// currenttime:Date;
// settime(d:Date){
// this.currenttime = d;
// }
// constructor(h:number,m:number){
// }
// }
// //类静态部分和实例部分的区别
// interface clockconstructor {
// new (hour:number,minute:number):clockinterface;
// }
// interface clockinterface {
// tick()
// }
// class digitclock implements clockinterface {
// constructor(h:number,m:number) {
// }
// tick(){
// console.log('ppxxpp');
// }
// }
// class vueclock implements clockinterface {
// constructor(h:number,m:number) {
// }
// tick() {
// console.log('vue');
// }
// }
// function createclock(ctor:clockconstructor,hour:number,minute:number):clockinterface {
// return new ctor(hour,minute);
// }
// let digit = createclock(digitclock,12,12);
// let vue = createclock(vueclock,5,5);
// console.log(digit.tick());
// console.log(vue.tick());
// //继承借口
// interface Shape {
// color:string;
// }
// interface Senstroke {
// penwidth:number;
// }
// interface Square extends Shape,Senstroke {
// sidelength:number;
// }
// let square = {} as Square;
// square.color = 'blue';
// square.penwidth = 11;
// square.sidelength = 4;
// console.log(square);
// //混合类型
// interface Counter {
// (start:number):string;
// interval:number;
// reset():void;
// }
// function getCounter():Counter {
// let counter = <Counter>function (start:number) {
// };
// counter.interval = 123;
// counter.reset = function():void {};
// return counter;
// }
// let c = getCounter();
// c(10);
// c.reset();
// c.interval = 1
// //接口继承类
// class Control {
// private state:any;
// pxp():void{
// console.log('pxp')
// };
// }
// interface SelectableControl extends Control {
// select():void;
// }
// class button extends Control implements SelectableControl {
// select(){}
// }
// class testbox extends Control {
// }
// // class img implements SelectableControl { //error img不是Control的子类
// // select(){}
// // }
|
b0db4485f61756225a851a9f30dfd71dd0e5ce69
|
TypeScript
|
shubham-kaushal/contember
|
/packages/engine-content-api/tests/cases/unit/permissionMergerTest.ts
| 2.59375
| 3
|
import 'jasmine'
import { Acl, Model } from '@contember/schema'
import PermissionFactory from '../../../src/acl/PermissionFactory'
import { SchemaBuilder } from '@contember/schema-definition'
interface Test {
acl: Acl.Schema
roles: string[]
result: Acl.Permissions
}
const execute = (test: Test) => {
const schema: Model.Schema = new SchemaBuilder()
.entity('Entity1', e => e.column('lorem').column('bar'))
.entity('Entity2', e => e.oneHasOne('xyz', r => r.target('Entity1')))
.buildSchema()
const merger = new PermissionFactory(schema)
const result = merger.create(test.acl, test.roles)
expect(result).toEqual(test.result)
}
describe('permission merger', () => {
it('merges inheritance', () => {
execute({
acl: {
roles: {
role1: {
variables: {},
stages: '*',
entities: {
Entity1: {
predicates: {},
operations: {
read: {
id: true,
},
},
},
},
},
role2: {
variables: {},
inherits: ['role1'],
stages: '*',
entities: {
Entity2: {
predicates: {},
operations: {
read: {
id: true,
},
},
},
},
},
},
},
roles: ['role2'],
result: {
Entity1: {
predicates: {},
operations: {
read: {
id: true,
},
},
},
Entity2: {
predicates: {},
operations: {
read: {
id: true,
},
},
},
},
})
})
it('merges entity operations', () => {
execute({
acl: {
roles: {
role1: {
variables: {},
stages: '*',
entities: {
Entity1: {
predicates: {},
operations: {
read: {
id: true,
},
},
},
},
},
role2: {
variables: {},
stages: '*',
entities: {
Entity1: {
predicates: {},
operations: {
read: {
title: true,
},
},
},
},
},
},
},
roles: ['role1', 'role2'],
result: {
Entity1: {
predicates: {},
operations: {
read: {
id: true,
title: true,
},
},
},
},
})
})
it('merges entity operations with predicates', () => {
execute({
acl: {
roles: {
role1: {
variables: {},
stages: '*',
entities: {
Entity1: {
predicates: {},
operations: {
read: {
id: true,
},
},
},
},
},
role2: {
variables: {},
stages: '*',
entities: {
Entity1: {
predicates: {
foo: { bar: { eq: 'abc' } },
},
operations: {
read: {
title: 'foo',
},
},
},
},
},
},
},
roles: ['role1', 'role2'],
result: {
Entity1: {
predicates: {
foo: { bar: { eq: 'abc' } },
},
operations: {
read: {
id: true,
title: 'foo',
},
},
},
},
})
})
it('merges entity operations and drops predicate', () => {
execute({
acl: {
roles: {
role1: {
variables: {},
stages: '*',
entities: {
Entity1: {
predicates: {},
operations: {
read: {
id: true,
title: true,
},
},
},
},
},
role2: {
variables: {},
stages: '*',
entities: {
Entity1: {
predicates: {
foo: { bar: { eq: 'abc' } },
},
operations: {
read: {
title: 'foo',
},
},
},
},
},
},
},
roles: ['role1', 'role2'],
result: {
Entity1: {
predicates: {},
operations: {
read: {
id: true,
title: true,
},
},
},
},
})
})
it('merges entity operations and merges predicates', () => {
execute({
acl: {
roles: {
role1: {
variables: {},
stages: '*',
entities: {
Entity1: {
predicates: {
bar: { lorem: { eq: 'ipsum' } },
},
operations: {
read: {
id: true,
title: 'bar',
},
},
},
},
},
role2: {
variables: {},
stages: '*',
entities: {
Entity1: {
predicates: {
foo: { bar: { eq: 'abc' } },
},
operations: {
read: {
title: 'foo',
},
},
},
},
},
},
},
roles: ['role1', 'role2'],
result: {
Entity1: {
predicates: {
__merge__bar__foo: {
or: [{ lorem: { eq: 'ipsum' } }, { bar: { eq: 'abc' } }],
},
},
operations: {
read: {
id: true,
title: '__merge__bar__foo',
},
},
},
},
})
})
it('merges delete operation', () => {
execute({
acl: {
roles: {
role1: {
variables: {},
stages: '*',
entities: {
Entity1: {
predicates: {
bar: { lorem: { eq: 'ipsum' } },
},
operations: {
delete: 'bar',
},
},
},
},
role2: {
variables: {},
stages: '*',
entities: {
Entity1: {
predicates: {
foo: { bar: { eq: 'abc' } },
},
operations: {
delete: 'foo',
},
},
},
},
},
},
roles: ['role1', 'role2'],
result: {
Entity1: {
predicates: {
__merge__bar__foo: {
or: [{ lorem: { eq: 'ipsum' } }, { bar: { eq: 'abc' } }],
},
},
operations: {
delete: '__merge__bar__foo',
},
},
},
})
})
it('merges predicates and resolves conflicts', () => {
execute({
acl: {
roles: {
role1: {
variables: {},
stages: '*',
entities: {
Entity1: {
predicates: {
foo: { lorem: { eq: 'ipsum' } },
},
operations: {
read: {
id: true,
title: 'foo',
},
},
},
},
},
role2: {
variables: {},
stages: '*',
entities: {
Entity1: {
predicates: {
foo: { bar: { eq: 'abc' } },
},
operations: {
read: {
content: 'foo',
},
},
},
},
},
},
},
roles: ['role1', 'role2'],
result: {
Entity1: {
predicates: {
foo: { lorem: { eq: 'ipsum' } },
foo_: { bar: { eq: 'abc' } },
},
operations: {
read: {
id: true,
title: 'foo',
content: 'foo_',
},
},
},
},
})
})
it('makes primary predicate union of all other fields', () => {
execute({
acl: {
roles: {
role1: {
variables: {},
stages: '*',
entities: {
Entity1: {
predicates: {
foo: { lorem: { eq: 'ipsum' } },
bar: { lorem: { eq: 'ipsum' } },
},
operations: {
read: {
title: 'foo',
description: 'bar',
content: 'bar',
},
},
},
},
},
},
},
roles: ['role1'],
result: {
Entity1: {
predicates: {
foo: { lorem: { eq: 'ipsum' } },
bar: { lorem: { eq: 'ipsum' } },
__merge__foo__bar: {
or: [{ lorem: { eq: 'ipsum' } }, { lorem: { eq: 'ipsum' } }],
},
},
operations: {
read: {
id: '__merge__foo__bar',
title: 'foo',
description: 'bar',
content: 'bar',
},
},
},
},
})
})
it('prefixes variables', () => {
execute({
acl: {
roles: {
role1: {
variables: {},
stages: '*',
entities: {
Entity2: {
predicates: {
foo: { xyz: { lorem: 'foo' } },
},
operations: {
read: {
title: 'foo',
},
},
},
},
},
},
},
roles: ['role1'],
result: {
Entity2: {
operations: {
read: {
title: 'foo',
id: 'foo',
},
},
predicates: {
foo: {
xyz: {
lorem: 'role1__foo',
},
},
},
},
},
})
})
it('prefixes inherited variables', () => {
execute({
acl: {
roles: {
role1: {
variables: {
foo: { entityName: 'Test', type: Acl.VariableType.entity },
},
stages: '*',
entities: {
Entity2: {
predicates: {
foo: { xyz: { lorem: 'foo' } },
},
operations: {
read: {
title: 'foo',
},
},
},
},
},
role2: {
variables: {},
entities: {},
inherits: ['role1'],
stages: '*',
},
},
},
roles: ['role2'],
result: {
Entity2: {
operations: {
read: {
title: 'foo',
id: 'foo',
},
},
predicates: {
foo: {
xyz: {
lorem: 'role2__foo',
},
},
},
},
},
})
})
})
|
1e4b5a3052480d77c37e5191c9b941cd0a5cd80a
|
TypeScript
|
zhaoge1991/oa-front
|
/src/app/models/work/task/taskType.ts
| 2.8125
| 3
|
export class TaskType {
task_type_id: number;
name: string;
level: number;
created_at: string;
updated_at: string;
constructor(taskType) {
if (taskType) {
this.task_type_id = taskType.task_type_id;
this.name = taskType.name;
this.level = taskType.level;
this.created_at = taskType.created_at;
this.updated_at = taskType.updated_at;
} else {
this.task_type_id = 0;
this.name = '';
this.level = 0;
this.created_at = '';
this.updated_at = '';
}
}
}
|
44c6c60f46222ca5aeb811ba64f854d899b706ad
|
TypeScript
|
malvdev/angular-google-books-api
|
/libs/book/domain/src/lib/application/+state/book/book.reducer.ts
| 2.65625
| 3
|
import { EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity';
import { createReducer, on, Action } from '@ngrx/store';
import * as BookActions from './book.actions';
import { BookEntity } from '../../../entities';
export const BOOK_FEATURE_KEY = 'book';
export interface BookError {
error: { message: string };
}
export interface State extends EntityState<BookEntity> {
totalItems: number;
loaded: boolean;
error?: null | BookError;
}
export interface BookPartialState {
readonly [BOOK_FEATURE_KEY]: State;
}
export const bookAdapter: EntityAdapter<BookEntity> =
createEntityAdapter<BookEntity>();
export const initialState: State = bookAdapter.getInitialState({
totalItems: 0,
loaded: false,
});
const bookReducer = createReducer(
initialState,
on(BookActions.initSearchBookPage, (state) => ({
...state,
loaded: true,
error: null,
})),
on(BookActions.searchBook, (state) => ({
...state,
loaded: false,
error: null,
})),
on(BookActions.searchBookSuccess, (state, { items, totalItems }) =>
bookAdapter.setAll(items, {
...state,
loaded: true,
error: null,
totalItems,
})
),
on(BookActions.searchBookFailure, (state, { error }) => ({
...state,
loaded: true,
error,
})),
on(BookActions.loadBookSuccess, (state, { book }) =>
bookAdapter.addOne(book, {
...state,
loaded: true,
error: null,
})
),
on(BookActions.loadBookFailure, (state, { error }) => ({
...state,
loaded: true,
error,
}))
);
export function reducer(state: State | undefined, action: Action) {
return bookReducer(state, action);
}
|
2f4026a56d638a817bc684968a0282f3e483766e
|
TypeScript
|
ShashirajSingh/Git-Assignment
|
/src/controllers/userController.ts
| 2.671875
| 3
|
import { Request, Response } from 'express';
import userModel from '../models/user.model';
import userService from '../services/user.service';
import responseService from '../services/response.service';
export default class {
static async getUserDetails(req: Request, res: Response) {
try {
const userName: string = req.body.username;
if (!userName) {
const apiResponse = responseService.success(
'please provide a valid user name.',
{},
403
);
res.send(apiResponse);
} else {
const userData = await userModel.findOne({ login: `${userName}` });
/* if user is present in our DB. */
if (userData !== null) {
const apiResponse = responseService.success('Success', userData, 200);
res.send(apiResponse);
} else {
const response = await userService.userSearch(userName);
if (response.data) {
const responseData = await userModel.create(response.data);
const apiResponse = responseService.success(
'Success',
responseData,
200
);
res.send(apiResponse);
} else {
const apiResponse = responseService.success('No user found', {});
res.send(apiResponse);
}
}
}
} catch (error) {
console.log(error);
return error;
}
}
}
|
0cc37bfadea2af5d664b479167a29f57d10cd1a2
|
TypeScript
|
rubykhanhas/techlife-ecommerce
|
/client/src/app/slices/cartSlice.ts
| 3.015625
| 3
|
import {createSlice} from '@reduxjs/toolkit'
export type CartItemType = {
imageUrl: string;
amount?: number;
title: string;
_id: string;
color: string;
salePrice: number;
}
type CartSliceActionType = {
type: string;
payload: CartItemType
}
const cache: any = sessionStorage.getItem('cartData');
const initState: CartItemType[] = JSON.parse(cache) || [];
const cartSlice = createSlice({
name: 'cart',
initialState: initState,
reducers: {
addToCart(state, action: CartSliceActionType){
if(!action.payload.amount) {
state.push({...action.payload, amount: 1});
saveToSession(state);
} else {
state.push({...action.payload})
}
},
removeCart(state, action: {payload: {_id: string}}) {
const myState = state.filter(item => item._id != action.payload._id);
saveToSession(myState);
return myState;
},
changeAmount(state, action: {payload: {_id: string; amount: number}}) {
const myState = state.map(item => {
if(item._id === action.payload._id){
return {...item, amount: action.payload.amount}
} else {
return item;
}
});
saveToSession(myState);
return myState;
}
}
})
const saveToSession = (rawData: CartItemType[]) => {
const data = rawData.map(item => {
return {
_id: item._id,
title: item.title,
imageUrl: item.imageUrl,
amount: item.amount,
color: item.color,
salePrice: item.salePrice
}
});
sessionStorage.setItem('cartData', JSON.stringify(data));
}
const {actions, reducer} = cartSlice;
export default reducer;
export const { addToCart, removeCart, changeAmount } = actions;
|
e9facc7f88f35e247ca49a1efe8c83adb5badc79
|
TypeScript
|
EverCrawl/client
|
/src/core/ECS.ts
| 3.546875
| 4
|
import { Constructor, InstanceTypeTuple, TypeOf } from "core/utils";
/**
* An opaque identifier used to access component arrays
*/
export type Entity = number;
/**
* Stores arbitrary data
*/
export type Component = {
free?: () => void;
[x: string]: any;
[x: number]: any;
}
/**
* Smallest logical unit of the game
*/
export interface System {
(registry: Registry, ...args: any[]): void;
}
export type View<Types extends Component[]> = Iterable<[Entity, ...Types]>;
export const Null: Entity = -1 >>> 0;
interface TypeList<T> { [key: string]: T };
interface Storage<T> { [key: number]: T };
export type ComponentView<T extends Constructor<Component>[]> = (registry: Registry, callback: (entity: Entity, ...components: InstanceTypeTuple<T>) => void) => void;
export class Group<T extends Constructor<Component>[]> {
constructor(private registry: Registry, private view: ComponentView<T>) { }
each(callback: (entity: Entity, ...components: InstanceTypeTuple<T>) => void) {
this.view(this.registry, callback);
}
}
const TagRegistry: { [id: string]: Constructor<any> } = {};
/**
* Similar to JS 'Symbol', this creates a unique
* ECS Tag, which can be used to give an entity
* a unique tag, which you can query for afterwards
*/
export function Tag(name: string) {
let tag = TagRegistry[name]
if (tag == null) {
tag = Object.defineProperty(class { }, "name", { value: name });
TagRegistry[name] = tag;
}
return tag;
}
/**
* Registry holds all components in arrays
*
* Component types must be registered first
*/
export class Registry {
private entitySequence: Entity = 0 >>> 0;
private entities: Set<Entity> = new Set;
private components: TypeList<Storage<Component>> = {};
private groups: { [id: string]: Group<any> } = {};
// TODO(speed): store entities and components by archetype
/**
* Creates an entity from provided components (if any)
*/
create<T extends Component[]>(...components: T): Entity {
const entity = this.entitySequence++ >>> 0;
this.entities.add(entity);
// emplace all components into entity
for (let i = 0, len = components.length; i < len; ++i) {
this.emplace(entity, components[i]);
}
return entity;
}
insert<T extends Component[]>(entity: Entity, ...components: T): Entity {
if (this.entities.has(entity)) {
throw new Error(`Attempted to insert duplicate entity ${entity}`);
}
this.entities.add(entity);
for (let i = 0, len = components.length; i < len; ++i) {
this.emplace(entity, components[i]);
}
return entity;
}
/**
* Returns true if `entity` is in the registry
*/
alive(entity: Entity): boolean {
return this.entities.has(entity);
}
/**
* Destroys an entity and all its components
*
* Calls `.free()` (if available) on each destroyed component
*
* Example:
* ```
* class A { free() { console.log("A freed"); } }
* const registry = new Registry();
* const entity = registry.create();
* registry.emplace(entity, new A);
* registry.destroy(entity); // logs "A freed"
* ```
*/
destroy(entity: Entity) {
this.entities.delete(entity);
for (const storage of Object.values(this.components)) {
const component = storage[entity];
if (component?.free) component.free();
delete storage[entity];
}
}
/**
* Retrieves component of type `type` for `entity`
*
* Example:
* ```
* const registry = new Registry();
* const entity = registry.create();
* registry.emplace(entity, new Component);
* // ...
* const component = registry.get(entity, Component);
* ```
*/
get<T extends Component>(entity: Entity, component: Constructor<T>): T | undefined {
const type = TypeOf(component);
// can't get for "dead" entity
if (!this.entities.has(entity)) {
throw new Error(`Cannot get component "${TypeOf(component)}" for dead entity ID ${entity}`);
}
const storage = this.components[type];
if (storage == null) return undefined;
return storage[entity] as T | undefined;
}
/**
* Used to check if `entity` has instance of `component`.
*
* Example:
* ```
* const registry = new Registry();
* const entity = registry.create();
* registry.has(entity, Component); // false
* registry.emplace(entity, new Component);
* registry.has(entity, Component); // true
* ```
*/
has<T extends Component>(entity: Entity, component: Constructor<T>): boolean {
const type = TypeOf(component);
const storage = this.components[type];
return storage != null && storage[entity] != null;
}
/**
* Sets `entity`'s instance of component `type` to `component`.
*
* **Warning:** Overwrites any existing instance of the component!
* Use `has` to check for existence first, if this is undesirable.
*
* Example:
* ```
* const entity = registry.create();
* registry.emplace(new Component, entity);
* ```
*/
emplace<T extends Component>(entity: Entity, component: T) {
const type = TypeOf(component);
if (!this.entities.has(entity)) {
throw new Error(`Cannot set component "${TypeOf(component)}" for dead entity ID ${entity}`);
}
const storage = this.components[type];
if (storage == null) this.components[type] = {};
this.components[type][entity] = component;
}
/**
* Removes instance of `component` from `entity`. Also returns the removed component.
*
* Example:
* ```
* const registry = new Registry();
* const entity = registry.create();
* registry.emplace(entity, new Component);
* // ...
* registry.remove(entity, Component); // true
* ```
*/
remove<T extends Component>(entity: Entity, component: Constructor<T>): T | undefined {
const type = TypeOf(component);
// can't remove for "dead" entity
if (!this.entities.has(entity)) {
throw new Error(`Cannot remove component "${TypeOf(component)}" for dead entity ID ${entity}`);
}
const storage = this.components[type];
if (storage == null) return undefined;
const out = this.components[type][entity] as T | undefined;
delete this.components[type][entity];
return out;
}
/**
* Returns the size of the registry (how many entities are stored)
*/
size(): number {
return this.entities.size;
}
/**
* Returns the ID part of the Entity
*/
static id(entity: Entity): number {
return entity & 0b00000000_00000000_11111111_11111111
}
/**
* Returns the version part of the Entity
*/
static version(entity: Entity): number {
return entity & 0b11111111_11111111_00000000_00000000
}
group<T extends Constructor<Component>[]>(...types: T): Group<T> {
let id = "";
for (let i = 0; i < types.length; ++i) {
id += types[i].name;
}
if (this.groups[id] == null) {
this.groups[id] = new Group(this, generateView(types));
}
return this.groups[id];
}
}
function join(arr: string[], sep: string) {
let out = "";
let end = arr.length - 1;
for (let i = 0; i < end; ++i) {
out += arr[i] + sep
}
out += arr[end]
return out
}
// don't really care about types here
function generateView(types: any[]): ComponentView<any> {
// note: prefix _$ is used to lower the chance of name collisions
let variables = "";
const varNames: string[] = [];
for (let i = 0; i < types.length; ++i) {
const typeName = types[i].name;
const varName = `${typeName}${i}`;
varNames.push(varName);
variables += `var ${varName} = _$registry.components["${typeName}"][entity];\n`;
variables += `if (${varName} == null) continue nextEntity;\n`;
}
let fn = "";
fn += "nextEntity: for(var entity of _$registry.entities.values()) {\n";
fn += `${variables}`;
fn += `_$callback(entity,${join(varNames, ",")});\n`
fn += "}";
return new Function("_$registry", "_$callback", fn) as any;
}
|
96158a77394e1f7f6f3b4e550c001466297a27f7
|
TypeScript
|
flyFatSeal/react-components
|
/src/haiwell/Alert/MockAlertService.ts
| 2.703125
| 3
|
function ranText(prefix: string = "", len: number = 9): string {
let str = prefix;
for (let i = 0; i < len; i++) {
str += String.fromCharCode(Math.floor(Math.random() * 26) | ranOption(0x41, 0x61));
}
return str;
}
function ranOption<T1, T2>(v: T1, v2: T2): T1 | T2 {
return Math.random() >= 0.5 ? v : v2;
}
function ranDate(latest: number = Date.now()): Date {
return new Date(Math.floor(Math.random() * latest))
}
let DATA_INDEX = 0;
let UID = 0;
function ranData(): alert2.client.DataWithIndex {
const time = ranDate().toLocaleString();
const isAlert = Math.random() >= 0.5;
return {
index: ++DATA_INDEX,
uid: ++UID,
alertTime: isAlert ? time : '',
value: ranText("value:"),
message: ranText("message:", 12),
type: ranOption("alert", "recovery"),
variableID: 0,
variableName: ranText("name:", 8),
confirmTime: ranOption("", ranDate().toLocaleString()),
recoveryTime: isAlert ? "" : time,
};
}
export class MockAlertDataBuilder implements alert2.client.Service {
private readonly pageSize = 10;
private _tab: alert2.common.DataType = "realtime";
private historyPage = 0;
private unconfirmPage = 0;
private confirmPage = 0;
private latest: alert2.client.DataWithIndex[];
constructor() {
this.latest = [];
this.ranLatest(1000);
}
private ranLatest(timeout: number): void {
setTimeout(() => {
this.latest.push(ranData());
if (this.latest.length > 10) {
this.latest.shift();
}
this.ranLatest(timeout);
this.emitUpdate(this.latest);
}, timeout);
}
getData() {
const tab = this._tab;
let page = 0;
switch (tab) {
case "realtime": page = 0; break;
case "history": page = this.historyPage; break;
case "unconfirm": page = this.unconfirmPage; break;
case "confirmed": page = this.confirmPage; break;
}
return {
page,
tab,
alerts: this.latest,
confirm: this.confirm,
setPage: this.setPage,
setTab: this.setTab,
inputPage: this.inputPage,
inputDate: this.inputDate,
uiLang: Object.create(null),
dataLang: Object.create(null),
beep: this.beep,
};
};
onUpdate?: (d: alert2.client.TableData) => void;
readonly confirm = (alert?: alert2.client.DataWithIndex) => {
if (alert === undefined) {
const date = new Date().toLocaleString();
this.latest.forEach(l => l.confirmTime = date);
this.emitUpdate(this.latest);
return;
}
let mod = false;
this.latest.forEach(l => {
if (l.uid === alert.uid) {
l.confirmTime = new Date().toLocaleString();
mod = true;
}
});
if (mod) {
this.emitUpdate(this.latest);
}
};
private emitUpdate(data: alert2.client.DataWithIndex[]): void {
if (this.onUpdate === undefined) return;
console.log("emit update");
const alerts = [];
for (let i = 0; i < this.pageSize; i++) {
alerts[i] = data[i];
}
const tab = this._tab;
let page = 0;
switch (tab) {
case "confirmed": page = this.confirmPage; break;
case "unconfirm": page = this.unconfirmPage; break;
case "history": page = this.historyPage; break;
}
this.onUpdate(this.getData());
}
readonly query = (tab: alert2.common.DataType, page: number, pageSize: number): void => {
console.log("query type: %s, page: %d, pageSize: %d", tab, page, pageSize);
}
setPage = (p: number): void => {
console.log("set page: %d", p);
if (p < 0) return;
switch (this._tab) {
case "history":
this.historyPage = p;
break;
case "unconfirm":
this.unconfirmPage = p;
break;
case "confirmed":
this.confirmPage = p;
break;
}
this.emitUpdate(this.latest);
}
setTab = (tab: alert2.common.DataType): void => {
console.log("set tab: ", tab);
if (tab === this._tab) return;
this._tab = tab;
this.emitUpdate(this.latest);
}
inputPage = (): void => { }
inputDate = (): void => { }
private readonly beep = () => {
console.log("bee");
}
}
|
1763fa22e8a906e296a79c317e68e379983a6eeb
|
TypeScript
|
YuhSylphy/motty-derby
|
/src/features/horse-defs/core/horse.ts
| 3.078125
| 3
|
import { of } from 'rxjs';
import {
groupBy,
mergeAll,
mergeMap,
toArray,
reduce,
tap,
} from 'rxjs/operators';
export type Sex = 'male' | 'female' | 'unknown';
export type Line =
| 'Uk' // 不明(指定なし)
| 'Ec' // エクリプス系
| 'Ph' // ファラリス系
| 'Ns' // ナスルーラ系
| 'Ro' // ロイヤルチャージャー系
| 'Ne' // ニアークティック系
| 'Na' // ネイティヴダンサー系
| 'Fa' // フェアウェイ系
| 'To' // トムフール系
| 'Te' // テディ系
| 'Sw' // スインフォード系
| 'Ha' // ハンプトン系
| 'Hi' // ヒムヤー系
| 'St' // セントサイモン系
| 'Ma' // マッチェム系
| 'He'; // ヘロド系
export const lineMap: { [key in Line]: { label: string } } = {
Uk: { label: '不明(指定なし)' },
Ec: { label: 'エクリプス' },
Ph: { label: 'ファラリス' },
Ns: { label: 'ナスルーラ' },
Ro: { label: 'ロイヤルチャージャー' },
Ne: { label: 'ニアークティック' },
Na: { label: 'ネイティヴダンサー' },
Fa: { label: 'フェアウェイ' },
To: { label: 'トムフール' },
Te: { label: 'テディ' },
Sw: { label: 'スインフォード' },
Ha: { label: 'ハンプトン' },
Hi: { label: 'ヒムヤー' },
St: { label: 'セントサイモン' },
Ma: { label: 'マッチェム' },
He: { label: 'ヘロド' },
};
export type HorseDef = {
/** 名称: ID代わり */
name: string;
/** 父親名 */
fatherName?: string;
/** 母親名 */
motherName?: string;
/** 性別 */
sex: Sex;
/** 系統 */
line: Line;
/** 種牡馬/繁殖牝馬一覧に載っているか */
listed: boolean;
/** 所有馬 */
owned: boolean;
/** 表示すべきか */
show: boolean;
/** メモ */
memo: string[];
};
type AnscestorHorse = {
name?: string;
father?: AnscestorHorse;
mother?: AnscestorHorse;
line?: Line;
};
interface ListedAnscestor extends AnscestorHorse {
name: Exclude<AnscestorHorse['name'], undefined>;
father: Exclude<AnscestorHorse['father'], undefined>;
mother: Exclude<AnscestorHorse['mother'], undefined>;
}
/**
* 種牡馬・繁殖牝馬リストを競走馬一覧にflattenして返す
* @param def
* @param param1
*/
const flatten = (
def: AnscestorHorse,
{ sex, listed, childName }: { sex: Sex; listed?: boolean; childName: string }
): HorseDef[] => {
const name =
def.name ??
`${childName}${sex === 'female' ? '母' : sex === 'male' ? '父' : '親'}`;
const show = def.name !== void 0;
const fathers = def.father
? flatten(def.father, { sex: 'male', childName: name })
: [];
const mothers = def.mother
? flatten(def.mother, { sex: 'female', childName: name })
: [];
const line = def.line ?? fathers?.[0]?.line ?? 'Uk';
const target: HorseDef = {
name,
line,
listed: !!listed,
owned: false,
show,
fatherName: fathers?.[0]?.name,
motherName: mothers?.[0]?.name,
memo: [],
sex,
};
return [target, fathers, mothers].flat();
};
const fetchOwned =
// 所有馬
(): Promise<HorseDef[]> =>
fetch(`${process.env.PUBLIC_URL}/assets/horse-defs.json`)
.then((res) => res.json())
.then((data: (HorseDef & { removed?: boolean })[]) =>
data
.filter((def) => !def.removed)
.map((def) => ({
...def,
listed: !!def.listed,
owned: true,
show: true,
memo: def.memo ?? [],
}))
);
/**
* 繁殖牝馬リスト
*/
const fetchBroodmare = (): Promise<HorseDef[]> =>
fetch(`${process.env.PUBLIC_URL}/assets/broodmares.json`)
.then((res) => res.json())
.then((data: ListedAnscestor[]) =>
data
.map((def) =>
flatten(def, { sex: 'female', listed: true, childName: 'N/A' })
)
.flat()
);
/**
* 種牡馬リスト
*/
const fetchStallion = (): Promise<HorseDef[]> =>
fetch(`${process.env.PUBLIC_URL}/assets/stallions.json`)
.then((res) => res.json())
.then((data: ListedAnscestor[]) =>
data
.map((def) =>
flatten(def, { sex: 'male', listed: true, childName: 'N/A' })
)
.flat()
);
/**
* 競走馬の定義を取得してマージする
*/
export const fetchHorseDefs = (): Promise<HorseDef[]> =>
of(fetchOwned, fetchStallion, fetchBroodmare)
.pipe(
mergeMap((func) => func()),
mergeAll(),
groupBy((def) => def.name),
mergeMap((group) =>
group.pipe(
reduce((lhs, rhs) => ({
name: lhs.name ?? rhs.name,
sex: lhs.sex ?? rhs.sex,
listed: lhs.listed || rhs.listed,
show: lhs.show || rhs.show,
owned: lhs.owned || rhs.owned,
line: lhs.line === 'Uk' ? rhs.line : lhs.line,
memo: [...lhs.memo, ...rhs.memo],
fatherName: lhs.fatherName ?? rhs.fatherName,
motherName: lhs.motherName ?? rhs.motherName,
}))
)
),
toArray(),
tap((defs) => {
const m = new Map<string, HorseDef>(defs.map((def) => [def.name, def]));
/** lineがUnknownのものを父親の情報から保完する */
const complementLine = (def: HorseDef) => {
// 対応不要
if (def.line && def.line !== 'Uk') {
return;
}
// 父親が後ろにいるかも知れないので先に再帰しておく
if (def.fatherName) {
const father = m.get(def.fatherName);
if (father) {
complementLine(father);
} else {
console.warn(
`${def.fatherName}: father of ${def.name} doesnt exist in list`,
def,
m
);
}
}
// それでも未確定ならUkに設定
def.line = m.get(def.fatherName || '')?.line ?? 'Uk';
if (def.line === 'Uk') {
console.warn(`couldnt determine line of ${def.name}`);
}
};
defs.forEach(complementLine);
})
)
.toPromise();
|
73e6a01368fac686db153fa42ac3ba8c690a9834
|
TypeScript
|
Jsurapong/compare-purestate-recoil-rxjs
|
/modules/pureState/service/api.ts
| 2.953125
| 3
|
import axios from "axios";
interface List {
id: number;
title: string;
author: string;
}
interface Form {
id: number | null;
method: "post" | "put";
data: List;
}
export interface State {
list: List[];
detail: List;
form: Form;
}
const initDetail: List = { id: 0, title: "", author: "" }; // show
const initForm: Form = {
id: 0,
method: "post",
data: { id: 0, title: "", author: "" },
}; // edit form
export const initState: State = {
list: [],
detail: initDetail,
form: initForm,
};
class User {
apiUrl = "http://localhost:4000/posts";
state: State = initState;
setState = (...params: any) => {};
init = (setState: (...p: any) => void) => {
this.setState = setState;
this.setState(this.state);
};
updateState = (key: string, value: {} | string | number | []) => {
const newState: State = { ...this.state, [key]: value };
this.state = newState;
this.setState(this.state); // force component re-render
};
getItemForm = (id: number | null): List | {} => {
const item = this.state.list.find((item) => item.id === id);
return item || initForm;
};
form = {
init: () => {}, // set init form options api fetch
onChange: (key: string, value: string | number) => {
const newForm = { ...this.state.form, [key]: value };
this.updateState("form", newForm);
},
selectedId: (id: number | null) => {
this.updateState("formMethod", id ? "put" : "post");
const user = this.getItemForm(id);
this.updateState("form", user);
},
};
submit = () => this[this.state.form.method]();
// api
fetch = async (id: number | null) => {
const { data } = await axios(`${this.apiUrl}${id || ""}`);
const key = id ? "item" : "list";
this.updateState(key, data);
};
post = async () => {
const data = this.state.form;
await axios.post(this.apiUrl, data);
this.updateState("form", initForm);
this.fetch(null);
};
put = async () => {
const data = this.state.form;
await axios.put(`${this.apiUrl}/${this.state.form.id}`, data);
this.updateState("form", initForm);
this.fetch(null);
};
delete = async (id: number) => {
await axios.delete(`${this.apiUrl}/${id}`);
const newList = this.state.list.filter((item) => item?.id !== id);
this.updateState("list", newList);
};
}
export { User };
|
6dffc72b493b34efbf37a787588fc0ef14808fc6
|
TypeScript
|
cybernetics/WebRx
|
/src/Collections/Map.ts
| 2.859375
| 3
|
/// <reference path="../../node_modules/typescript/lib/lib.es6.d.ts" />
/// <reference path="../Interfaces.ts" />
import { getOid } from "../Core/Oid"
"use strict";
/**
* ES6 Map Shim
* @class
*/
class MapEmulated<TKey extends Object, T> implements wx.IMap<TKey, T> {
////////////////////
/// IMap
public get size() {
return this.keys.length;
}
public has(key: any): boolean {
if (key === this.cache) {
return true;
}
if (this.find(key) >= 0) {
this.cache = key;
return true;
}
return false;
}
public get(key: any): any {
var index = this.find(key);
if (index >= 0) {
this.cache = key;
return this.values[index];
}
return undefined;
}
public set(key: any, value: any): wx.IMap<any, any> {
this.delete(key);
this.keys.push(key);
this.values.push(value);
this.cache = key;
return this;
}
public delete(key: any): boolean {
var index = this.find(key);
if (index >= 0) {
this.keys.splice(index, 1);
this.values.splice(index, 1);
this.cache = this.cacheSentinel;
return true;
}
return false;
}
public clear(): void {
this.keys.length = 0;
this.values.length = 0;
this.cache = this.cacheSentinel;
}
public forEach(callback: (value: any, key: any, map: wx.IMap<any, any>) => void, thisArg?: any): void {
var size = this.size;
for (var i = 0; i < size; ++i) {
var key = this.keys[i];
var value = this.values[i];
this.cache = key;
callback.call(this, value, key, this);
}
}
public get isEmulated(): boolean {
return true;
}
////////////////////
/// Implementation
cacheSentinel = {};
keys = [];
values = [];
cache = this.cacheSentinel;
private find(key: any): number {
var keys = this.keys;
var size = keys.length;
for (var i = 0; i < size; ++i) {
if (keys[i] === key) {
return i;
}
}
return -1;
}
}
function isFunction(o: any): boolean {
return typeof o === 'function';
}
var proto: wx.IMap<any, any> = (window != null && window["Map"] !== undefined) ? <any> Map.prototype : undefined;
var hasNativeSupport = window != null && isFunction(window["Map"]) && isFunction(proto.forEach) &&
isFunction(proto.set) && isFunction(proto.clear) &&
isFunction(proto.delete) && isFunction(proto.has);
/**
* Creates a new WeakMap instance
* @param {boolean} disableNativeSupport Force creation of an emulated implementation, regardless of browser native support.
* @return {IWeakMap<TKey, T>} A new instance of a suitable IWeakMap implementation
*/
export function createMap<TKey, T>(disableNativeSupport?: boolean): wx.IMap<TKey, T> {
if (disableNativeSupport || !hasNativeSupport) {
return new MapEmulated<TKey, T>();
}
return <wx.IMap<TKey, T>> <any> new Map();
}
|
b94fd3abd894e0c1315c040639a4acb45e258af2
|
TypeScript
|
BinaryProvider/react-data-grid
|
/test/keyboardNavigation.test.ts
| 2.546875
| 3
|
import userEvent from '@testing-library/user-event';
import { fireEvent } from '@testing-library/react';
import type { Column } from '../src';
import { setup, getSelectedCell, validateCellPosition } from './utils';
type Row = undefined;
const rows: readonly Row[] = Array(100);
const columns: readonly Column<Row>[] = [
{ key: 'col1', name: 'col1' },
{ key: 'col2', name: 'col2' },
{ key: 'col3', name: 'col3' },
{ key: 'col4', name: 'col4' },
{ key: 'col5', name: 'col5' },
{ key: 'col6', name: 'col6' },
{ key: 'col7', name: 'col7' }
];
test('basic keyboard navigation', () => {
setup({ columns, rows });
// no initial selection
expect(getSelectedCell()).not.toBeInTheDocument();
// tab into the grid
userEvent.tab();
validateCellPosition(0, 0);
// tab to the next cell
userEvent.tab();
validateCellPosition(1, 0);
// tab back to the previous cell
userEvent.tab({ shift: true });
validateCellPosition(0, 0);
// arrow navigation
userEvent.type(document.activeElement!, '{arrowdown}');
validateCellPosition(0, 1);
userEvent.type(document.activeElement!, '{arrowright}');
validateCellPosition(1, 1);
userEvent.type(document.activeElement!, '{arrowup}');
validateCellPosition(1, 0);
userEvent.type(document.activeElement!, '{arrowleft}');
validateCellPosition(0, 0);
// page {up,down}/home/end navigation
fireEvent.keyDown(document.activeElement!, { key: 'PageDown' });
validateCellPosition(0, 29);
fireEvent.keyDown(document.activeElement!, { key: 'PageDown' });
validateCellPosition(0, 58);
fireEvent.keyDown(document.activeElement!, { key: 'PageUp' });
validateCellPosition(0, 29);
userEvent.type(document.activeElement!, '{end}');
validateCellPosition(6, 29);
userEvent.type(document.activeElement!, '{home}');
validateCellPosition(0, 29);
userEvent.type(document.activeElement!, '{ctrl}{end}');
validateCellPosition(6, 99);
userEvent.type(document.activeElement!, '{ctrl}{home}');
validateCellPosition(0, 0);
});
test('at-bounds basic keyboard navigation', () => {
setup({ columns, rows });
// tab into the grid
userEvent.tab();
validateCellPosition(0, 0);
// arrow navigation
userEvent.type(document.activeElement!, '{arrowup}');
validateCellPosition(0, 0);
userEvent.type(document.activeElement!, '{arrowleft}');
validateCellPosition(0, 0);
userEvent.type(document.activeElement!, '{ctrl}{end}');
validateCellPosition(6, 99);
userEvent.type(document.activeElement!, '{arrowdown}');
validateCellPosition(6, 99);
userEvent.type(document.activeElement!, '{arrowright}');
validateCellPosition(6, 99);
// page {up,down}/home/end navigation
userEvent.type(document.activeElement!, '{end}');
validateCellPosition(6, 99);
userEvent.type(document.activeElement!, '{ctrl}{end}');
validateCellPosition(6, 99);
fireEvent.keyDown(document.activeElement!, { key: 'PageDown' });
validateCellPosition(6, 99);
userEvent.type(document.activeElement!, '{ctrl}{home}');
validateCellPosition(0, 0);
userEvent.type(document.activeElement!, '{home}');
validateCellPosition(0, 0);
userEvent.type(document.activeElement!, '{ctrl}{home}');
validateCellPosition(0, 0);
fireEvent.keyDown(document.activeElement!, { key: 'PageUp' });
validateCellPosition(0, 0);
// shift+tab tabs out of the grid
userEvent.tab({ shift: true });
expect(document.body).toHaveFocus();
// tab at the end of a row selects the first cell on the next row
userEvent.tab();
userEvent.type(document.activeElement!, '{end}');
userEvent.tab();
validateCellPosition(0, 1);
// tab at the end of the grid tabs out of the grid
userEvent.type(document.activeElement!, '{ctrl}{end}');
userEvent.tab();
expect(document.body).toHaveFocus();
});
|
2d95768f4ecc3dcc11a759f8ba618afa19ee32e2
|
TypeScript
|
mostafabita/firebase-ang
|
/src/app/pipes/abbr.pipe.ts
| 2.65625
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'abbr',
})
export class AbbrPipe implements PipeTransform {
transform(value: string, length: number = 2): any {
if (!value) return null;
return value
.split(' ')
.map((str) => str.substr(0, 1))
.join('')
.substr(0, length)
.toUpperCase();
}
}
|
d0dd217f85b2e8139a2424169bf850954c243cc6
|
TypeScript
|
wlgns2223/booking-light-client
|
/src/hook/useBookingInput.ts
| 2.578125
| 3
|
import { arraySum } from "@janda-com/front";
import { useState } from "react";
import {
BookingInput,
CapacityInput,
Fproduct,
FproductBooking,
productList_ProductList_items_ProductBooking,
productList_ProductList_items_ProductBooking_capacityDetails,
productList_ProductList_items_ProductBooking_usageDetails,
} from "../type/api";
import { getCapacityOptionPrice } from "../utils/productBookingUtils";
export interface IBookingInputData extends BookingInput {
productOrigin: Partial<FproductBooking>;
}
export interface IUseBookingsInput
extends ReturnType<typeof useBookingsInput> {}
export const useBookingsInput = (
defaultProps: IBookingInputData[],
allproducts?: productList_ProductList_items_ProductBooking[]
) => {
const [bookingInputs, setBookingInputs] =
useState<IBookingInputData[]>(defaultProps);
const recalculatedGet = (bookingInputs: IBookingInputData[]) => {
return bookingInputs.map((bi) => ({
...bi,
priceOrigin: cdPrices(bi.countDetails || []),
}));
};
const cdPrices = (cd: CapacityInput[]): number => {
return arraySum(cd.map((cd) => cd.price)) || 0;
};
const priceSum = arraySum(
bookingInputs.map((input) => input.priceOrigin || 0)
);
const findBookingInput = (pid: string) => {
return bookingInputs.find((bi) => bi.productId === pid);
};
const findCpacity = (pid: string, key: string | number) => {
const bookingInput = findBookingInput(pid);
const targetCapacity =
typeof key === "string"
? (bookingInput?.countDetails || []).find(
(detail) => detail.key === key
)
: bookingInput?.countDetails?.[key];
return targetCapacity;
};
const findAllCapacity = (pid: string, key: string) => {
const bookingInput = findBookingInput(pid);
return bookingInput?.countDetails?.filter((cd) => cd.key === key) || [];
};
const removeCapacity = (pid: string, key: string | number) => {
const bookingInput = findBookingInput(pid);
if (!bookingInput) return;
if (!bookingInput.countDetails) return;
const { countDetails } = bookingInput;
let targetIndex = key as number;
if (typeof key === "string") {
targetIndex = countDetails.findIndex((cd) => cd.key === key);
}
countDetails.splice(targetIndex, 1);
const len = bookingInput.countDetails.length;
if (len < 1) {
removeProduct(pid);
return;
}
setBookingInputs([...recalculatedGet(bookingInputs)]);
};
//가격은 들어오기전에 cp에 넣어줘야한다.
const addCapcity = (pid: string, cp: CapacityInput) => {
const target = findBookingInput(pid);
if (!target) return;
target.countDetails?.push(cp);
setBookingInputs([...recalculatedGet(bookingInputs)]);
};
const removeProduct = (pid: string) => {
const targetIndex = bookingInputs.findIndex(
(prod) => prod.productId === pid
);
bookingInputs.splice(targetIndex, 1);
setBookingInputs([...recalculatedGet(bookingInputs)]);
};
const empty = () => {
setBookingInputs([]);
};
const addProduct = (bookingInput: IBookingInputData) => {
bookingInputs.push(bookingInput);
setBookingInputs([...recalculatedGet(bookingInputs)]);
};
const toggleProduct = (bookingInput: IBookingInputData) => {
const productId = bookingInput.productId;
const target = findBookingInput(productId);
if (!target) {
addProduct(bookingInput);
} else {
removeProduct(productId);
}
setBookingInputs([...recalculatedGet(bookingInputs)]);
};
// 하나의 캐파시티를 변경 가격은 들오어기전에 cp에 들어있다.
const changeCapacity = (pid: string, cp: CapacityInput, index?: number) => {
let target: CapacityInput | undefined;
const findWith = typeof index === "number" ? index : cp.key;
target = findCpacity(pid, findWith);
// 없으면 캐파시티 추가...
if (!target) {
addCapcity(pid, { ...cp });
return;
}
// 0이되면 캐파시티 제거...
if (cp.count === 0) {
removeCapacity(pid, findWith);
return;
}
// 카운트 입력
target.price = cp.price;
target.count = cp.count;
target.options = cp.options;
setBookingInputs([...recalculatedGet(bookingInputs)]);
};
const capacityChangeMaster = (
product: productList_ProductList_items_ProductBooking,
cd: productList_ProductList_items_ProductBooking_usageDetails,
num: number
) => {
const isIncluded = findBookingInput(product._id);
const update: CapacityInput = {
count: num,
key: cd.key,
label: cd.label,
price: cd.price * num,
};
if (isIncluded) {
changeCapacity(product._id, update);
} else {
addProduct({
productOrigin: product,
itemId: product._itemId,
productId: product._id,
countDetails: [update],
});
}
};
const getLeftCountOf = (
usageDetail: productList_ProductList_items_ProductBooking_usageDetails,
pid: string
) => {
const { usage, capacityCount, key } = usageDetail;
const selectedCount = findAllCapacity(pid, key);
const selecteds = arraySum(
selectedCount.map((selectedCount) => selectedCount.count)
);
return capacityCount - usage - selecteds;
};
return {
empty,
priceSum,
bookingInputs,
setBookingInputs,
changeCapacity,
addCapcity,
addProduct,
removeCapacity,
removeProduct,
findCpacity,
getLeftCountOf,
findBookingInput,
getCapacityOptionPrice,
capacityChangeMaster,
toggleProduct,
};
};
|
61485c9fbae84a746d2879088a8195719ea6e16b
|
TypeScript
|
katawolf/eshop
|
/src/store/cart/reducer.spec.ts
| 2.65625
| 3
|
import cartReducer from "./reducer";
import {CartActionType} from "./type";
import {aCartArticle} from "../../data.mock";
describe('reducer spec', () => {
describe('default handle', () => {
test('should return initial state', () => {
expect(
cartReducer(undefined, {} as CartActionType)
).toEqual({
cartArticles: []
})
})
})
describe('handle "ADD_CART_ARTICLE"', () => {
test('should add article', () => {
expect(
cartReducer({
cartArticles: [aCartArticle({id: '2', name: 'X1 carbon', quantity: 1})]
}, {
type: 'ADD_CART_ARTICLE',
payload: aCartArticle({id: '1', name: 'Iphone', quantity: 1})
})
).toEqual({
cartArticles: [
aCartArticle({id: '2', name: 'X1 carbon', quantity: 1}),
aCartArticle({id: '1', name: 'Iphone', quantity: 1})
]
})
})
test('should not add and return error when the quantity is superior of max quantity by cart', () => {
expect(
cartReducer({
cartArticles: [
aCartArticle({id: '1', name: 'Iphone', quantity: 1}),
]
}, {
type: 'ADD_CART_ARTICLE',
payload: aCartArticle({id: '2', name: 'X1 carbon', quantity: 9, maxQuantityByCart: 8})
})
).toEqual({
error: 'You can\'t add more quantity of max quantity article in cart',
cartArticles: [
aCartArticle({id: '1', name: 'Iphone', quantity: 1}),
]
})
})
describe('article is already added', () => {
test('should update quantity of article', () => {
expect(
cartReducer({
cartArticles: [
aCartArticle({id: '1', name: 'Iphone', quantity: 1}),
aCartArticle({id: '2', name: 'X1 carbon', quantity: 1})
]
}, {
type: 'ADD_CART_ARTICLE',
payload: aCartArticle({id: '2', name: 'X1 carbon', quantity: 1})
})
).toEqual({
cartArticles: [
aCartArticle({id: '1', name: 'Iphone', quantity: 1}),
aCartArticle({id: '2', name: 'X1 carbon', quantity: 2})
]
})
})
test('should not add article and return error when the max quantity of article in cart is exceeded', () => {
expect(
cartReducer({
cartArticles: [
aCartArticle({id: '1', name: 'Iphone', quantity: 1}),
aCartArticle({id: '2', name: 'X1 carbon', quantity: 8, maxQuantityByCart: 8})
]
}, {
type: 'ADD_CART_ARTICLE',
payload: aCartArticle({id: '2', name: 'X1 carbon', quantity: 1, maxQuantityByCart: 8})
})
).toEqual({
error: 'You can\'t add more quantity of max quantity article in cart',
cartArticles: [
aCartArticle({id: '1', name: 'Iphone', quantity: 1}),
aCartArticle({id: '2', name: 'X1 carbon', quantity: 8, maxQuantityByCart: 8})
]
})
})
test('should not return error when article is added', () => {
expect(
cartReducer({
error: 'an error',
cartArticles: []
}, {
type: 'ADD_CART_ARTICLE',
payload: aCartArticle({id: '1', name: 'Iphone', quantity: 1})
})
).toEqual({
cartArticles: [
aCartArticle({id: '1', name: 'Iphone', quantity: 1}),
]
})
})
})
})
describe('handle "REMOVE_CART_ARTICLE"', () => {
test('should remove article', () => {
expect(
cartReducer({
cartArticles: [
aCartArticle({id: '1', name: 'Iphone', quantity: 1}),
aCartArticle({id: '2', name: 'X1 carbon', quantity: 1})
]
}, {
type: 'REMOVE_CART_ARTICLE',
payload: aCartArticle({id: '1', name: 'Iphone', quantity: 1})
})
).toEqual({
cartArticles: [
aCartArticle({id: '2', name: 'X1 carbon', quantity: 1})
]
})
})
test('should not return error when article is removed', () => {
expect(
cartReducer({
error: 'an error',
cartArticles: [
aCartArticle({id: '1', name: 'Iphone', quantity: 1}),
]
}, {
type: 'REMOVE_CART_ARTICLE',
payload: aCartArticle({id: '1', name: 'Iphone', quantity: 1})
})
).toEqual({
cartArticles: []
})
})
})
describe('handle "UPDATE_CART_ARTICLE"', () => {
test('should update article', () => {
expect(
cartReducer({
cartArticles: [
aCartArticle({id: '1', name: 'Iphone', quantity: 1}),
aCartArticle({id: '2', name: 'X1 carbon', quantity: 5})
]
}, {
type: 'UPDATE_CART_ARTICLE',
payload: aCartArticle({id: '2', name: 'X1 carbon', quantity: 10})
})
).toEqual({
cartArticles: [
aCartArticle({id: '1', name: 'Iphone', quantity: 1}),
aCartArticle({id: '2', name: 'X1 carbon', quantity: 10})
]
})
})
test('should not update articles when article is not already added', () => {
expect(
cartReducer({
cartArticles: [
aCartArticle({id: '1', name: 'Iphone', quantity: 1}),
]
}, {
type: 'UPDATE_CART_ARTICLE',
payload: aCartArticle({id: '2', name: 'X1 carbon', quantity: 10})
})
).toEqual({
cartArticles: [
aCartArticle({id: '1', name: 'Iphone', quantity: 1}),
]
})
})
test('should not update when the quantity is superior of max quantity by cart', () => {
expect(
cartReducer({
cartArticles: [
aCartArticle({id: '2', name: 'X1 carbon', quantity: 5})
]
}, {
type: 'UPDATE_CART_ARTICLE',
payload: aCartArticle({id: '2', name: 'X1 carbon', quantity: 10, maxQuantityByCart: 8})
})
).toEqual({
cartArticles: [
aCartArticle({id: '2', name: 'X1 carbon', quantity: 5})
]
})
})
test('should not return error when article is updated', () => {
expect(
cartReducer({
error: 'An error',
cartArticles: [
aCartArticle({id: '2', name: 'X1 carbon', quantity: 5})
]
}, {
type: 'UPDATE_CART_ARTICLE',
payload: aCartArticle({id: '2', name: 'X1 carbon', quantity: 10})
})
).toEqual({
cartArticles: [
aCartArticle({id: '2', name: 'X1 carbon', quantity: 10})
]
})
})
})
describe('handle "CLEAN ERROR"', () => {
test('should clean error', () => {
expect(
cartReducer({
error: 'An error',
cartArticles: [
aCartArticle({id: '2', name: 'X1 carbon', quantity: 5})
]
}, {
type: 'CLEAN_CART_ERROR',
})
).toEqual({
cartArticles: [
aCartArticle({id: '2', name: 'X1 carbon', quantity: 5})
]
})
})
})
describe('handle "RESET CART"', () => {
test('should reset cart', () => {
expect(
cartReducer({
error: 'An error',
cartArticles: [
aCartArticle({id: '2', name: 'X1 carbon', quantity: 5})
]
}, {
type: 'RESET_CART',
})
).toEqual({
cartArticles: []
})
})
})
})
|
e4d82d9fc520883b1b15287e5855755a3bf24c96
|
TypeScript
|
tbilyi/angular-assets-map
|
/src/app/trucks-list/store/trucks-list.reducer.ts
| 2.8125
| 3
|
import { Truck } from '../../shared/truck.model';
import * as TrucksListActions from './trucks-list.actions';
export interface State {
trucks: Truck[],
latitude: number,
longitude: number;
}
const initialState: State = {
trucks: [
new Truck(1, 'Truck 1001', 46.968810, 31.957536),
new Truck(2, 'Truck 1002', 6.923463, 122.078770),
new Truck(3, 'Truck 1003', -34.636551, -58.406627),
new Truck(4, 'Truck 1004', -36.878692, 174.782927),
new Truck(5, 'Truck 1005', 21.317799, -157.863967),
new Truck(6, 'Truck 1006', 33.932971, -118.184870),
new Truck(7, 'Truck 1007', 61.193976, -149.895978),
new Truck(8, 'Truck 1008', 51.469459, -0.121203),
new Truck(9, 'Truck 1009', 19.383402, -99.177722),
new Truck(10, 'Truck 1010', -12.056608, -77.050116),
new Truck(11, 'Truck 1011', -33.440251, -70.659052),
],
latitude: 50.447747,
longitude: 30.501775,
};
export function trucksListReducer(
state: State = initialState,
action: TrucksListActions.TrucksListActions
) {
switch (action.type) {
case TrucksListActions.ADD_TRUCK:
return {
...state,
trucks: [...state.trucks, action.payload]
};
case TrucksListActions.DELETE_TRUCK:
return {
...state,
trucks: state.trucks.filter((ig) => {
return ig.id !== action.payload;
})
};
default:
return state;
}
}
|
7f449b7bdd30e559331f6c3fbd5945660733b45d
|
TypeScript
|
Souler/limbus-providers
|
/src/limbus-provider-kissanimeac/utils/delay.ts
| 2.609375
| 3
|
export default function delay<T>(time: number, arg?: T) {
return new Promise((resolve) => {
setTimeout(resolve, time, arg);
});
}
|
8ce5f611d9cb1c523b9097fc493890b261bd9e44
|
TypeScript
|
nagyg74poc/wp-promotion-server
|
/src/interceptors/response-mapper.interceptor.ts
| 2.5625
| 3
|
import { ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ObjectMapper } from '../mappers/object.mapper';
export interface Response<T> {
data: T;
}
@Injectable()
export class ResponseMapperInterceptor<T> implements NestInterceptor<T, Response<T>> {
constructor(private readonly mapModel: any) {
}
intercept(
context: ExecutionContext,
call$: Observable<T>,
): Observable<Response<T>> {
return call$.pipe(map(data => this.mapObject(data)));
}
private mapObject<T>(data): T {
const result = ObjectMapper.map<T>(data, this.mapModel);
return result;
}
}
|
a3fab311d1e51a1579d24aaaab54b80144dc95ce
|
TypeScript
|
danielgitk/admin-page
|
/src/app/input/link/link.component.ts
| 2.515625
| 3
|
import { Component, Input, OnInit } from '@angular/core';
import { Link } from 'src/app/interfaces';
@Component({
selector: 'input-link',
templateUrl: './link.component.html',
styleUrls: ['./link.component.css']
})
export class LinkComponent implements OnInit {
@Input() defaultValue: false | Link = false;
value: Link = {
target: "_self",
url: "",
title: ""
};
valid = true;
errors: any = {
title: false,
url: false
};
showPicker: boolean = false;
showOpenUrlModel: boolean = false;
ngOnInit() {
if (!this.defaultValue) return;
this.value = this.defaultValue;
}
/**
* Save changes and hide link form
*
* @param url
* @param title
* @param target
*/
saveChanges(url: string, title: string, target: any) {
this.errors = {
title: false,
url: false
};
this.valid = true;
if (!url) {
this.errors.url = "Url is required";
this.valid = false;
}
if (!title) {
this.valid = false;
this.errors.title = "Title is required";
}
if (!this.valid) return;
this.value = {
target: target ? "_blank" : "_self",
url,
title
};
this.showPicker = false;
}
/**
* Toggle link form
*
* @param e
*/
togglePicker(e: any = false) {
if (e) e.preventDefault();
this.showPicker = !this.showPicker;
}
/**
* Toggle open url modal
*
* @param e
*/
toggleUrlModal(e: any = false) {
if (e) {
e.stopPropagation();
e.preventDefault();
}
this.showOpenUrlModel = !this.showOpenUrlModel;
}
}
|
f0935eb7cd0fcbd5a8f5509414f61839e516ed5b
|
TypeScript
|
NJUPT-NYR/SOPT-Frontend
|
/src/utils/tools.ts
| 3.203125
| 3
|
/**
* 用户控制MarkdownEditor的编辑历史
*/
export class SizedHistoryState<T = any> {
private values: T[];
private size: number;
private ptr: number;
private listener: any[];
constructor(size: number, init?: T) {
this.values = [];
this.size = size;
this.ptr = 0;
this.listener = [];
if (init) {
this.values.push(init);
}
}
get value(): T | null {
return this.values[this.ptr] || null;
}
get hasPrev(): boolean {
return !!this.values[this.ptr + 1];
}
get hasNext(): boolean {
return !!this.values[this.ptr - 1];
}
movePrev = () => {
if (this.hasPrev) {
this.ptr += 1;
}
this.listener.forEach((cb) => cb());
};
moveNext = () => {
if (this.hasNext) {
this.ptr -= 1;
}
this.listener.forEach((cb) => cb());
};
append = (value: T) => {
if (this.ptr !== 0) {
this.values.splice(0, this.ptr);
this.ptr = 0;
}
this.values.unshift(value);
if (this.values.length > this.size) {
this.values.pop();
}
};
clear = () => {
this.ptr = 0;
this.values = [];
this.listener.forEach((cb) => cb());
};
subscribe = (callback) => {
this.listener.push(callback);
};
unSubscribe = (callback) => {
this.listener = this.listener.filter((one) => one !== callback);
};
}
export function stringAppendAroundSelection({
str,
selectionStart,
selectionEnd,
startReplacement,
endReplacement,
}: {
str: string;
selectionStart: number | undefined;
selectionEnd: number | undefined;
startReplacement: string;
endReplacement: string;
}): string {
if (typeof selectionStart === "number" && typeof selectionEnd === "number") {
[selectionStart, selectionEnd] = [selectionStart, selectionEnd].sort(
(a, b) => a - b
);
const chars = str.split("");
if (selectionStart === selectionEnd) {
for (let i = selectionStart; i >= 0; i--) {
if (chars[i - 1] === " " || chars[i - 1] === "\n" || i === 0) {
selectionStart = i;
break;
}
}
for (let i = selectionEnd; i <= chars.length; i++) {
if (chars[i] === " " || chars[i] === "\n" || i === chars.length) {
selectionEnd = i;
break;
}
}
}
chars.splice(selectionStart ?? 0, 0, startReplacement);
chars.splice((selectionEnd ?? 0) + 1, 0, endReplacement);
return chars.join("");
}
}
export function stringAppendNextLine({
str,
selectionStart,
replacement,
}: {
str: string;
selectionStart: number;
replacement: string;
}): string {
const chars = str.split("");
for (let i = selectionStart; i < chars.length; i++) {
if (chars[i] === "\n" || i === chars.length - 1) {
selectionStart = i;
break;
}
}
chars.splice((selectionStart ?? 0) + 1, 0, replacement);
return chars.join("");
}
export function stringAppendThisLine({
str,
selectionStart,
replacement,
}: {
str: string;
selectionStart: number;
replacement: string;
}): string {
const chars = str.split("");
for (let i = selectionStart; i >= 0; i--) {
if (chars[i - 1] === "\n" || i === 0) {
selectionStart = i;
break;
}
}
chars.splice(selectionStart ?? 0, 0, replacement);
return chars.join("");
}
export function objectSkipNullOrUndefinedOrEmptyString(obj) {
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if (
obj[key] === undefined ||
obj[key] === null ||
(typeof obj[key] === "string" && obj[key].length === 0)
) {
delete obj[key];
}
}
}
return obj;
}
export function dateFormat(date: Date, format: string) {
if (!date) return undefined;
var o = {
"M+": date.getMonth() + 1, //月份
"d+": date.getDate(), //日
"H+": date.getHours(), //小时
"m+": date.getMinutes(), //分
"s+": date.getSeconds(), //秒
"q+": Math.floor((date.getMonth() + 3) / 3), //季度
"f+": date.getMilliseconds(), //毫秒
};
if (/(y+)/.test(format)) {
format = format.replace(
RegExp.$1,
(date.getFullYear() + "").substr(4 - RegExp.$1.length)
);
}
for (var k in o)
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(
RegExp.$1,
RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
);
}
return format;
}
export function isBrowser(): boolean {
return globalThis.window !== undefined;
}
export class Revalidator<T extends object> {
private activators: WeakMap<T, T[]>;
private listeners: WeakMap<T, (() => void)[]>;
constructor(dependencies: [T, T[]][]) {
this.activators = new WeakMap();
for (const [key, value] of dependencies) {
for (const item of value) {
if (!this.activators.has(item)) {
this.activators.set(item, []);
}
this.activators.get(item).push(key);
}
}
this.listeners = new WeakMap();
}
revalidate(model: T) {
const watchers = this.activators.get(model);
watchers?.forEach((watcher) => {
const callbacks = this.listeners.get(watcher);
callbacks?.forEach((callback) => {
callback();
});
});
}
register(model, callback) {
if (!this.listeners.has(model)) {
this.listeners.set(model, []);
}
this.listeners.get(model).push(callback);
}
revoke(model, callback) {
const callbacks = this.listeners.get(model);
if (callbacks?.length) {
const index = callbacks.findIndex((one) => one === callback);
if (index !== -1) {
callbacks.splice(index, 1);
}
}
}
}
export class Memorizer<TModel extends object> {
private memo: WeakMap<
TModel,
Map<
string,
{ response: undefined; listeners: ((data: any, error: any) => void)[] }
>
>;
private models: WeakSet<TModel>;
constructor(model: TModel[]) {
this.models = new WeakSet(model);
this.memo = new WeakMap();
}
call(fetcher: Function) {
return (model: TModel, param: any) => {
if (!this.models.has(model)) {
return fetcher(model, param);
}
let serializedKey;
try {
serializedKey = JSON.stringify(param);
} catch (_error) {
return fetcher(model, param);
}
if (!this.memo.get(model)) {
this.memo.set(model, new Map());
}
const map = this.memo.get(model);
if (!map.has(serializedKey)) {
map.set(serializedKey, { response: undefined, listeners: [] });
}
const value = map.get(serializedKey);
if (value.listeners.length === 0) {
if (value.response === undefined) {
fetcher(model, param)
.then((data) => {
value.response = data;
value.listeners.forEach((cb) => cb(data, undefined));
})
.catch((error) => {
value.listeners.forEach((cb) => cb(undefined, error));
})
.finally(() => {
value.listeners.splice(0, value.listeners.length);
});
} else {
return value.response;
}
}
return new Promise(async (resolve, reject) => {
value.listeners.push((data, error) => {
if (error) {
reject(error);
} else if (data) {
resolve(data);
}
});
});
};
}
revoke(model: TModel) {
this.memo.delete(model);
}
}
|
8be33dbb07c276c26f8a7dfeba41de71c93aa983
|
TypeScript
|
13club/13club.github.io
|
/codeCu/web_admin_main/src/store/modules/admin.ts
| 2.5625
| 3
|
// import api from 'api/ader'
interface breadCrumbM{
path:string
title:string
}
interface stateM{
breadCrumb: object[] // 面包屑导航,
active:string //当前活动页
}
// initial state
const state:stateM = {
breadCrumb: [],
active:'',
}
// getters
const getters = {
breadCrumb: state => state.breadCrumb,
collapseMenu: state => state.collapseMenu
}
// actions
const actions = {
/* 设置主题部分标题 */
setBreadCrumb(state: any, breadCrumb: breadCrumbM) {
this.commit('setBreadCrumb', breadCrumb)
},
/* 富文本排序加一 */
addUeSort(state: any) {
this.commit('setBreadCrumb')
},
/* 设置当前页 --激活页*/
setActive(state: any,val:string){
this.commit('setActive',val)
}
}
// mutations
const mutations = {
setBreadCrumb(state: any, breadCrumb: breadCrumbM) {
state.breadCrumb = breadCrumb
},
/* 设置主题部分标题 */
addUeSort(state: any) {
state.ueSort += 1
},
/* 设置当前页 --激活页*/
setActive(state: any,val:string){
state.active = val
}
}
export default {
state,
getters,
actions,
mutations
}
|
017ffb76c4d3c972ccc82d071545a59ab488abc8
|
TypeScript
|
june2/banking-app
|
/api-server-node-typescript/src/api/user/user.service.ts
| 2.640625
| 3
|
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { UpdateResult, DeleteResult } from 'typeorm';
import { User } from './user.entity';
import { UserRepository } from './user.repository';
import { CreateUserDto, UpdateUserDto } from './user.dto'
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private readonly userRepository: UserRepository,
) { }
async create(createUserDto: CreateUserDto): Promise<User> {
const entity = Object.assign(new User(), createUserDto);
return await this.userRepository.save(entity);
}
async findAll(): Promise<User[]> {
return await this.userRepository.find();
}
async findById(id: number, ): Promise<User> {
return await this.userRepository.findOne({ where: { id: id } });
}
async findByEmailAndPass(email: string, password: string): Promise<User> {
return await this.userRepository.findByEmailAndPass(email, password);
}
async update(id: number, updateUserDto: UpdateUserDto): Promise<UpdateResult> {
return await this.userRepository.update(id, updateUserDto);
}
// async delete(id: number, updateUserDto: UpdateUserDto): Promise<UpdateResult> {
// return await this.userRepository.d
// }
}
|
af21ca8946df49a2e769498b42792d693a999389
|
TypeScript
|
CN-Shopkeeper/vue3-ts-cms
|
/src/service/request/config.ts
| 2.515625
| 3
|
// 1.手动修改
// 2.根据process.env.NODE_ENV
// 开发环境:development
// 生产环境:production
// 测试环境:test
let BASE_URL = "";
const TIME_OUT = 10000;
if (process.env.NODE_ENV === "development") {
BASE_URL = "/api";
} else if (process.env.NODE_ENV === "production") {
BASE_URL = "http://152.136.185.210:5000";
} else {
BASE_URL = "http://152.136.185.210:5000";
}
export { TIME_OUT, BASE_URL };
// 3.在根目录中创建环境变量
// .env .env.development .env.test
// 一般使用第二种
|
25d272630505a49c522e3bc241c8a992bb91add1
|
TypeScript
|
nrfm/umbrella
|
/packages/shader-ast-stdlib/src/sdf/plane.ts
| 2.828125
| 3
|
import { defn, ret } from "@thi.ng/shader-ast/ast/function";
import { add } from "@thi.ng/shader-ast/ast/ops";
import { dot } from "@thi.ng/shader-ast/builtin/math";
/**
* Returns signed distance from `p` to plane defined by `normal` and `w`.
*
* @param p - vec2
* @param normal - vec2
* @param w - float
*/
export const sdfPlane2 = defn(
"float",
"sdPlane2",
["vec2", "vec2", "float"],
(p, n, w) => [ret(add(dot(p, n), w))]
);
/**
* Returns signed distance from `p` to plane defined by `normal` and `w`.
*
* @param p - vec3
* @param normal - vec3
* @param w - float
*/
export const sdfPlane3 = defn(
"float",
"sdPlane3",
["vec3", "vec3", "float"],
(p, n, w) => [ret(add(dot(p, n), w))]
);
|
04904cbbdb107af7ca0296f935bb98a1ab5e549f
|
TypeScript
|
DNSLV-PMTKV/TravelProject-web
|
/src/redux/users/userReducer.ts
| 3.03125
| 3
|
import { setAuthenticated, SET_AUTHENTICATED } from './userActions';
export interface UserState {
isAuthenticated: boolean;
}
export const InitialState: UserState = {
isAuthenticated: false
};
type Action = setAuthenticated;
export const userReducer = (state: UserState = InitialState, action: Action): UserState => {
switch (action.type) {
case SET_AUTHENTICATED:
return {
...state,
isAuthenticated: action.value
};
default:
return state;
}
};
|
71086811fa05182980179346ba4e23c9f78311c4
|
TypeScript
|
PHPCraftdream/ReactTypescriptReduxSassChallenge
|
/src/Core/Types.ts
| 2.765625
| 3
|
import { FetchError } from "node-fetch";
import { DetailedHTMLProps, InputHTMLAttributes } from "react";
type TReactRenderA = React.ReactElement<any, string | React.JSXElementConstructor<any>>;
type TReactRenderB = React.ReactNodeArray | React.ReactPortal | React.ReactFragment;
export type TRender = TReactRenderA | TReactRenderB | null | undefined;
export enum EAsyncStatus {
PROCESSING = "PROCESSING",
SUCCESS = "SUCCESS",
ERROR = "ERROR",
}
export interface IAsyncData<DataType> {
data?: DataType | null;
error?: FetchError;
status: EAsyncStatus;
}
export interface IHTMLInputElementType
extends DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement> {
}
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
export interface IHTMLInputElementProps extends Omit<IHTMLInputElementType, "onChange" | "value"> {
addClassName?: string;
className?: string;
initialValue?: string;
value?: string;
onChange?: TOnChangeFunc;
}
/**
* false - не обновлять
* string - установить значения
* true | void | undefined | null - обновить
*/
export type TOnChangeResult = boolean | string | void | undefined | null;
export type TOnChangeFunc = (value: string, name?: string) => TOnChangeResult;
export interface IDictionary<T> {
[key: string]: T;
}
|
10fc13c3fd5e4161d725d237555a212349eec25c
|
TypeScript
|
EduardQV/charge-point-app
|
/test/services/charge-point.service.spec.ts
| 2.703125
| 3
|
import { CallbackError, Query } from 'mongoose';
import ChargePoint, { IChargePoint, IStatus } from '../../src/api/models/charge-point.model';
import ChargePointService from '../../src/api/services/charge-point.service';
describe('Unit test for ChargePointService', () => {
const service = new ChargePointService();
describe('Unit test for save function', () => {
const saveSpy = jest.spyOn(ChargePoint.prototype, 'save');
describe('Given ChargePoint', () => {
const chargePoint: IChargePoint = { name: 'name' };
describe('When successfully saved into the database', () => {
const expectedChargePoint: IChargePoint = {
id: 1,
name: 'name',
status: IStatus.READY,
created_at: new Date()
};
beforeEach(() => {
saveSpy.mockImplementationOnce(() => Promise.resolve(expectedChargePoint));
});
it('Then return the saved ChargePoint', async () => {
const response = await service.save(chargePoint);
expect(response).toEqual(expectedChargePoint);
});
});
describe('When an error occurs', () => {
const expectedError: CallbackError = { name: 'errorName', message: 'Error message' };
beforeEach(() => {
saveSpy.mockImplementationOnce(() => Promise.reject(expectedError));
});
it('Then return status 500 with the error message', async () => {
try {
await service.save(chargePoint);
} catch (err) {
expect(err).toEqual({ status: 500, message: expectedError.message });
}
});
});
});
});
describe('Unit test for deleteById function', () => {
const findByIdAndUpdateSpy = jest.spyOn(ChargePoint, 'findByIdAndUpdate');
describe('Given id', () => {
const reqId = 2;
const dateMock = new Date();
beforeEach(() => {
spyOn(global, 'Date').and.callFake(() => {
return dateMock;
});
});
describe('When a ChargePoint is deleted', () => {
const queryResponse: IChargePoint = {
id: 1,
name: 'name',
status: IStatus.READY,
created_at: new Date(),
deleted_at: dateMock
};
beforeEach(() => {
jest.spyOn(Query.prototype, 'exec').mockReturnValue(Promise.resolve(queryResponse));
});
it('Then resolve promise', async () => {
await service.deleteById(reqId);
expect(findByIdAndUpdateSpy).toHaveBeenCalledWith(reqId, { deleted_at: dateMock });
});
});
describe('When a ChargePoint is NOT found', () => {
beforeEach(() => {
jest.spyOn(Query.prototype, 'exec').mockReturnValue(Promise.resolve(null));
});
it('Then return status 404 with the error message', async () => {
try {
await service.deleteById(reqId);
} catch (err) {
expect(findByIdAndUpdateSpy).toHaveBeenCalledWith(reqId, { deleted_at: dateMock });
expect(err).toEqual({ status: 404, message: `No ChargePoint found with ID: ${reqId}` });
}
});
});
describe('When an error occurs', () => {
const expectedError: CallbackError = { name: 'errorName', message: 'Error message' };
beforeEach(() => {
jest.spyOn(Query.prototype, 'exec').mockReturnValue(Promise.reject(expectedError));
});
it('Then return status 500 with the error message', async () => {
try {
await service.deleteById(reqId);
} catch (err) {
expect(findByIdAndUpdateSpy).toHaveBeenCalledWith(reqId, { deleted_at: dateMock });
expect(err).toEqual({ status: 500, message: expectedError.message });
}
});
});
});
});
describe('Unit test for findById function', () => {
const findByIdSpy = jest.spyOn(ChargePoint, 'findById');
describe('Given id', () => {
const reqId = 2;
describe('When a ChargePoint is found', () => {
const expectedChargePoint: IChargePoint = {
id: 1,
name: 'name',
status: IStatus.READY,
created_at: new Date()
};
beforeEach(() => {
jest.spyOn(Query.prototype, 'exec').mockReturnValue(Promise.resolve(expectedChargePoint));
});
it('Then return the ChargePoint', async () => {
const response = await service.findById(reqId);
expect(findByIdSpy).toHaveBeenCalledWith(reqId);
expect(response).toEqual(expectedChargePoint);
});
});
describe('When a ChargePoint is NOT found', () => {
beforeEach(() => {
jest.spyOn(Query.prototype, 'exec').mockReturnValue(Promise.resolve(null));
});
it('Then return status 404 with the error message', async () => {
try {
await service.findById(reqId);
} catch (err) {
expect(findByIdSpy).toHaveBeenCalledWith(reqId);
expect(err).toEqual({ status: 404, message: `No ChargePoint found with ID: ${reqId}` });
}
});
});
describe('When an error occurs', () => {
const expectedError: CallbackError = { name: 'errorName', message: 'Error message' };
beforeEach(() => {
jest.spyOn(Query.prototype, 'exec').mockReturnValue(Promise.reject(expectedError));
});
it('Then return status 500 with the error message', async () => {
try {
await service.findById(reqId);
} catch (err) {
expect(findByIdSpy).toHaveBeenCalledWith(reqId);
expect(err).toEqual({ status: 500, message: expectedError.message });
}
});
});
});
});
describe('Unit test for findAll function', () => {
const findSpy = jest.spyOn(ChargePoint, 'find');
describe('Given nothing', () => {
describe('When ChargePoints is found', () => {
const expectedChargePoint: Array<IChargePoint> = [
{
id: 1,
name: 'name',
status: IStatus.READY,
created_at: new Date()
}
];
beforeEach(() => {
jest.spyOn(Query.prototype, 'exec').mockReturnValue(Promise.resolve(expectedChargePoint));
});
it('Then return the ChargePoints', async () => {
const response = await service.findAll();
expect(findSpy).toHaveBeenCalled();
expect(response).toEqual(expectedChargePoint);
});
});
describe('When ChargePoints is NOT found', () => {
beforeEach(() => {
jest.spyOn(Query.prototype, 'exec').mockReturnValue(Promise.resolve([]));
});
it('Then return status 404 with the error message', async () => {
try {
await service.findAll();
} catch (err) {
expect(findSpy).toHaveBeenCalledWith();
expect(err).toEqual({ status: 404, message: 'No ChargePoints found.' });
}
});
});
describe('When an error occurs', () => {
const expectedError: CallbackError = { name: 'errorName', message: 'Error message' };
beforeEach(() => {
jest.spyOn(Query.prototype, 'exec').mockReturnValue(Promise.reject(expectedError));
});
it('Then return status 500 with the error message', async () => {
try {
await service.findAll();
} catch (err) {
expect(findSpy).toHaveBeenCalledWith();
expect(err).toEqual({ status: 500, message: expectedError.message });
}
});
});
});
});
describe('Unit test for updateStatus function', () => {
const findOneAndUpdateSpy = jest.spyOn(ChargePoint, 'findOneAndUpdate');
beforeEach(() => {
findOneAndUpdateSpy.mockClear();
});
describe('Given valid ChargePoint', () => {
const req: IChargePoint = {
id: 2,
name: 'name',
status: IStatus.READY
};
describe('When call to db', () => {
const queryResponse: IChargePoint = {
id: 1,
name: 'name',
status: IStatus.READY
};
beforeEach(() => {
jest.spyOn(Query.prototype, 'exec').mockReturnValue(Promise.resolve(queryResponse));
});
it('Then send the query with the request data', async () => {
await service.updateStatus(req);
expect(findOneAndUpdateSpy).toHaveBeenCalledWith(
{ _id: req.id, name: req.name },
{ status: req.status },
{ omitUndefined: true, new: true }
);
});
});
describe('When a ChargePoint is updated', () => {
const queryResponse: IChargePoint = {
id: 1,
name: 'name',
status: IStatus.READY
};
beforeEach(() => {
jest.spyOn(Query.prototype, 'exec').mockReturnValue(Promise.resolve(queryResponse));
});
it('Then return updated ChargePoint', async () => {
const result = await service.updateStatus(req);
expect(findOneAndUpdateSpy).toHaveBeenCalled();
expect(result).toEqual(queryResponse);
});
});
describe('When a ChargePoint is NOT found', () => {
beforeEach(() => {
jest.spyOn(Query.prototype, 'exec').mockReturnValue(Promise.resolve(null));
});
it('Then return status 404 with the error message', async () => {
try {
await service.updateStatus(req);
} catch (err) {
expect(findOneAndUpdateSpy).toHaveBeenCalled();
expect(err).toEqual({
status: 404,
message: 'No ChargePoint was found with this data.'
});
}
});
});
describe('When an error occurs', () => {
const expectedError: CallbackError = { name: 'errorName', message: 'Error message' };
beforeEach(() => {
jest.spyOn(Query.prototype, 'exec').mockReturnValue(Promise.reject(expectedError));
});
it('Then return status 500 with the error message', async () => {
try {
await service.updateStatus(req);
} catch (err) {
expect(findOneAndUpdateSpy).toHaveBeenCalled();
expect(err).toEqual({ status: 500, message: expectedError.message });
}
});
});
});
describe('Given ChargePoint without query information', () => {
const req: IChargePoint = {
status: IStatus.READY
};
describe('When build the query', () => {
it('Then return the status and message error', async () => {
try {
await service.updateStatus(req);
} catch (err) {
expect(findOneAndUpdateSpy).not.toHaveBeenCalled();
expect(err).toEqual({ status: 404, message: 'Invalid query data.' });
}
});
});
});
});
});
|
04c3c82f7bf12cf16af22546b6788b9016b7d705
|
TypeScript
|
swc-project/swc
|
/crates/swc_bundler/tests/.cache/deno/f6b67896830a42fe1517a5f9c1bc677006d5472e.ts
| 3.5
| 4
|
// Loaded from https://deno.land/x/ramda@v0.27.2/source/invoker.js
import _curry2 from './internal/_curry2.js';
import _isFunction from './internal/_isFunction.js';
import curryN from './curryN.js';
import toString from './toString.js';
/**
* Turns a named method with a specified arity into a function that can be
* called directly supplied with arguments and a target object.
*
* The returned function is curried and accepts `arity + 1` parameters where
* the final parameter is the target object.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig Number -> String -> (a -> b -> ... -> n -> Object -> *)
* @param {Number} arity Number of arguments the returned function should take
* before the target object.
* @param {String} method Name of any of the target object's methods to call.
* @return {Function} A new curried function.
* @see R.construct
* @example
*
* const sliceFrom = R.invoker(1, 'slice');
* sliceFrom(6, 'abcdefghijklm'); //=> 'ghijklm'
* const sliceFrom6 = R.invoker(2, 'slice')(6);
* sliceFrom6(8, 'abcdefghijklm'); //=> 'gh'
*
* const dog = {
* speak: async () => 'Woof!'
* };
* const speak = R.invoker(0, 'speak');
* speak(dog).then(console.log) //~> 'Woof!'
*
* @symb R.invoker(0, 'method')(o) = o['method']()
* @symb R.invoker(1, 'method')(a, o) = o['method'](a)
* @symb R.invoker(2, 'method')(a, b, o) = o['method'](a, b)
*/
var invoker = _curry2(function invoker(arity, method) {
return curryN(arity + 1, function() {
var target = arguments[arity];
if (target != null && _isFunction(target[method])) {
return target[method].apply(target, Array.prototype.slice.call(arguments, 0, arity));
}
throw new TypeError(toString(target) + ' does not have a method named "' + method + '"');
});
});
export default invoker;
|
033211f9753b38569b0cbdbc08c246460f0af5e7
|
TypeScript
|
iraamaro/vtex-node-sdk
|
/src/utils/VtexHttpResponse.ts
| 2.921875
| 3
|
import { IncomingHttpHeaders } from "http";
export class VtexHttpResponse<T = any> {
/**
* Response status
*/
readonly status: number;
/**
* Response body
*/
readonly body: T;
/**
* Response headers
*/
readonly headers: IncomingHttpHeaders;
/**
* @param {number} status
* @param {T} body
* @param {IncomingHttpHeaders} headers
*/
constructor(status: number, body: T, headers: IncomingHttpHeaders) {
this.status = status;
this.body = body;
this.headers = headers;
}
}
|
62aaf7229f13f397c1d2f4e8bfb61ac942f26bad
|
TypeScript
|
vibrunazo/gengarbobo
|
/src/app/shared/minmax.directive.ts
| 2.625
| 3
|
import { Attribute, Directive, forwardRef, Input, OnChanges, SimpleChanges, Provider, NgModule } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, FormControl } from '@angular/forms';
export const MIN_VALUE_VALIDATOR: any = {
provide: NG_VALIDATORS,
// tslint:disable-next-line: no-use-before-declare
useExisting: forwardRef(() => MinValueValidator),
multi: true
};
@Directive({
// tslint:disable-next-line: directive-selector
selector: '[min][formControlName],[min][formControl],[min][ngModel]',
providers: [MIN_VALUE_VALIDATOR],
// tslint:disable-next-line: no-host-metadata-property
host: { '[attr.min]': 'min ? min : 0' }
})
export class MinValueValidator implements Validator, OnChanges {
constructor(@Attribute('min') mn: string) {
if (mn !== undefined && mn !== null) {
// isPresent
const attrValue = parseInt(mn, 10);
if (!isNaN(attrValue)) {
this.min = mn;
this._createValidator();
}
}
}
// tslint:disable-next-line: variable-name
private _validator: ValidatorFn;
@Input() min: string;
static min(mn: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
const v = +control.value;
return v < mn ? { min: { minValue: mn, actualValue: v } } : null;
};
}
ngOnChanges(changes: SimpleChanges) {
const minChange = changes.min;
if (minChange) {
this._createValidator();
}
}
private _createValidator() {
this._validator = MinValueValidator.min(parseInt(this.min, 10));
}
validate(c: AbstractControl): { [key: string]: any } {
return this._validator(c);
}
}
export const MAX_VALUE_VALIDATOR: any = {
provide: NG_VALIDATORS,
// tslint:disable-next-line: no-use-before-declare
useExisting: forwardRef(() => MaxValueValidator),
multi: true
};
@Directive({
// tslint:disable-next-line: directive-selector
selector: '[max][formControlName],[min][formControl],[min][ngModel]',
providers: [MAX_VALUE_VALIDATOR],
// tslint:disable-next-line: no-host-metadata-property
host: { '[attr.max]': 'max ? max : 0' }
})
export class MaxValueValidator implements Validator, OnChanges {
constructor(@Attribute('max') mx: string) {
if (mx !== undefined && mx !== null) {
// isPresent
const attrValue = parseInt(mx, 10);
if (!isNaN(attrValue)) {
this.max = mx;
this._createValidator();
}
}
}
// tslint:disable-next-line: variable-name
private _validator: ValidatorFn;
@Input() max: string;
static max(mx: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
const v = +control.value;
return v > mx ? { max: { maxValue: mx, actualValue: v } } : null;
};
}
ngOnChanges(changes: SimpleChanges) {
const maxChange = changes.max;
if (maxChange) {
this._createValidator();
}
}
private _createValidator() {
this._validator = MaxValueValidator.max(parseInt(this.max, 10));
}
validate(c: AbstractControl): { [key: string]: any } {
return this._validator(c);
}
}
|
c87dec02a0a8e456969ce947ca69d60e1571490b
|
TypeScript
|
green-fox-academy/alexfrenkel92
|
/week-04/4. nap/anagram.ts
| 3.3125
| 3
|
'use strict';
export function anagram (word1: string, word2: string) {
if (word1.split('').sort() !== word2.split('').sort()) {
console.log('Lucky boyyyy, it is an anagram!');
} else {
console.log('You are out of luck, it is not an anagram.');
}
}
anagram('alex', 'lexa');
|
343edcd14d7be22eb8c621bcd2307ac0425c1873
|
TypeScript
|
brooksbecton/cah
|
/client/src/game/utils/getRandomInt.ts
| 3.328125
| 3
|
/**
* Returns a random integer below the max provided
*/
function getRandomInt(max = 0) {
if (max !== 0) {
return Math.floor(Math.random() * Math.floor(max));
} else {
throw new Error(`Error: ${max} passed to getRandomInt`);
}
}
export default getRandomInt;
|
b8a92b6593d81886129962ab87d942f29f102c68
|
TypeScript
|
wt2209/qingwu-apartment
|
/src/pages/living/rooms/data.d.ts
| 2.671875
| 3
|
export interface RoomListItem {
id: number;
roomName: string;
building: string;
unit: string;
rent: number; // 房间的默认租金,如承包商公寓的房间租金。入住时,可使用此租金,也可自定义新租金
number: number; // 最大人数
remark: string; // 房间备注
status?: 'show' | 'hide'; // 是否在主页面中显示
}
export interface RoomFormValueType {
id: number;
roomName: string;
building: string;
unit: string;
number: number | undefined;
rent: number | undefined;
remark: string;
}
|
2b654c977f98f2cd9ff84803978d16fc246e882a
|
TypeScript
|
JakeStanger/ts-docs
|
/src/searchData.ts
| 2.9375
| 3
|
import { ClassProperty, Project } from "@ts-docs/extractor";
import fs from "fs";
import { getComment } from "./utils";
/**
* Used for the [[packSearchData]] function.
*/
export const enum ClassMemberFlags {
IS_GETTER = 1 << 0,
IS_SETTER = 1 << 1,
IS_PRIVATE = 1 << 2
}
function buildBitfield(...bits: Array<number|undefined|false>) : number {
return (bits.filter(bit => bit) as Array<number>).reduce((acc, bit) => acc | bit, 0);
}
export type SearchDataComment = string|undefined;
export type PackedSearchData = [
Array<[
number, // Module ID,
Array<[string, Array<[string, number, SearchDataComment]>, Array<[string, number, SearchDataComment]>, Array<number>, SearchDataComment]>, // Classes
Array<[string, Array<string>, Array<number>, SearchDataComment]>, // Interfaces,
Array<[string, Array<string>, Array<number>, SearchDataComment]>, // Enums,
Array<[string, Array<number>]>, // Types
Array<[string, Array<number>]>, // Functions
Array<[string, Array<number>]> // Constants
]>,
Array<string> // Module names
];
/**
* Packs the data in a convinient, small format. Unlike the default strucutre provided by ts-extractor, this packed structure only registers the "global"
* modules and includes all of the sub-module's things (classes, interfaces, etc.).
*
* Returns an array which looks something like this:
* `[globalModules, allModuleNames];`
*
* globalModules is an [[Array]] of module objects, which look like this:
* `[nameIndex, classes, interfaces, enums, types, functions, constants]`
*
* a **class**: `[name, properties, methods, path, comment?]`
* a **method**: `[name, flags, comment?]`
* a **property**: `[name, flags, comment?]`
* an **inteface**: `[name, properties, path, comment?]`
* an **enum**: `[name, members, path, comment?]`
* a **type alias**: `[name, path]`
* a **function**: `[name, path]`
* a **constant**: `[name, path]`
*
*
* `flags` is a bitfield containing [[ClassMemberFlags]]
* `path` is an array of numbers, which are the indexes of the module names inside the `allModuleNames` array. Since module names repeat very often, they're all placed in one array (`allModuleNames`) to save space.
*
* Also check out [[PackedSearchData]]
*
*/
export function packSearchData(extractors: Array<Project>, path: string) : void {
const res = [[], []] as PackedSearchData;
const notSingleExtractor = extractors.length !== 1;
for (const extractor of extractors) {
const modObj = [0,[],[],[],[],[],[]] as PackedSearchData[0][0];
extractor.forEachModule(extractor.module, (mod, path) => {
modObj[0] = res[1].push(mod.name) - 1;
const numPath = path.map(pathName => res[1].indexOf(pathName));
for (const cl of mod.classes) modObj[1].push([`${cl.name}${cl.id ? `_${cl.id}`:""}`, cl.properties.filter(p => !("key" in p)).map(p => [(p as ClassProperty).name, buildBitfield((p as ClassProperty).isPrivate && ClassMemberFlags.IS_PRIVATE), getComment(p as ClassProperty)]), cl.methods.map(p => [p.realName || (p.name as string), buildBitfield(p.isGetter && ClassMemberFlags.IS_GETTER, p.isSetter && ClassMemberFlags.IS_SETTER, p.isPrivate && ClassMemberFlags.IS_PRIVATE), getComment(p)]), numPath, getComment(cl)]);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
for (const intf of mod.interfaces) modObj[2].push([`${intf.name}${intf.id ? `_${intf.id}`:""}`, intf.properties.filter(p => p.prop).map(p => p.prop!.name), numPath, getComment(intf)]);
for (const en of mod.enums) modObj[3].push([`${en.name}${en.id ? `_${en.id}`:""}`, en.members.map(m => m.name), numPath, getComment(en)]);
for (const typ of mod.types) modObj[4].push([`${typ.name}${typ.id ? `_${typ.id}`:""}`, numPath]);
for (const fn of mod.functions) modObj[5].push([`${fn.name}${fn.id ? `_${fn.id}`:""}`, numPath]);
for (const constant of mod.constants) modObj[6].push([`${constant.name}${constant.id ? `_${constant.id}`:""}`, numPath]);
}, notSingleExtractor ? [extractor.module.name] : []);
res[0].push(modObj);
}
fs.writeFileSync(path, JSON.stringify(res));
}
|
d3d5b9ae8801101c3bd356572f28d4172bae9587
|
TypeScript
|
vladimir-ivanov/ngrx-store-example
|
/src/app/shared/error-overlay/reducers/error-overlay.reducer.ts
| 2.734375
| 3
|
import {APP_ERROR} from "../errror-overlay.actions";
export interface State {
errorMessage: string;
}
export const initialState: State = {
errorMessage: ''
};
export function reducer(state = initialState,
action: any): State {
switch (action.type) {
case APP_ERROR: {
return {
errorMessage: action.payload
};
}
default: {
return state;
}
}
}
export const getErrorMessage = (state: State) => state.errorMessage;
|
dc75fc9791bfebcae7c26db1609841db6b864b09
|
TypeScript
|
FeldmanMatan/FinalProject
|
/src/app/services/window-day-off.service.ts
| 2.578125
| 3
|
// import { Injectable } from '@angular/core';
// @Injectable({
// providedIn: 'root'
// })
// export class WindowDayOffService {
// constructor() { }
// }
import { Injectable } from "@angular/core";
@Injectable({
providedIn: "root"
})
export class WindowsDaysOffService {
windows_importance: number = 3;
windows_string: string = String(this.windows_importance);
days_off_importance: number = 8;
days_off_string: string = String(this.days_off_importance);
constructor() {}
set_windows_importance(importance: number) {
this.windows_importance = importance;
this.windows_string = String(importance);
console.log("windows importance:", this.windows_importance);
}
set_daysoff_importance(importance: number) {
this.days_off_importance = importance;
this.days_off_string = String(importance);
console.log("daysoff importance:", this.days_off_importance);
}
}
|
d1e4a99d9bdd6f447762f7fce1f0b13b56ff9a0c
|
TypeScript
|
anshnagrath/ionic-recepieapp
|
/src/services/shopping-list.ts
| 2.609375
| 3
|
import { Ingridents } from '../models/ingrident';
export class ShoppingListService {
private ingridents: Ingridents[] = [];
addItem(name: string, amount: number) {
this.ingridents.push(new Ingridents(name, amount));
}
addItems(items: Ingridents[]) {
this.ingridents.push(...items);
}
getItems() {
return this.ingridents.slice();
}
removeItem(index: number) {
this.ingridents.splice(index, 1)
}
}
|
3aca1555f28a7c93c4a2385dc0ca6b836fa24b2b
|
TypeScript
|
fabremx/gameru
|
/src/objects/dialogBox.ts
| 2.96875
| 3
|
import { IDialogConstructor } from "../interfaces/text.interface";
export default class DialogBox {
private box: Phaser.GameObjects.Rectangle;
private scene: Phaser.Scene;
private dialogs: string[];
private currentText: Phaser.GameObjects.Text;
/** Variables when reading dialogs */
private letterCounter: number = 0;
private currentDialogIndex: number = 0;
/** Interval for writing text effect */
private textInterval: any;
constructor({ scene, dialogs }: IDialogConstructor) {
this.scene = scene
this.dialogs = dialogs;
}
async display() {
const MARGIN_LEFT = 50;
const MARGIN_TOP = this.scene.scale.height - 250
const WIDTH = (this.scene.cameras.main.width - (MARGIN_LEFT * 2));
const HEIGHT = 230;
const PADDING_LEFT = 50;
const PADDING_TOP = 30;
this.box = this.scene.add.rectangle(
(this.scene.cameras.main.scrollX + MARGIN_LEFT),
(this.scene.cameras.main.scrollY + MARGIN_TOP),
WIDTH,
HEIGHT,
0xff0000
).setOrigin(0).setDepth(10)
this.currentText = this.scene.add.text(this.box.x + PADDING_LEFT, this.box.y + PADDING_TOP, '', {
color: 'White',
fontFamily: 'Georgia, "Goudy Bookletter 1911", Times, serif',
fontSize: '32px'
}).setWordWrapWidth(WIDTH - (PADDING_LEFT * 2))
this.currentText.setDepth(11)
// Begin with first line, other line will be triggered by handleSkip method
this.readLine(this.dialogs[0]);
}
async readLine(dialog: string) {
this.letterCounter = 0;
this.textInterval = setInterval((() => {
const isAllLineRendered = (this.letterCounter >= dialog.length);
// When text is entierely rendered, waiting for user action
if (isAllLineRendered) {
clearInterval(this.textInterval);
return;
}
this.currentText.text += dialog[this.letterCounter]
this.letterCounter += 1;
}).bind(this), 80);
}
handleSkip() {
const currentDialog: string = this.dialogs[this.currentDialogIndex];
const isAllLineRendered: boolean = (this.letterCounter === currentDialog.length);
if (!isAllLineRendered) {
return this.renderAllDialog();
}
if (isAllLineRendered) {
const isLastDialogEnded = this.currentDialogIndex >= this.dialogs.length - 1;
return isLastDialogEnded
? this.endDialog()
: this.readNextDialog();
}
}
private renderAllDialog() {
clearInterval(this.textInterval);
const currentDialog: string = this.dialogs[this.currentDialogIndex];
this.currentText.text = currentDialog;
this.letterCounter = currentDialog.length;
}
private endDialog() {
this.scene.events.emit('END_DIALOG');
this.destroy();
}
private readNextDialog() {
this.currentDialogIndex += 1;
this.currentText.text = '';
this.readLine(this.dialogs[this.currentDialogIndex]);
}
destroy() {
this.box.destroy()
this.currentText.destroy();
}
}
|
448ed6be535f962dbf0374c66d434a68f5811505
|
TypeScript
|
dshubhadeep/veza
|
/src/lib/Util/Header.ts
| 3.140625
| 3
|
function getBytes(number: number) {
const result = [];
while (number >= 1) {
result.unshift(Math.floor(number) % 0xff);
number /= 0xff;
}
return result;
}
function parseBytes(bytes: number[]) {
let number = 0;
let n = 1;
for (let i = bytes.length - 1; i >= 0; i--) {
number += bytes[i] * n;
n *= 0xff;
}
return number;
}
function fill(bytes: number[], length: number) {
if (bytes.length < length) { for (let i = length - bytes.length; i > 0; i--) bytes.unshift(0); }
return bytes;
}
function createHeader(
id: string,
type: number,
receptive: any,
length: number
) {
return Buffer.concat([
Buffer.from(id, 'base64'),
Buffer.from([type, receptive ? 1 : 0, ...fill(getBytes(length), 4)])
]);
}
function readHeader(header: any) {
return {
id: header.toString('base64', 0, 7),
type: header[7],
receptive: Boolean(header[8]),
length: parseBytes(header.slice(9, 13))
};
}
let a = 0;
function createID() {
a = a < 0xffff ? a + 1 : 0;
return Buffer.from(getBytes(Date.now()).concat(a)).toString('base64');
}
export default Object.freeze({ createHeader, readHeader, createID });
|
1bfdcd09fa6790b295656c2e0874fcd882896668
|
TypeScript
|
YalongYan/scan-statistics
|
/dist/index.d.ts
| 2.71875
| 3
|
interface propTypes {
email: string;
userName: string;
requestUrl?: string;
browserUrl: string;
env: string;
platform: string;
}
/**
*
* @param obj 请求的参数 包含 email、userName、requestUrl、browserUrl、env、platform; 其中 requestUrl 非必传,其他都是必传的
* @param url 请求要使用的接口地址,默认是本地的服务地址
* @returns
*/
declare const handleStatisticsRequest: (obj: propTypes, url?: string) => void;
export default handleStatisticsRequest;
|
42f944270235e660768c40bd66aeebdaa3196b8c
|
TypeScript
|
Pasakinskas/book-app
|
/src/models/userModel.ts
| 2.734375
| 3
|
import mongoose from "mongoose";
import validator from "validator";
export interface User extends mongoose.Document {
email: string;
password: string;
}
const schema = new mongoose.Schema({
email: {
type: String,
required: true,
unique: true,
validate: (value: string) => {
return validator.isEmail(value)
}
},
password: { type: String, required: true },
});
export const UserModel = mongoose.model<User>('User', schema);
|
ebd76b385c601be7353d1573c50305c9a2a09bed
|
TypeScript
|
yingshaoxo/Let-s-become-a-master-of-Vue3
|
/src/functions.ts
| 2.671875
| 3
|
import { reactive } from "vue";
export const doesTheyTwoEqual = (a: any, b: any) => {
return a === b
}
export const theGlobalReactiveObject = reactive({
data: {
mood: "",
},
functions: {
changeTheMood: (mood: string) => {
theGlobalReactiveObject.data.mood = mood
},
},
})
export const unreactive = (obj: any) => {
return JSON.parse(JSON.stringify(obj))
}
|
d8459266c629f90a36a84454d4d0d3ab87c80448
|
TypeScript
|
rooneyshuman/Battlecode
|
/src/Nav.ts
| 2.59375
| 3
|
import { availableLoc, manhatDist, horizontalFlip, simplePathFinder } from "./utils";
export function checkerBoardMovement(self: any) {
const formation: number[][] =
[[-1, -1],
[1, -1],
[1, 1],
[-1, 1]];
if (self.checkerBoardSpot === undefined) {
self.checkerBoardSpot = firstSpot(self);
}
if (self.map[self.destination[1]][self.destination[0]] === false) {
self.log("DESTINATION IMPASSABLE" + " " + self.destination);
return null;
}
const visionMap = self.getVisibleRobotMap();
self.log("SELF.DESTINATION:::::" + self.destination);
self.log("visionMap " + visionMap[self.destination[1]][self.destination[0]]);
if (self.me.x === self.destination[0] && self.me.y === self.destination[1]) {
self.log("AT DESTINATION");
return null;
}
else if (visionMap[self.destination[1]][self.destination[0]] > 0) {
const firstX = self.destination[0];
const firstY = self.destination[1];
self.visitedBots.push(visionMap[firstY][firstX]);
let i;
for (i = 0; i < 4; ++i) {
const newX = firstX + formation[i][0];
const newY = firstY + formation[i][1];
// Make sure unit is also not going to a karbonite or fuel tile
let resourceCheck = true;
if (self.karbonite_map[newY][newX] === true || self.fuel_map[newY][newX] === true) { resourceCheck = false; }
// Make sure that it is not too close to the CASTLE
const dist = manhatDist(self.friendlyCastleLoc[0], [newX, newY]);
let distCheck = true;
if (dist < 3) { distCheck = false; }
if (newX < 0 || newY < 0) { continue; }
if (visionMap[newY][newX] === 0 && self.map[newY][newX] === true && resourceCheck === true && distCheck === true) {
self.log("HELLLLOOOOOO : : : " + newX + ", " + newY);
self.destination[0] = newX;
self.destination[1] = newY;
i = 5;
self.destinationQueue = simplePathFinder(self.map, self.getVisibleRobotMap(), [self.me.x, self.me.y], self.destination);
self.destinationQueue.pop();
}
if (i === 3) {
let x;
self.log("NO NEW SPACES AVAILABLE CHANGE DESTINATION");
for (x = 0; x < 4; ++x) {
const nextpointX = firstX + formation[x][0];
const nextpointY = firstY + formation[x][1];
if (nextpointX === 0 || nextpointY === 0 || nextpointX === self.map.length - 1 || nextpointY === self.map.length - 1) { continue; }
let resourceChecks = true;
if (self.karbonite_map[nextpointY][nextpointX] === true || self.fuel_map[nextpointY][nextpointX] === true) { resourceChecks = false; }
// Make sure that it is not too close to the CASTLE
const disti = manhatDist(self.friendlyCastleLoc[0], [nextpointX, nextpointY]);
let distChecks = true;
if (disti < 3) { distChecks = false; }
if (self.visitedBots.includes(visionMap[nextpointY][nextpointX])) { continue; }
if (resourceChecks === false || distChecks === false || self.map[nextpointY][nextpointX] === false) { continue; }
self.destination[0] = nextpointX;
self.destination[1] = nextpointY;
break;
}
}
}
if (i === 4) {
return null;
}
self.log("NEW DESTIONATION :::::: " + self.destination);
}
return goTo(self);
}
function firstSpot(self: any) {
// Move to first initial spot. If it is already occupied check to see if one of the formation
// spots are available and move there.
const horizontal = horizontalFlip(self.map);
let firstSpots: number[];
const visionMap = self.getVisibleRobotMap();
const inBounds = false;
if (!horizontal) {
if (self.enemyCastleLoc[1] > self.me.y) {
self.log("*****************X********");
// firstSpots = [self.me.x, self.me.y - 3];
firstSpots = [self.friendlyCastleLoc[0][0], self.friendlyCastleLoc[0][1] - 3];
while (!inBounds) {
let resourceCheck = true;
if (self.karbonite_map[firstSpots[1]][firstSpots[0]] === true || self.fuel_map[firstSpots[1]][firstSpots[0]] === true) { resourceCheck = false; }
if (self.map[firstSpots[1]][firstSpots[0]] === true && resourceCheck === true) {
break;
}
firstSpots[0] = firstSpots[0] - 1;
}
}
else {
// firstSpots = [self.me.x, self.me.y + 3];
firstSpots = [self.friendlyCastleLoc[0][0], self.friendlyCastleLoc[0][1] + 3];
self.log("*****************1********");
while (!inBounds) {
let resourceCheck = true;
if (self.karbonite_map[firstSpots[1]][firstSpots[0]] === true || self.fuel_map[firstSpots[1]][firstSpots[0]] === true) { resourceCheck = false; }
if (self.map[firstSpots[1]][firstSpots[0]] === true) {
break;
}
firstSpots[0] = firstSpots[0] - 1;
}
}
}
else {
if (self.enemyCastleLoc[0] > self.me.x) {
// firstSpots = [self.me.x - 3, self.me.y];
firstSpots = [self.friendlyCastleLoc[0][0] - 3, self.friendlyCastleLoc[0][1]];
self.log("*****************2********");
while (!inBounds) {
let resourceCheck = true;
if (self.karbonite_map[firstSpots[1]][firstSpots[0]] === true || self.fuel_map[firstSpots[1]][firstSpots[0]] === true) { resourceCheck = false; }
if (self.map[firstSpots[1]][firstSpots[0]] === true) {
break;
}
firstSpots[1] = firstSpots[1] - 1;
}
}
else {
// firstSpots = [self.me.x + 3, self.me.y];
firstSpots = [self.friendlyCastleLoc[0][0] + 3, self.friendlyCastleLoc[0][1]];
self.log("*****************3********");
while (!inBounds) {
let resourceCheck = true;
if (self.karbonite_map[firstSpots[1]][firstSpots[0]] === true || self.fuel_map[firstSpots[1]][firstSpots[0]] === true) { resourceCheck = false; }
if (self.map[firstSpots[1]][firstSpots[0]] === true) {
break;
}
firstSpots[1] = firstSpots[1] - 1;
}
}
}
self.destination = firstSpots;
const visibleRobots = self.getVisibleRobots();
const listLength = visibleRobots.length;
let i;
for (i = 0; i < listLength; ++i) {
const rob = visibleRobots[i];
if (rob.x === self.destination[0] && rob.y === self.destination[1]) {
return null;
}
}
self.destinationQueue = simplePathFinder(self.map, self.getVisibleRobotMap(), [self.me.x, self.me.y], self.destination);
self.destinationQueue.pop();
return firstSpots;
}
function goTo(self: any) {
self.log("RUN PATH AGAIN ====" + self.runPathAgain);
if (self.runPathAgain === 1) {
if (availableLoc(self.me.x, self.me.y, self.getVisibleRobotMap(), self.map) === null) { return null; }
self.destinationQueue = simplePathFinder(self.map, self.getVisibleRobotMap(), [self.me.x, self.me.y], self.destination);
self.destinationQueue.pop();
self.runPathAgain--;
}
if (availableLoc(self.me.x, self.me.y, self.getVisibleRobotMap(), self.map) === null) { return null; }
if (self.enemyCastleLoc !== null && (self.destinationQueue !== undefined && self.destinationQueue.length !== 0)) {
const toMove = self.destinationQueue.pop();
self.log("DSADSADSADSADSA " + toMove);
toMove[0] = toMove[0] - self.me.x;
toMove[1] = toMove[1] - self.me.y;
self.log("TO MOVE ++++++ :" + toMove);
self.log("DESTINATION +++++ : " + self.destination);
const visibleRobots = self.getVisibleRobots();
const listLength = visibleRobots.length;
let i;
for (i = 0; i < listLength; ++i) {
const rob = visibleRobots[i];
if (rob.x === toMove[0] && rob.y === toMove[1]) {
self.runPathAgain = 1;
return null;
}
}
if (toMove === null) {
self.runPathAgain = 1;
}
else {
return self.move(toMove[0], toMove[1]);
}
}
if (self.destinationQueue.length === 0) {
self.destinationQueue = simplePathFinder(self.map, self.getVisibleRobotMap(), [self.me.x, self.me.y], self.destination);
}
return null;
}
|
27ed74e88c110ee7470c5a467825e73c90198e2c
|
TypeScript
|
knidhi/ibm
|
/day2/src/step2.ts
| 3.203125
| 3
|
function addPower(pow:number){
return function(targetClass:any){
return class {
title = new targetClass().title;
power = pow
}
}
}
@addPower(5)
class Batman{
title = "Batman"
};
console.log(new Batman());
|
1a269418501d50bc3c466b75da14d1429c0400c3
|
TypeScript
|
Ajax-7/few300-apr-2020
|
/src/app/features/game/actions/game.actions.ts
| 2.515625
| 3
|
import { createAction, props } from '@ngrx/store';
// this.store.dispatch(gameStarted())
export const gameStarted = createAction(
'[game] game started',
() => ({
randomNumber: Math.floor(Math.random() * 10) + 1 // stolen from Tom Gannaway
})
);
// this.store.dispatch(tookAGuess({ guess }))
export const tookAGuess = createAction(
'[game] took a guess',
props<{ guess: number }>()
);
|
b049f70330f8dba3ffe691c46d3ee263f643cbfb
|
TypeScript
|
nikbelikov/tsp-solver
|
/demo/index.ts
| 2.734375
| 3
|
import TSPSolver from "../src/index";
import { IChromosomeWithFitness } from "../src/models/Chromosome";
const ready = () => {
const points = [
{ id: 0, name: "Praha" },
{ id: 1, name: "Paris" },
{ id: 2, name: "Rennes" },
{ id: 3, name: "Amsterdam" },
{ id: 4, name: "Hamburg" },
{ id: 5, name: "Budapest" },
{ id: 6, name: "Brno" },
{ id: 7, name: "Warszava" },
{ id: 8, name: "Milano" },
];
const values = [
{ set: [0, 1], value: 1032 },
{ set: [0, 2], value: 1375 },
{ set: [0, 3], value: 877 },
{ set: [0, 4], value: 639 },
{ set: [0, 5], value: 539 },
{ set: [0, 6], value: 205 },
{ set: [0, 7], value: 683 },
{ set: [0, 8], value: 869 },
{ set: [1, 2], value: 354 },
{ set: [1, 3], value: 517 },
{ set: [1, 4], value: 902 },
{ set: [1, 5], value: 1484 },
{ set: [1, 6], value: 1232 },
{ set: [1, 7], value: 1591 },
{ set: [1, 8], value: 851 },
{ set: [2, 3], value: 856 },
{ set: [2, 4], value: 1245 },
{ set: [2, 5], value: 1823 },
{ set: [2, 6], value: 1570 },
{ set: [2, 7], value: 1930 },
{ set: [2, 8], value: 1153 },
{ set: [3, 4], value: 464 },
{ set: [3, 5], value: 1394 },
{ set: [3, 6], value: 1080 },
{ set: [3, 7], value: 1193 },
{ set: [3, 8], value: 1078 },
{ set: [4, 5], value: 1178 },
{ set: [4, 6], value: 845 },
{ set: [4, 7], value: 852 },
{ set: [4, 8], value: 1112 },
{ set: [5, 6], value: 326 },
{ set: [5, 7], value: 858 },
{ set: [5, 8], value: 967 },
{ set: [6, 7], value: 539 },
{ set: [6, 8], value: 998 },
{ set: [7, 8], value: 1525 },
];
let i = 0;
const count = (latestPopulation?: IChromosomeWithFitness[]) => {
let solved;
do {
i++;
solved = TSPSolver(points, values, {
finishId: 0,
population: latestPopulation || undefined,
});
// @ts-ignore
document.getElementById("app").innerHTML = `${i}: ${JSON.stringify(
solved.result
)}`;
} while (i % 1 !== 0);
if (i === 10) {
// alert("done!");
} else {
setTimeout(count, 0, solved.latestPopulation);
}
};
count();
};
document.addEventListener("DOMContentLoaded", ready);
|
935bac5149026a6720540ceed551b344f7fa8a7f
|
TypeScript
|
aleweichandt/fitx
|
/src/user/model/reducer.ts
| 2.703125
| 3
|
import {createReducer} from '../../redux-helpers';
import {
LoadUserData,
LOAD_USER_DATA,
SetMetrics,
SetUsername,
SET_METRICS,
SET_USERNAME,
} from './actions';
import {State, User, UserMetrics} from './types';
export const initialState: State = {
loggedUser: undefined,
};
export const handleLoadUserData = (
state: State,
action: LoadUserData,
): State => ({
...state,
loggedUser: action.payload,
});
export const handleSetUsername = (state: State, action: SetUsername): State => {
const loggedUser: Partial<User> = state.loggedUser || {};
return {
...state,
loggedUser: {
...loggedUser,
name: action.payload,
} as User,
};
};
export const handleSetMetrics = (state: State, action: SetMetrics): State => {
const loggedUser: Partial<User> = state.loggedUser || {};
const metrics: Partial<UserMetrics> = loggedUser.metrics || {};
return {
...state,
loggedUser: {
...loggedUser,
metrics: {...metrics, ...action.payload},
} as User,
};
};
const handlers = Object.freeze({
[LOAD_USER_DATA]: handleLoadUserData,
[SET_USERNAME]: handleSetUsername,
[SET_METRICS]: handleSetMetrics,
});
export default createReducer<State>(handlers, initialState);
|
8d36f80ee4d4e3b739d6ee260061d0af326d4cfd
|
TypeScript
|
guygoool/BillingApp
|
/backend/src/controllers/customerController.ts
| 2.6875
| 3
|
import { Response, Request } from "express"
import Customer from "../models/customerModel"
import { ICustomer } from "../types/customerType"
const addCustomer = async (req: Request, res: Response): Promise<void> => {
try {
const body = req.body as ICustomer
const customer: ICustomer = new Customer({
customer_id: body.customer_id,
first_name: body.first_name,
last_name: body.last_name,
email: body.email,
gender: body.gender,
country: body.country,
city: body.city,
street: body.street,
phone: body.phone
})
const newCustomer: ICustomer = await customer.save()
res.status(200).json({ message: "Customer added", customer: newCustomer })
} catch (error) {
res.status(400).json({ message: `${error}` })
}
}
const getCustomers = async (req: Request, res: Response): Promise<void> => {
try {
const customers: ICustomer[] = await Customer.find()
res.status(200).json({ customers })
} catch (error) {
res.status(400).json({ message: `${error}` })
}
}
const updateCustomer = async (req: Request, res: Response): Promise<void> => {
try {
const { params: { id }, body } = req
const updateCustomer: ICustomer | null = await Customer.findByIdAndUpdate({ customer_id: id }, body)
res.status(200).json({
message: "Customer updated",
customer: updateCustomer
})
} catch (error) {
res.status(400).json({ message: `${error}` })
}
}
const deleteCustomer = async (req: Request, res: Response): Promise<void> => {
try {
const { id } = req.params;
const deletedCustomer: ICustomer | null = await Customer.findOneAndRemove({ customer_id: id })
res.status(200).json({
message: "Customer deleted",
customer: deletedCustomer
})
} catch (error) {
res.status(400).json({ message: `${error}` })
}
}
export { getCustomers, addCustomer, updateCustomer, deleteCustomer }
|
e4ad52dbb127565d7e6de85ea7c7ccb4f07074de
|
TypeScript
|
sawsenFattahi/nest-crud
|
/src/auth/user.service.ts
| 2.65625
| 3
|
import {
HttpException,
HttpStatus,
Injectable,
InternalServerErrorException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Observable, from } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { IUser } from './interfaces/user.interface';
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private readonly userRepository: Repository<User>,
) {}
findOneByEmail(email): Observable<IUser> {
return from(this.userRepository.findOneOrFail({ email })).pipe(
map((user) => user),
catchError(() => {
throw new HttpException(
'user with this email does not exist',
HttpStatus.NOT_FOUND,
);
}),
);
}
createUser(userData: IUser): Observable<string> {
const newUser = this.userRepository.create(userData);
return from(this.userRepository.save(newUser)).pipe(
map((response: IUser) => response.email),
catchError((e) => {
throw new InternalServerErrorException(e);
}),
);
}
}
|
3219c23fda6f31fff2adca4d6df8bfda4a6dcef8
|
TypeScript
|
krry/commonplace-foamy-nextjs
|
/lib/cache.ts
| 2.671875
| 3
|
/*
* cache for search
* following [@matswainson's lead](https://medium.com/@matswainson/building-a-search-component-for-your-next-js-markdown-blog-9e75e0e7d210)
*/
import fs from 'fs'
import path from 'path'
import read from 'fs-readdir-recursive'
import matter from 'gray-matter'
function getNotes() {
const notesDir = path.join(process.cwd(), 'docs')
// const notesDir = path.join(process.cwd(), 'private')
const filenames = read(notesDir)
const notes = filenames.map(file => {
const slug = file.replace(/\.mdx?$/, '')
const fullPath = path.join(notesDir, file)
const fileContents = fs.readFileSync(fullPath, 'utf8')
const { data } = matter(fileContents)
return {
slug,
title: data.title,
}
})
return JSON.stringify(notes)
}
const fileContents = `export const notes = ${getNotes()}`
function cache() {
try {
fs.readdirSync('_cache')
} catch (e) {
fs.mkdirSync('_cache')
}
fs.writeFile('_cache/data.js', fileContents, function (err) {
if (err) return console.error('error writing to cache', err)
console.info('notes cached for search')
})
}
export default cache
|
fb711d3aa1e9181ef4bc437a0ad59b11d756de3d
|
TypeScript
|
makasuapp/web-portal
|
/src/app/models/order.ts
| 2.734375
| 3
|
export type OrderType = 'delivery' | 'pickup'
export type OrderState = 'new' | 'started' | 'done' | 'delivered'
export interface Customer {
id: number
email?: string
name?: string
phone_number?: string
}
export interface OrderItem {
id: number
recipe_id: number
price_cents: number
quantity: number
started_at?: number
done_at?: number
}
export interface Order {
id: number
order_id: string
order_type: OrderType
created_at: number
for_time?: number
state: OrderState
customer: Customer
items: OrderItem[]
}
|
daf42c3f2fdce7cc2d257df4379a29b577d3c557
|
TypeScript
|
huan/mike-bo
|
/src/chatgpt/on-message.ts
| 2.609375
| 3
|
import type { Wechaty, Message } from 'wechaty'
import { ChatGPTAPIBuilder } from './chatgpt-api-builder.js'
const chatGptApi = await ChatGPTAPIBuilder()
const DEFAULT_CREDIT = 1
const MAX_PREMIUM_NUM_NOTICE = '发个红包热闹一下吧!'
const credits = {} as Record<string, number>
export async function onMessage (this: Wechaty, message: Message): Promise<void> {
const room = message.room()
// if (!room) return
// const topic = await room.topic()
// if (!/ChatGPT/.test(topic)) return
const talker = message.talker()
const credit = credits[talker.id] || 0
/**
* Check red packet
*/
if (message.type() === this.Message.Type.RedEnvelope) {
credits[talker.id] = (credits[talker.id] || 0) + 1
return
}
if (room && !(await message.mentionSelf())) return
/**
* Check freemium
*/
const admins = [
'lizhuohuan',
'qunaer001',
]
if (!admins.includes(talker.id) && credit <= 0 - DEFAULT_CREDIT) {
await (room
? room.say(MAX_PREMIUM_NUM_NOTICE, talker)
: message.say(MAX_PREMIUM_NUM_NOTICE)
)
return
}
credits[talker.id] = credit - 1
/**
* Only response in a room with "ChatGPT" in the topic and mentioned self
*/
const text = await message.mentionText()
// send a message and wait for the response
const response = await chatGptApi.ask(text)
const fullText = [
talker.name() + ': ' + text,
'-----',
'ChatGPT: ' + response || 'No response',
].join('\n')
await message.say(fullText)
}
|
7d80c4d8199ca2a5b815765718a940612bb9da3e
|
TypeScript
|
altriayu/release_log_crawler
|
/src/utils/chrome/getChromeLogUrl.ts
| 2.671875
| 3
|
import * as superagent from "superagent"
/**
* 该函数通过输入一个chrome浏览器的版本号,来获取对应版本的更新日志所在的url
* @param version 需要获取的更新日志的版本号
* @returns 更新日志的URL
*/
export const getChromeUrl = async (version: string): Promise<string | any> => {
const getBlogListUrl: string = 'https://0ppzv3ey55-dsn.algolia.net/1/indexes/prod_developer_chrome/query?x-algolia-agent=Algolia%20for%20JavaScript%20(4.6.0)%3B%20Browser%20(lite)&x-algolia-api-key=f08cd9d7ead266781a7c2455b5f4a7b2&x-algolia-application-id=0PPZV3EY55'
let postQueryParams = {
query: '',
hitsPerPage: 10,
filters: 'locale:\"en\"',
highlightPreTag: '<strong>',
highlightPostTag: '</strong>',
attributesToSnippet: ["content:25"],
snippetEllipsisText: '…'
}
postQueryParams.query = "new in chrome" + version
try {
const blogUrl = await superagent.post(getBlogListUrl).send(postQueryParams)
if (blogUrl.body.hits[0].title.toLowerCase().replace(/\s*/g, "", '') === ('new in chrome' + version).replace(/\s*/g, "")) {
console.log(blogUrl.body.hits[0].url)
return Promise.resolve("https://developer.chrome.com" + blogUrl.body.hits[0].url)
} else {
return Promise.reject("版本尚未发布")
}
} catch (errs) {
console.log("获取url失败!")
return Promise.reject(errs)
}
}
|
45bd0e1f0c7e3c68379e810fdba9a66e93ac7e1d
|
TypeScript
|
future4code/Yuzo-Okamoto
|
/semana-19/aula-1/tests/1.test.ts
| 2.953125
| 3
|
import { performPurchase, User } from '../src/exercises/1'
describe("Testing function performPurchase from exercise 1", () => {
test("Must return the updated user if purchase value is lesser than user's balance", () => {
const user = new User("John Doe", 1000);
const output = performPurchase(user, 250);
expect(output).toEqual(user);
expect(user.getBalance()).toBe(750);
});
test("Must return the updated user if purchase value is equal to user's balance", () => {
const user = new User("John Doe", 1000);
const output = performPurchase(user, 1000);
expect(output).toEqual(user);
expect(user.getBalance()).toBe(0);
});
test("Must return undefined if purchase value is greater than user's balance", () => {
const user = new User("John Doe", 1000);
const output = performPurchase(user, 2000);
expect(output).toBe(undefined);
expect(user.getBalance()).toBe(1000);
});
})
|
29d839b4d23fdf655c060e41adb740c386cf4890
|
TypeScript
|
thrashr888/monkey-typescript
|
/evaluator/builtins/file_realpath.ts
| 3.03125
| 3
|
import OObject, { Builtin, STRING_OBJ, OBoolean, OString } from '../../object/object';
import { newError } from '../evaluator';
import Environment from '../../object/environment';
import fs from 'fs';
// gets the real path of a given path (resolves `.` and `..`)
// file_realpath('./tmp')
// file_realpath('../sibling/b')
export default new Builtin(function(env: Environment, ...args: OObject[]): OObject {
if (args.length !== 1) {
return newError('wrong number of arguments. got=%s, want=1', args.length);
}
if (args[0].Type() !== STRING_OBJ) {
return newError('argument to `file_realpath` must be STRING, got %s', args[0].Type());
}
let path = args[0].Inspect();
return new OString(fs.realpathSync(path, { encoding: 'utf8' }));
});
|
e22b10b00a89576469614820ac8a886452f24410
|
TypeScript
|
njcodemonster/csvmatchingelectronangular4
|
/src/app/app.component.ts
| 2.515625
| 3
|
import { Component } from '@angular/core';
import {ElectronService} from 'ngx-electron';
//import fs = require('fs');
//
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
msg = 'Reading FTP data in back ground Please enter C and D column!';
Ccolumn:string = "D";
isdone:boolean = false;
Dcolumn:string = "B";
Clines:any = [];
ClinesProcessed:any = [];
ftpdata:string="";
constructor(private _electronService: ElectronService) {
this._electronService.ipcRenderer.addListener('async-reply',(event:any, arg:any)=>{ this.isdone=true;
this.ftpdata = arg;
this.Clines = this.extractData(arg);
this.msg = "Data Recived....";
this.isdone = true;
})
}
matchstep2(){
if(!this.isdone){
alert("Please request data first!.");
}
else{
let i:number=0;
for (i=0;i<this.Clines.length;i++){
let v:string = this.Clines[i];
v = v.replace(".JPG", "").replace(".jpg", "");
// console.log (v.split(" ")[0]);
v=v.split(" ")[0];
if(this.Dcolumn.indexOf(v)!=-1){
this.ClinesProcessed.push("\""+v+"\""+",R-Column\r\n");
}
else{
if(this.Ccolumn.indexOf(v)!=-1){
this.ClinesProcessed.push("\""+v+"\""+",C-Column\r\n");
}
else{
this.ClinesProcessed.push("\""+v+"\""+",NOT FOUND\r\n");
}
}
}
}
var p= this._electronService.ipcRenderer.send("tabora",[this.ClinesProcessed]);
//console.log(this.ClinesProcessed);
}
matchit(){
this.msg="Requesting FTP listing data....";
this.delay(1000);
this.Clines = this.extractData(this.Ccolumn);
var p= this._electronService.ipcRenderer.send("async",[this.Ccolumn,this.Dcolumn]);
console.log("sds");
}
//////////////////////////////
delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
private extractData(csvdata:string) {
let csvData = csvdata || '';
let allTextLines = csvData.split(/\r\n|\n/);
//let headers = allTextLines[2].split(',');
//console.log(headers);
let lines = [];
lines = allTextLines;
/*
for ( let i = 0; i < allTextLines.length; i++) {
// split content based on comma
let data = allTextLines[i].split(',');
if (data.length == headers.length) {
let tarr = [];
for ( let j = 0; j < headers.length; j++) {
tarr.push(data[j]);
}
lines.push(tarr);
}
}*/
return lines;
}
/////////////////////////////
}
|
8f03cc001d360c98655db98e2c6e8f9c9e5a6925
|
TypeScript
|
Ithomiroff/pane-no-paine
|
/src/module/classes/separator.ts
| 2.609375
| 3
|
import { ISeparatorParams } from '../intefaces/separator-params';
import { AbstractElement } from './abstract-element';
export class Separator extends AbstractElement<ISeparatorParams> {
private _hold: boolean = false;
get hold(): boolean {
return this._hold;
}
set hold(value: boolean) {
this._hold = value;
}
private _clientX: number;
get clientX(): number {
return this._clientX;
}
set clientX(value: number) {
this._clientX = value;
this.setStyles({
transform: `translateX(${value}px)`,
})
}
constructor(params: ISeparatorParams) {
super(params);
this.setStyles({
position: 'absolute',
top: `${params.position.top}px`,
transform: `translateX(${params.position.left}px)`,
height: `100%`,
width: '5px',
background: '#ccc',
});
this._clientX = this.params.htmlRef.getBoundingClientRect().x;
}
}
|
5b3e6a0279ab37136c85a981e9afa6b209768a70
|
TypeScript
|
MohammedFaragallah/me
|
/src/Store/Reducers/Locale/reducer.ts
| 2.71875
| 3
|
import { ActionTypes, LocaleActions, LocaleState } from 'Store';
import {
DefaultLanguage,
getLocale,
getTranslatedMessages,
} from 'localization';
const locale = getLocale(DefaultLanguage.code);
const initialState: LocaleState = {
locale,
messages: getTranslatedMessages(locale.code),
preferredLanguage: undefined,
};
export const localeReducer = (state = initialState, action: LocaleActions) => {
switch (action.type) {
case ActionTypes.CHANGE_LANGUAGE: {
const locale = getLocale(action.payload);
return {
...state,
locale,
messages: getTranslatedMessages(action.payload),
preferredLanguage: locale,
};
}
default:
return state;
}
};
|
5fb8dc52097317e4c98044e485122f701f851bb0
|
TypeScript
|
liphe/delisp
|
/packages/delisp-core/__tests__/reader.ts
| 3.078125
| 3
|
import { readAllFromString, readFromString } from "../src/reader";
import { ASExpr } from "../src/sexpr";
function removeLocation(x: ASExpr): object {
switch (x.tag) {
case "number":
case "symbol":
case "string": {
const { location: _, ...props } = x;
return props;
}
case "list":
case "vector": {
const { location: _, ...props } = x;
return {
...props,
elements: x.elements.map(removeLocation),
};
}
case "map": {
const { location: _, ...props } = x;
return {
...props,
fields: x.fields.map((f) => ({
label: f.label,
value: removeLocation(f.value),
})),
};
}
}
}
describe("Reader", () => {
it("should read numbers", () => {
expect(readFromString("12")).toMatchObject({
tag: "number",
value: 12,
location: { start: 0, end: 2 },
});
expect(readFromString(" 12 ")).toMatchObject({
tag: "number",
value: 12,
location: { start: 2, end: 4 },
});
expect(readFromString(" -12 ")).toMatchObject({
tag: "number",
value: -12,
location: { start: 2, end: 5 },
});
expect(readFromString(" 0.05 ")).toMatchObject({
tag: "number",
value: 0.05,
location: { start: 2, end: 6 },
});
expect(readFromString(" -0.9 ")).toMatchObject({
tag: "number",
value: -0.9,
location: { start: 2, end: 6 },
});
});
it("should read strings", () => {
expect(readFromString(' "xyz" ')).toMatchObject({
tag: "string",
value: "xyz",
location: { start: 2, end: 7 },
});
expect(readFromString(' "a\\nb" ')).toMatchObject({
tag: "string",
value: "a\nb",
location: { start: 2, end: 8 },
});
});
it("should read symbols", () => {
expect(readFromString(" xyz ")).toMatchObject({
tag: "symbol",
name: "xyz",
location: { start: 2, end: 5 },
});
expect(readFromString(" a2 ")).toMatchObject({
tag: "symbol",
name: "a2",
location: { start: 2, end: 4 },
});
expect(readFromString(" 3d ")).toMatchObject({
tag: "symbol",
name: "3d",
location: { start: 2, end: 4 },
});
expect(readFromString(" $bc ")).toMatchObject({
tag: "symbol",
name: "$bc",
location: { start: 2, end: 5 },
});
});
it("should read lists", () => {
expect(readFromString("()")).toMatchObject({
tag: "list",
elements: [],
location: { start: 0, end: 2 },
});
expect(readFromString("( )")).toMatchObject({
tag: "list",
elements: [],
location: { start: 0, end: 4 },
});
expect(readFromString("(1 2 3)")).toMatchObject({
tag: "list",
elements: [
{
tag: "number",
value: 1,
location: { start: 1, end: 2 },
},
{
tag: "number",
value: 2,
location: { start: 3, end: 4 },
},
{
tag: "number",
value: 3,
location: { start: 5, end: 6 },
},
],
location: { start: 0, end: 7 },
});
expect(readFromString(" (1 ( 2 ) 3) ")).toMatchObject({
tag: "list",
elements: [
{
tag: "number",
value: 1,
location: { start: 2, end: 3 },
},
{
tag: "list",
elements: [
{
tag: "number",
value: 2,
location: { start: 6, end: 7 },
},
],
location: { start: 4, end: 9 },
},
{
tag: "number",
value: 3,
location: { start: 10, end: 11 },
},
],
location: { start: 1, end: 12 },
});
});
it("should read vectors with square bracket notation", () => {
expect(readFromString("[]")).toMatchObject({
tag: "vector",
elements: [],
location: { start: 0, end: 2 },
});
expect(readFromString("[ ]")).toMatchObject({
tag: "vector",
elements: [],
location: { start: 0, end: 4 },
});
expect(readFromString("[1 2 3]")).toMatchObject({
tag: "vector",
elements: [
{
tag: "number",
value: 1,
location: { start: 1, end: 2 },
},
{
tag: "number",
value: 2,
location: { start: 3, end: 4 },
},
{
tag: "number",
value: 3,
location: { start: 5, end: 6 },
},
],
location: { start: 0, end: 7 },
});
expect(readFromString(" [1 [ 2 ] 3] ")).toMatchObject({
tag: "vector",
elements: [
{
tag: "number",
value: 1,
location: { start: 2, end: 3 },
},
{
tag: "vector",
elements: [
{
tag: "number",
value: 2,
location: { start: 6, end: 7 },
},
],
location: { start: 4, end: 9 },
},
{
tag: "number",
value: 3,
location: { start: 10, end: 11 },
},
],
location: { start: 1, end: 12 },
});
});
it("should read multiple S-expressions", () => {
expect(readAllFromString("(x 1 2)(y 3)")).toMatchObject([
{ tag: "list" },
{ tag: "list" },
]);
expect(readAllFromString(" (x 1 2) (y 3) ")).toMatchObject([
{ tag: "list" },
{ tag: "list" },
]);
expect(
readAllFromString(`
(x 1 2)
(y 3)
`)
).toMatchObject([{ tag: "list" }, { tag: "list" }]);
});
describe("Error messages", () => {
const failedRead = (x: string) => {
try {
readFromString(x);
} catch (err) {
return err.message;
}
throw new Error(`This expression didn't fail!`);
};
it("generate user-friendly error for an incomplete list", () => {
expect(failedRead("(1 2 3")).toMatchSnapshot();
});
it("generate user-friendly error for a closing parenthesis", () => {
expect(failedRead(")")).toMatchSnapshot();
});
it("generate user-friendly error for an incomplete string", () => {
expect(failedRead('"foo')).toMatchSnapshot();
});
it("generate user-friendly error for badly escaped string", () => {
expect(failedRead('"ab\\xyz"')).toMatchSnapshot();
});
it("generate a user-friendly error for incomplete escaped string", () => {
expect(failedRead('"abc\\')).toMatchSnapshot();
});
});
it("should detect incomplete inputs", () => {
const read = (x: string) => {
try {
readFromString(x);
return undefined;
} catch (err) {
return err.incomplete;
}
};
const readAll = (x: string) => {
try {
readAllFromString(x);
return undefined;
} catch (err) {
return err.incomplete;
}
};
expect(read("(1 2 3")).toBe(true);
expect(read(")")).toBe(false);
expect(read('"foo')).toBe(true);
expect(read('"ab\\xyz"')).toBe(false);
expect(read('"abc\\')).toBe(true);
expect(readAll("(1 2 3)(4 5")).toBe(true);
expect(readAll("(1 2 3)4 5)")).toBe(false);
expect(readAll("((1 2 3)")).toBe(true);
expect(readAll("(1 2 3))")).toBe(false);
expect(readAll("@{abc")).toBe(true);
});
describe("@-syntax", () => {
expect(removeLocation(readFromString("@{hello world}"))).toEqual(
removeLocation(readFromString(`(comment "hello world")`))
);
expect(removeLocation(readFromString("@comment{hello world}"))).toEqual(
removeLocation(readFromString(`(comment "hello world")`))
);
expect(
removeLocation(
readFromString("@desc{see @ref{note-1} for further information}")
)
).toEqual(
removeLocation(
readFromString(
`(desc "see " (ref "note-1") " for further information")`
)
)
);
});
});
|
d065583aeaa91bda9a73c7b7773426e92ba3ef04
|
TypeScript
|
luomus/laji
|
/projects/laji/src/app/shared/pipe/label.pipe.ts
| 2.703125
| 3
|
import { concatMap, map, switchMap, toArray } from 'rxjs/operators';
import { Observable, from, of, Subscription } from 'rxjs';
import { ChangeDetectorRef, Pipe, PipeTransform, OnDestroy } from '@angular/core';
import { WarehouseValueMappingService } from '../service/warehouse-value-mapping.service';
import { TranslateService } from '@ngx-translate/core';
import { TriplestoreLabelService } from '../service/triplestore-label.service';
import { IdService } from '../service/id.service';
type LabelType = 'qname'|'fullUri'|'warehouse'|'withKey'|'emptyWhenMissing';
/**
* Triplestores label maker
* Takes a triplestore id of type alt|property|class and returns it's label
* Usage:
* value | label
*/
@Pipe({
name: 'label',
pure: false
})
export class LabelPipe implements PipeTransform, OnDestroy {
private value: string|string[] = '';
private lastKey?: string;
private fetchSub?: Subscription;
constructor(
private translate: TranslateService,
private warehouseService: WarehouseValueMappingService,
private triplestoreLabelService: TriplestoreLabelService,
private cdr: ChangeDetectorRef
) {}
transform(value: string, type?: LabelType): string;
transform(value: string[], type?: LabelType): string[];
transform(value: string|string[], type?: LabelType): string|string[] {
if (!value || (typeof value !== 'string' && !Array.isArray(value)) || value.length === 0) {
return value;
}
const key = Array.isArray(value) ? value.join(',') : value;
// if we ask another time for the same key, return the last value
if (key === this.lastKey) {
return this.value;
}
this.lastKey = key;
this.clearSub();
if (Array.isArray(value)) {
this.fetchSub = from(value).pipe(
concatMap(v => this.fetchValue(v, type)),
toArray()
).subscribe(v => {
this.updateValue(v);
});
} else {
this.fetchSub = this.fetchValue(value, type).subscribe(v => this.updateValue(v));
}
return this.value;
}
ngOnDestroy() {
this.clearSub();
}
private clearSub() {
if (this.fetchSub) {
this.fetchSub.unsubscribe();
}
}
private updateValue(value: string|string[]) {
this.value = value;
this.cdr.markForCheck();
}
private fetchValue(key: string, type?: LabelType): Observable<string> {
switch (type) {
case 'warehouse':
return this.warehouseService.getSchemaKey(key).pipe(
switchMap(res => this.fetchValue(res))
);
case 'fullUri':
return key.indexOf('http') === 0 ?
this.triplestoreLabelService.get(IdService.getId(key), this.translate.currentLang) :
of(key);
case 'withKey':
return this.triplestoreLabelService.get(key, this.translate.currentLang).pipe(
map(value => value !== key ? `${value} (${key})` : value)
);
case 'emptyWhenMissing':
return this.fetchValue(key).pipe(
map(res => res === key ? '' : key)
);
default:
return this.triplestoreLabelService.get(key, this.translate.currentLang).pipe(
map(res => res || key)
);
}
}
}
|
aaf7d2bef7b8ce54bc92d265a350a69ec6f1b485
|
TypeScript
|
EmmanuelMat/clients-api
|
/src/core/interfaes/IRequestHandler.ts
| 2.75
| 3
|
export interface IRequestHandler<TRequest, TResponse> {
task(request: TRequest): TResponse
}
|
50f5d57c6bd875212f36c2d911f71b1559c163e0
|
TypeScript
|
kevincar/TRProject
|
/src/objects/SheetRecordDictionary.ts
| 3.25
| 3
|
/*
* Filename: SheetRecordDictionary.ts
* Author: Kevin Davis
*
* Description
* A Custom SheetObjectDictionary to properly handle the formula strings
* that TRRecord classes need
*/
class SheetRecordDictionary extends SheetObjectDictionary<TRRecord> {
constructor(sheet: Sheet) {
super(TRRecord, sheet);
}
translate(): TRRecord[] {
if(this.sheet == null) throw `Cannot translate a null sheet`;
// Get Values for all columns expect those columns that are formula dependant
let records: TRRecord[] = [];
this.sheet.formulas.forEach((rowData: any[], rowIndex: number): void => {
if(rowIndex == 0) return;
if(this.sheet == null) throw `sheet is null and should not be!`;
let headers: string[] = this.sheet.headers;
let data: SheetObjectInterface = {};
headers.forEach((header: string, headerIndex: number): void => {
data[header] = rowData[headerIndex];
//if(header == "Expiring In (mo)") {
//if(this.sheet == null) throw `SheetRecordDictionary::translate - sheet is null`;
//data[header] = this.sheet.formulas[rowIndex][headerIndex];
//}
});
//if(this.ctor == null) throw `SheetRecord Dictionary::translate - constructor is null!`;
let instance: TRRecord = new TRRecord(data);
if(!instance.validate(data)) return;
records.push(instance);
});
return records;
}
}
|
584fa66053dcc9e7678d73c0f56498ed46824b2e
|
TypeScript
|
Coffeekraken/coffeekraken
|
/packages/tools/sugar/src/js/filter/SSvgFilter.ts
| 2.921875
| 3
|
// @ts-nocheck
import __uniqid from '../../js/string/uniqid.js';
/**
* @name __SSvgFilter
* @namespace js.filter
* @type Class
* @platform js
* @status wip
*
* This class allows you to create with ease some complexe SVG filters and to apply it on any HTMLElement that you want
* by extending this class like so
*
* @todo interface
* @todo doc
* @todo tests
*
* @example js
* import { __SSvgFilter } from '@coffeekraken/sugar/filter';
* class MyBlurFilter extends __SSvgFilter {
*
* constructor(amount = 8) {
* super(`
* <feGaussianBlur in="SourceGraphic" stdDeviation="${amount}" result="blur" />
* `);
* }
* }
*
* // using your filter
* const myFilter = new MyBlurFilter(10);
* myFilter.applyTo(myCoolHTMLElement);
*
* @since 2.0.0
* @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io)
*/
export default class __SSvgFilter {
/**
* @name constructor
* @type Function
*
* Constructor
*
* @param {String} filter The SVG filter string representation
*
* @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io)
*/
constructor(filter_content) {
// save the reference of each elements
this.elms = [];
// save parameters
this.filter_content = filter_content;
// generate a uniqid
this.id = 's-svg-filter-' + __uniqid();
// if need to inject svg
if (!document.body.querySelector('#s-svg-filters'))
SSvgFilter._injectFiltersContainer();
// insert the filter
this._insertFilter();
}
/**
* @name applyTo
* @type Function
*
* Apply the filter to an element
*
* @param {HTMLElement} elm The element on which to apply the filter
*
* @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io)
*/
applyTo(elm) {
['-webkit-', '-moz-', '-ms-', '-o-', ''].forEach((vendor) => {
elm.style[vendor + 'filter'] = 'url("#' + this.id + '")';
});
this.elms.push(elm);
}
/**
* @name unapplyFrom
* @type Function
*
* Unapply from
*
* @param {HTMLElement} elm The element from which to remove the filter
*
* @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io)
*/
unapplyFrom(elm) {
['-webkit-', '-moz-', '-ms-', '-o-', ''].forEach((vendor) => {
elm.style[vendor + 'filter'] = null;
delete elm.style[vendor + 'filter'];
});
// remove from stack
const idx = this.elms.indexOf(elm);
if (idx) this.elms.splice(idx, 1);
}
/**
* @name _insertFilter
* @type Function
* @private
*
* Insert the filter
*
* @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io)
*/
_insertFilter() {
const svg = `
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<defs>
</defs>
</svg>
`;
const div = document.createElement('div');
div.innerHTML = svg;
const defs = div.querySelector('defs');
// add the filter to the svg
this.filter_content =
'<filter id="' + this.id + '">' + this.filter_content + '</filter>';
defs.innerHTML = this.filter_content;
this.filter = defs.querySelector('#' + this.id);
this.svg = div.querySelector('svg');
SSvgFilter.filtersContainer.appendChild(this.svg);
}
/**
* @name destroy
* @type Function
*
* Destroy the filter
*
* @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io)
*/
destroy() {
// loop on each element savec in stack to remove the filter
this.elms.forEach((elm) => {
this.unapplyFrom(elm);
});
// remove the filter from the html
this.svg.parentNode.removeChild(this.svg);
}
/**
* @name _injectFiltersContainer
* @type Function
* @private
* @static
*
* Inject the svg that will contains all the filters created through this class
*
* @author Olivier Bossel <olivier.bossel@gmail.com> (https://coffeekraken.io)
*/
static _injectFiltersContainer() {
const style = ['position:absolute;', 'left:-1000px;', 'top:-300px;'];
if (
/Chrome/.test(navigator.userAgent) &&
/Google Inc/.test(navigator.vendor)
) {
style.push('display:none;');
}
SSvgFilter.filtersContainer = document.createElement('div');
SSvgFilter.filtersContainer.id = 's-svg-filters';
SSvgFilter.filtersContainer.style = style.join(' ');
document.body.appendChild(SSvgFilter.filtersContainer);
}
}
|
26e16b9cb0a0cd29b2730f43f2601ce5efdadf67
|
TypeScript
|
penge/expenses-tracker
|
/src/api/categories.ts
| 3.078125
| 3
|
const categoriesKey = (email: string) => `categories.${email}`;
export function getCategories(email: string) {
const key = categoriesKey(email);
const categories = (JSON.parse(localStorage.getItem(key) as string) || []) as string[];
return categories;
}
function setCategories(email: string, categories: string[]) {
const key = categoriesKey(email);
localStorage.setItem(key, JSON.stringify(categories));
}
export function addCategory(email: string, categoryName: string) {
const categories = getCategories(email);
if (categories.includes(categoryName)) {
return false;
}
categories.push(categoryName);
setCategories(email, categories);
return true;
}
|
7365dde2117dade973fa747481cf40de43831a21
|
TypeScript
|
KeithMarex/VvE-APP
|
/WebApp/src/app/calendar-overview/calendar/calendar.service.ts
| 2.640625
| 3
|
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { addMonths, isSameMinute, isSameMonth, subMonths } from 'date-fns';
import { CalendarItem } from '../../../shared/models/calendar-item';
import { CustomEvent } from './custom-event';
import { CalendarDao } from '../../../shared/services/calendar-dao.service';
interface StoredMonth {
month: Date;
calendarItems: CalendarItem[];
}
@Injectable()
export class CalendarService {
calendarItems = new BehaviorSubject<CalendarItem[]>([]);
storedMonths: StoredMonth[] = [];
constructor(private calendarDao: CalendarDao) { }
customEventToCalendarItem(event: CustomEvent): CalendarItem {
return new CalendarItem(
event.id,
event.title,
event.description,
event.start,
event.end
);
}
updateCalendarItem(calendarItem: CalendarItem): void {
const calendarItems = this.calendarItems.getValue();
const updatedCalendarItemIndex = calendarItems.findIndex(
(item) => item._id === calendarItem._id
);
calendarItems[updatedCalendarItemIndex] = calendarItem;
this.calendarItems.next(calendarItems);
}
deleteCalendarItem(calendarItemId: string): void {
this.calendarItems.next(
this.calendarItems.getValue().filter((calendarItem) => {
return calendarItem._id !== calendarItemId;
}
));
}
setCalendarItems(calendarItems: CalendarItem[]): void {
this.calendarItems.next(calendarItems);
}
addCalendarItem(calendarItem: CalendarItem): void {
this.calendarItems.next(
this.calendarItems.getValue().concat([calendarItem])
);
}
fetchMonthAndSurroundingMonthsItems(date: Date): void {
let calendarItemsWithSurroundingMonths = [];
this.findOrFetchMonthItems(date)
.then((thisMonthItems) => {
calendarItemsWithSurroundingMonths =
calendarItemsWithSurroundingMonths.concat(thisMonthItems);
this.findOrFetchMonthItems(subMonths(date, 1))
.then((prevMonthItems) => {
calendarItemsWithSurroundingMonths =
calendarItemsWithSurroundingMonths.concat(prevMonthItems);
this.findOrFetchMonthItems(addMonths(date, 1))
.then((nextMonthItems) => {
calendarItemsWithSurroundingMonths =
calendarItemsWithSurroundingMonths.concat(nextMonthItems);
this.setCalendarItems(calendarItemsWithSurroundingMonths);
});
});
});
}
overwriteWithNewMonthItems(newDate: Date, oldDate: Date): boolean {
let didOverwriteMonthItems = false;
if (!this.calendarItemsIsEmpty()) {
this.storeMonth(oldDate);
}
const foundCalendarItemsThisMonth = this.findStoredCalendarItems(newDate);
if (foundCalendarItemsThisMonth) {
const foundCalendarItems = foundCalendarItemsThisMonth ? foundCalendarItemsThisMonth : [];
const foundSurroundingCalendarItems = this.findSurroundingStoredCalendarItems(newDate);
foundCalendarItems.push(...foundSurroundingCalendarItems);
this.setCalendarItems(foundCalendarItems);
didOverwriteMonthItems = true;
}
return didOverwriteMonthItems;
}
storeMonth(month: Date): void {
if (!this.monthIsStored(month)) {
this.storedMonths.push({
month,
calendarItems: this.calendarItems.getValue().filter(calendarItem =>
isSameMonth(new Date(calendarItem.date), month)
)
});
}
}
monthIsStored(month: Date): boolean {
this.storedMonths.forEach((storedMonth) => {
if (isSameMonth(storedMonth.month, month)) {
return true;
}
});
return false;
}
findOrFetchMonthItems(month: Date): Promise<CalendarItem[]> {
return new Promise<CalendarItem[]>((resolve) => {
const storedItemsMonth = this.findStoredCalendarItems(month);
if (!storedItemsMonth) {
this.calendarDao.getCalendarItems(this.getFetchMonthString(month))
.subscribe((monthCalItems) => {
resolve(monthCalItems);
});
} else {
resolve(storedItemsMonth);
}
});
}
findSurroundingStoredCalendarItems(month: Date): CalendarItem[] {
const surroundingCalendarItems = [];
const nextMonthItems = this.findStoredCalendarItems(addMonths(month, 1));
const prevMonthItems = this.findStoredCalendarItems(subMonths(month, 1));
surroundingCalendarItems.push(...nextMonthItems ? nextMonthItems : []);
surroundingCalendarItems.push(...prevMonthItems ? prevMonthItems : []);
return surroundingCalendarItems;
}
findStoredCalendarItems(month: Date): CalendarItem[] {
let foundItems = null;
this.storedMonths.forEach((storedMonth) => {
if (isSameMonth(storedMonth.month, month)) {
foundItems = storedMonth.calendarItems;
}
});
return foundItems;
}
parseCalendarItemsToDisplayable(calItems: CalendarItem[], actions): CustomEvent[] {
const parsedEvents: CustomEvent[] = [];
calItems.forEach((calItem) => {
parsedEvents.push(
this.calendarItemToCustomEvent(calItem, actions)
);
});
return parsedEvents;
}
calendarItemToCustomEvent(calItem: CalendarItem, actions): CustomEvent {
const startDate = new Date(calItem.date);
const endDate = calItem.enddate ? new Date(calItem.enddate) : undefined;
const allDay = isSameMinute(startDate, endDate);
const customEvent: CustomEvent[] = [];
customEvent.push({
start: startDate,
end: endDate,
title: calItem.title,
description: calItem.description,
id: calItem._id,
allDay,
actions,
resizable: {
beforeStart: true,
afterEnd: true,
},
draggable: true,
});
return customEvent[0];
}
getFetchMonthString(month: Date): string {
return (month.getFullYear()) + '-' + (month.getMonth() + 1);
}
calendarItemsIsEmpty(): boolean {
return this.calendarItems.getValue().length <= 0;
}
}
|
ef6d0aeda644ff19c751d52d8a420e33e5bfb292
|
TypeScript
|
mariacki/tomb-racer
|
/back-end/src/game/events/PlayerHitEvent.ts
| 2.734375
| 3
|
import { PlayerHit, EventType } from "../../../../common";
export class PlayerHitEvent implements PlayerHit
{
isError: boolean = false;
type: EventType = EventType.PLAYER_HIT;
origin: string;
userId: string;
hpTaken: number;
currentHp: number;
constructor(
gameId: string,
userId: string,
hpTaken: number,
currentHp: number
) {
this.origin = gameId;
this.userId = userId;
this.hpTaken = hpTaken;
this.currentHp = currentHp;
}
}
|
82a8cfd5bd9b09346f6eb69da76039076045b664
|
TypeScript
|
Sciator/knapsack-approximation-algorithms
|
/src/utils/random.ts
| 3.34375
| 3
|
import { range } from "./array";
export const randInt: {
(maxExcluded: number): number;
(minIncluded: number, maxExcluded: number): number;
} = (a: number, b?: number): number => {
if (b === undefined)
return Math.floor(Math.random() * a);
else
return Math.floor(Math.random() * (b - a)) + a;
};
export const shuffle = <T>(arr: T[]): T[] => {
const newArr: T[] = [];
let len = 0;
for (const i of arr) {
newArr.splice(randInt(++len), 0, i);
}
return newArr;
};
export const shuffleTeleport = <T>(arr: T[], qty: number): T[] => {
const newArr = arr.slice();
const len = arr.length;
range(qty).forEach(() => {
const i1 = randInt(len);
const i2 = randInt(len);
const tmp = newArr[i1];
newArr[i1] = newArr[i2];
newArr[i2] = tmp;
});
return newArr;
};
export const shuffleSwap = <T>(arr: T[], swaps: number): T[] => {
const newArr: T[] = [...arr];
const swap = (i: number) => {
const val = newArr[i];
newArr[i] = newArr[i + 1];
newArr[i + 1] = val;
};
range(swaps)
.map(() => randInt(arr.length - 1))
.forEach(x => swap(x))
;
return newArr;
};
|
d2a55d5b458aaa9a2f443f7ca988eb967a8e13e4
|
TypeScript
|
c4bo3l/omnilytics
|
/src/hooks/useNumericGenerator.ts
| 3.03125
| 3
|
export const useNumericGenerator = () => {
const multiplier = [1, 10, 100, 1000, 10000, 100000];
const getRandomIntInRange = (min: number, max: number) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
};
const getRandomInteger = (length?: number) => {
const selectedMultiplier = length ? Math.pow(10, length) :
multiplier[getRandomIntInRange(0, multiplier.length - 1)];
const result = Math.random() * selectedMultiplier;
return Math.ceil(result);
};
const generateIntegerStr = (length?: number) => {
return getRandomInteger(length).toString();
};
const generateFloatStr = (length?: number) => {
const selectedMultiplier = length ? Math.pow(10, length) :
multiplier[getRandomIntInRange(0, multiplier.length - 1)];
const result = Math.random() * selectedMultiplier;
return result.toString();
};
const generateNumericStr = (length?: number) => {
const selector = getRandomIntInRange(0, 1000) % 2;
if (selector === 0) {
return generateIntegerStr(length);
}
return generateFloatStr(length);
};
return {
getRandomIntInRange,
getRandomInteger,
generateIntegerStr,
generateFloatStr,
generateNumericStr
};
};
|
49c9e0a2f9aee3a159df05b504fafe323963f5e7
|
TypeScript
|
baikinjo/TickitShop
|
/app/tickit-shop.ts
| 3.375
| 3
|
const LEGENDARY = 'ping-pong paddle'
const CONJURED = 'conjured'
const CHEESE = 'sharp cheddar'
const TICKET = 'lady gaga ticket'
const NORMAL = 'normal'
export class Item {
name: string
sellIn: number
quality: number
constructor(name: string, sellIn: number, quality: number) {
this.name = name
this.sellIn = sellIn
this.quality = quality
}
}
export class TickitShop {
items: Array<Item>
constructor(items = [] as Array<Item>) {
this.items = items
}
// categorize the item before applying any changes
private categorizeItem(name: string) {
// make them lower case to compare
const lowerCased = name.toLowerCase()
/**
* Order starts from legendary, conjured, cheese, and ticket
* since Legendary does not get affected by anything comes first
* conjured means it will decrease quality twice faster than regular items
* cheese or ticket order doesn't matter at this point
* if an item doesn't belong to any 4 of the category it is considered as a normal item
*/
if (lowerCased.includes(LEGENDARY)) return LEGENDARY
if (lowerCased.includes(CONJURED)) return CONJURED
if (lowerCased.includes(CHEESE)) return CHEESE
if (lowerCased.includes(TICKET)) return TICKET
return NORMAL
}
// handling legnedary item
private handleLegendary(item: Item, idx: number) {
let items = this.items
/**
* legendary never has to be sold or decrease quality so if the sellIn is not 0 then change to 0
* same applies to quality to 80 all the time
*/
if (item.sellIn !== 0) {
return (items[idx] = { ...item, sellIn: 0, quality: 80 })
} else {
return (items[idx] = { ...item, quality: 80 })
}
}
// handling conjured item
private handleConjured(item: Item, idx: number) {
/**
* Since the item degrades twice faster than the normal item, degrade the item until the quality reaches 0
* both sellin and quality value stops at 0
*/
return this.decreaseQuality(item, idx, 2)
}
// handle sharp cheddar item
private handleCheese(item: Item, idx: number) {
/**
* Quality of the item increases as it gets old but will degrade when sell in value is at 0
* First check the item's sellin value and if it is equal to zero then degrade item quality by two
* if not zero, then increase the item quality by one but decrease the sellin value by one as well
*/
if (item.sellIn <= 0) {
this.decreaseQuality(item, idx, 2)
} else {
this.increaseQuality(item, idx, 1)
}
}
// handle concert item
private handleTicket(item: Item, idx: number) {
let items = this.items
// quality will be zero when concert date has passed
if (item.sellIn <= 0) {
return (items[idx] = { ...item, quality: 0, sellIn: 0 })
}
/**
* check if the concert has less than 10 days left
* if true, check once more if the concert has less than 5 days left
* increase the quality depending on the sellIn value
*/
if (item.sellIn <= 10) {
if (item.sellIn <= 5) {
this.increaseQuality(item, idx, 3)
} else {
this.increaseQuality(item, idx, 2)
}
} else {
this.increaseQuality(item, idx, 1)
}
}
// handle normal item
private handleNormal(item: Item, idx: number) {
if (item.sellIn <= 0) {
this.decreaseQuality(item, idx, 2)
} else {
this.decreaseQuality(item, idx, 1)
}
}
/**
* This will increase the quality of the item until the maximum of 50
* once the quality reaches 50, it will stay 50 with varied sellIn value
* @param item Item that needs to modify the value
* @param idx position of the item in the original array
* @param valueToIncrease number of value to increase
*/
private increaseQuality(item: Item, idx: number, valueToIncrease: number) {
let items = this.items
const qualityExceeds = item.quality + valueToIncrease > 50
return qualityExceeds
? (items[idx] = {
...item,
quality: 50,
sellIn: item.sellIn <= 0 ? 0 : item.sellIn - 1,
})
: (items[idx] = {
...item,
quality: item.quality + valueToIncrease,
sellIn: item.sellIn <= 0 ? 0 : item.sellIn - 1,
})
}
/**
* This will increase the quality of the item until the minimum of 0
* once the quality meets 0, it will stay 0 with varied sellIn value
* @param item Item that needs to modify the value
* @param idx position of the item in the original array
* @param valueToIncrease number of value to decrease
*/
private decreaseQuality(item: Item, idx: number, valueToDecrease: number) {
let items = this.items
const qualityFalls = item.quality - valueToDecrease < 0
return qualityFalls
? (items[idx] = {
...item,
quality: 0,
sellIn: item.sellIn <= 0 ? 0 : item.sellIn - 1,
})
: (items[idx] = {
...item,
quality: item.quality - valueToDecrease,
sellIn: item.sellIn <= 0 ? 0 : item.sellIn - 1,
})
}
updateQuality() {
this.items.forEach((item: Item, idx: number) => {
const category = this.categorizeItem(item.name)
switch (category) {
case LEGENDARY:
this.handleLegendary(item, idx)
break
case CONJURED:
this.handleConjured(item, idx)
break
case CHEESE:
this.handleCheese(item, idx)
break
case TICKET:
this.handleTicket(item, idx)
break
default:
this.handleNormal(item, idx)
break
}
})
return this.items
}
}
|
22bab6058a3900ccfa8c305c20f635e7af2cbfb9
|
TypeScript
|
lazerwalker/closed-captions-app
|
/src/webrtc.ts
| 2.65625
| 3
|
import {
sendWebRTCConnectionOffer,
sendWebRTCConnectionAnswer,
sendIceCandidate,
} from "./signalR";
const connections: { [userId: string]: RTCPeerConnection } = {};
const iceServers = { iceServers: [{ urls: "stun:stun.l.google.com:19302" }] };
export async function initiateWebRTCConnection(
userId: string,
recipient: string
): Promise<void> {
const peerConnection = new RTCPeerConnection(iceServers);
peerConnection.addEventListener("icecandidate", (event) => {
console.log("Received Ice candidate for recipient", recipient);
console.log(event);
sendIceCandidate(userId, recipient, event.candidate);
});
connections[recipient] = peerConnection;
const connectionOffer = await peerConnection.createOffer();
peerConnection.setLocalDescription(connectionOffer);
sendWebRTCConnectionOffer(userId, recipient, connectionOffer);
}
export async function handleSentConnectionOffer(
userId: string,
sender: string,
offer: RTCSessionDescription
): Promise<void> {
// set local description
// set remote description
const peerConnection = new RTCPeerConnection(iceServers);
peerConnection.addEventListener("icecandidate", (event) => {
console.log("Received Ice candidate for sender", sender);
console.log(event);
sendIceCandidate(userId, sender, event.candidate);
});
connections[sender] = peerConnection;
peerConnection.setRemoteDescription(offer);
const answer = await peerConnection.createAnswer();
peerConnection.setLocalDescription(answer);
sendWebRTCConnectionAnswer(userId, sender, answer);
}
export async function handleSentConnectionAnswer(
sender: string,
answer: RTCSessionDescription
): Promise<void> {
// set local description
// set remote description
const peerConnection = connections[sender];
// other description
peerConnection.setRemoteDescription(answer);
}
export async function handleRemoteIceCandidate(
sender: string,
candidate: RTCIceCandidate
): Promise<void> {
const peerConnection = connections[sender];
return peerConnection.addIceCandidate(candidate);
}
|
802100eea75ba0b87c843dc56db8b6614fd6ef6c
|
TypeScript
|
LLLLLamHo/zzc-design-mobile
|
/components/Calendar/util/createPickerData.ts
| 2.703125
| 3
|
import {selectTimeInterface} from '../propsType';
import { PickerData, ListData } from '../../Picker/propsType';
import { isString } from '../../_util/typeof';
export default function createPickerData(timeRange, minutesInterval: number, currStartTime: selectTimeInterface, currEndTime: selectTimeInterface, defaultStartTime: string, defaultEndTime: string): Array<PickerData> {
const startTimeRange = isString(timeRange) ? ( JSON.parse(timeRange).left || [0,24]) : timeRange ;
const endTimeRange = isString(timeRange) ? ( JSON.parse(timeRange).right || [0,24]) : timeRange ;
const startPickerHourInfo = _renderPickerDataHour( startTimeRange,currStartTime,defaultStartTime);
const startPickerMinuteInfo = _renderPickerDataMinute( minutesInterval,currStartTime,defaultEndTime);
const endPickerHourInfo = _renderPickerDataHour( endTimeRange,currEndTime,defaultEndTime);
const endPickerMinuteInfo = _renderPickerDataMinute( minutesInterval,currEndTime,defaultEndTime);
const pickerInfo = [
{
className: 'zds-calendar-t-p-s-d',
itemClassName: 'zds-calendar-t-p-s-d-i',
scrollType: '0',
...startPickerHourInfo
},
{
className: 'zds-calendar-t-p-s-t',
itemClassName: 'zds-calendar-t-p-s-t-i',
scrollType: '1',
...startPickerMinuteInfo
},
{
className: 'zds-calendar-t-r-s-d',
itemClassName: 'zds-calendar-t-r-s-d-i',
scrollType: '2',
...endPickerHourInfo
},
{
className: 'zds-calendar-t-r-s-t',
itemClassName: 'zds-calendar-t-r-s-t-i',
scrollType: '3',
...endPickerMinuteInfo
},
];
return pickerInfo;
}
export function _renderPickerData(timeRange: [number, number],minutesInterval: number, currTime: selectTimeInterface, defaultTime: string,): Object {
const [start, end] = timeRange;
const pickerIime: Array<ListData> = [];
const MAX = 23;
let Index = 0;
let selectTime = currTime ? `${currTime.h}:${currTime.m}` : defaultTime;
for (let i = start; i <= end; i++) {
if ( i > MAX) {
break;
}
let step;
if (60 % minutesInterval == 0) {
step = 60 / minutesInterval;
} else {
step = 0;
}
for (let n = 0; n < step; n++) {
const h = i < 10 ? `0${i}` : i;
const m = n * minutesInterval;
if ( i == end && n > 0) {
break;
}
const minutes = m < 10 ? `0${m}`: m;
const c_t = `${i}:${m}`;
const time = `${h}:${minutes}`;
if ( c_t == selectTime) {
Index = pickerIime.length;
}
pickerIime.push({
text: time,
dataKey: time
});
}
}
return {
selectIndex: Index,
listData: pickerIime
}
}
export function _renderPickerDataHour(timeRange: [number, number], currTime: selectTimeInterface, defaultTime: string,): Object {
const [start, end] = timeRange;
const pickerIime: Array<ListData> = [];
const MAX = 23;
let Index = 0;
let selectDay = currTime ? `${currTime.h}` : defaultTime.split(":")[0];
for (let i = start; i <= end; i++) {
if ( i > MAX) {
break;
}
if(selectDay === i.toString()){ Index = i }
pickerIime.push({
text: i > 9 ? i.toString() : '0' + i,
dataKey: i > 9 ? i.toString() : '0' + i
});
}
return {
selectIndex: Index,
listData: pickerIime
}
}
export function _renderPickerDataMinute(minutesInterval: number, currTime: selectTimeInterface, defaultTime: string,): Object {
const pickerIime: Array<ListData> = [];
let Index = 0;
let selectTime = currTime ? `${currTime.m}` : defaultTime.split(":")[1];
let step;
if (60 % minutesInterval == 0) {
step = 60 / minutesInterval;
} else {
step = 0;
}
for (let n = 0; n < step; n++) {
const m = n * minutesInterval;
const minutes = m < 10 ? `0${m}`: m;
const c_t = `${m}`;
const time = `${minutes}`;
if ( c_t == selectTime) {
Index = n;
}
pickerIime.push({
text: time,
dataKey: time
});
}
return {
selectIndex: Index,
listData: pickerIime
}
}
|
55ec99613093292c78a7217c0360bd8f33d18b30
|
TypeScript
|
CodingSpiderFox/pantry_party
|
/src/app/utilities/arrayMove.ts
| 3.140625
| 3
|
export function arrayMove<T>(arr: T[], oldIndex: number, newIndex: number): T[] {
arr = [...arr];
if (newIndex >= arr.length) {
let k = newIndex - arr.length + 1;
while (k--) {
arr.push(undefined);
}
}
arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]);
return arr;
}
|
4a048d91249143538e78587309f186d08960f385
|
TypeScript
|
krzowski/zaiste_umbrella
|
/apps/zaiste_web/assets/js/components/wallet/interfaces.ts
| 2.59375
| 3
|
export interface DatesRange {
startDate: Date
endDate: Date
}
export interface TransactionsFilters {
showIncomes: boolean
showExpenses: boolean
}
export interface TransactionItem {
id: number
name: string
amount: string
}
export interface Transaction {
id: number
name: string
date: string
income: boolean
transactionItems: TransactionItem[]
}
export interface TransactionFormFields {
name: string
date: string
income: string
}
|
c5190c1684ba4bf995f1e9c2d100b22644d2d9ec
|
TypeScript
|
Synthetixio/kwenta
|
/hooks/useDebouncedMemo.ts
| 2.53125
| 3
|
import { useState, useEffect, DependencyList, useCallback } from 'react';
import debounce from 'lodash/debounce';
// source: https://github.com/SevenOutman/use-debounced-memo
export function useDebouncedMemo<T>(
factory: () => T,
deps: DependencyList | undefined,
debounceMs: number
): T {
const [state, setState] = useState(factory());
// eslint-disable-next-line
const debouncedSetState = useCallback(debounce(setState, debounceMs), []);
useEffect(() => {
debouncedSetState(factory());
// eslint-disable-next-line
}, deps);
return state;
}
export default useDebouncedMemo;
|
0b0a7dfcaf1a889ce2449f73117560d1ed2e5f91
|
TypeScript
|
karifrederiksen/ordered-collections
|
/dist/util.d.ts
| 2.796875
| 3
|
export declare function numberLT(l: number, r: number): boolean;
export declare function stringLT(l: string, r: string): boolean;
export declare type LessThan<a> = (key: a, otherKey: a) => boolean;
export declare function compareNumber(l: number, r: number): number;
export declare function compareString(l: string, r: string): number;
|
2b0a1fb158e6009c6f4f51af02734d239c005e7d
|
TypeScript
|
liming/lambda_dynamodb_demo
|
/src/libs/middleware.ts
| 2.578125
| 3
|
/**
* The file defines some useful middlewares
*/
import middy from "@middy/core"
import middyJsonBodyParser from "@middy/http-json-body-parser"
/**
*
* @param handler a lambda function which can be "middified"
* @returns
*/
export const middyfy = (handler) => {
// middyJsonBodyParser is to parse event body from a JSON string into object
// @see https://middy.js.org/packages/http-json-body-parser/
return middy(handler).use(middyJsonBodyParser())
}
|
17424640c96c2d4efd4e7d72ea01935dffbb4925
|
TypeScript
|
ejhayes/graphql-find-options
|
/sample/src/common/dto/paginated-request.ts
| 2.515625
| 3
|
import { Field, Int, ArgsType } from '@nestjs/graphql';
import { Type } from 'class-transformer';
import { ClassType } from 'class-transformer/ClassTransformer';
export default function PaginatedRequest<TWhere, TOrder>(TFilterClass: ClassType<TWhere>, TOrderClass: ClassType<TOrder>) {
@ArgsType()
abstract class PaginatedRequestClass {
@Field(() => Int, { defaultValue: 0, nullable: true })
offset?: number;
@Field(() => Int, { defaultValue: 200, nullable: true })
limit?: number;
@Field(() => TFilterClass, { nullable: true })
@Type(() => TFilterClass)
where?: TWhere;
@Field(() => [TOrderClass], { nullable: true })
@Type(() => TOrderClass)
order?: TOrder[];
}
return PaginatedRequestClass;
}
|
86ea3533c109521a073ed3a3108472804684928a
|
TypeScript
|
luchaohai/typescript-review
|
/BasicTypes/demo2.ts
| 4.21875
| 4
|
// TODO 初级「基础类型」
// let arr1:number []= [1,2,3]
// let arr2:(number|string)[] = [1, "str", '123']
// let arr3:Array<number|null> = [null, 123]
// let arr4:any[] = [123, 'string', false]
// TODO 中级「自定义类型」
// 类自定义类型[初级]
// class Person {
// name:string
// constructor(name:string) {
// this.name = name
// }
// }
// const item = {name: 'hello', age: 12} // 实际结构符合也可以作为符合类型校验(包含)
// let arr6:Array<Person> = [item]
// 类自定义类型[高级]
// class Person {
// name: string
// constructor(name: string) {
// this.name = name
// }
// }
// class Man extends Person {
// constructor(name: string) {
// super(name)
// }
// }
// const item = new Man("小白")
// let arr6: Array<Person> = [item]
// 不同版本内置了特殊的接口
// let arrReadonly: ReadonlyArray<number> = [1]
// let prettySure: Object = 4;
// 接口自定义类型[初级]
// interface Item {
// name: string
// age: number
// }
// let arr5: Array<Item> = [{name: 'dd', age: 18, date: 'hehe'} as Item]
// 接口自定义类型[高级]
interface Item {
name: string
age: number
}
interface SItem extends Item {
tall: number
}
// demo1
// let item: Item = {name: 'dd', age: 18}
// let arr5: Array<Item> = [item]
// demo2
// let item: SItem = {name: 'dd', age: 18, tall: 8}
// let arr5: Array<Item> = [item]
// demo3
// let item: object = {name: 'dd', age: 18, tall: 8}
// let arr5: Array<Item> = [item]
// demo4
// let item = {name: 'dd', age: 18, tall: 8}
// let arr5: Array<Item> = [item]
// TODO 高级「泛型」
// interface Item {
// name: string
// age: number
// }
// class myArr<T> {
// arr: Array<T>
// constructor() {
// this.arr = []
// }
// addItem(item: T) {
// this.arr.push(item)
// }
// }
// let arr7 = new myArr<Item>()
|
806f0dcc66a292ee6703ee8f102cb49043935cd3
|
TypeScript
|
Wangpengli0419/yg_league
|
/client/src/game/view/panel/scene/core/BattleCheck.ts
| 3
| 3
|
/**
* 前后端数据检测方法(有些属性客户端,服务器端的定义不同)
* Created by hh on 2016/11/30.
*/
module fight{
export function check(clientObj, serverObj) {
let result = true;
if (!clientObj || !serverObj || clientObj.length == 0 || serverObj.length == 0) {
return result;
}
let clientArr = clientObj.concat();
let serverArr = serverObj.concat();
console.group("------------报告检测-------------");
let clientLen = clientArr.length;
let serverLen = serverArr.length;
if (clientLen != serverLen) {
console.warn(`客户端战报步数:${clientLen} 服务器端战报步数:${serverLen}`);
}
const len = Math.min(clientLen, serverLen);
const props = fight.CHECK_PROP.split(",");
for (let i = 0; i < len; i ++) {
let clientItem = clientArr[i];
let serverItem = serverArr[i];
let ok:boolean = true;
for (let j = 0; j < props.length - 1; j++) {
let prop = props[j];
if (!checkProp(clientItem[prop], serverItem[prop])) {
ok = false;
result = false;
console.warn(`step:${i},pos:${clientItem["pos"]},prop:${prop},client:${String(clientItem[prop])},server:${String(serverItem[prop])}`);
break;
}
}
if (ok) {
let clientTarget = clientItem.target || [];
let serverTarget = serverItem.target || [];
if (clientTarget.length != serverTarget.length && clientTarget.length > 0) {
console.warn(`step:${i},prop:targetCount,client:${clientTarget.length},server:${serverTarget.length}`);
} else {
for (let k = 0; k < clientTarget.length; k++) {
for (let j = 0; j < props.length - 1; j++) {
let prop = props[j];
if (!checkProp(clientTarget[k][prop], serverTarget[k][prop])) {
result = false;
console.warn(`step:${i},pos:${clientTarget[k]["pos"]},prop:${prop},client:${String(clientTarget[k][prop])},server:${String(serverTarget[k][prop])}`);
break;
}
}
}
}
}
}
if (!result) {
console.warn(clientArr, serverArr);
}
console.groupEnd();
return result;
}
/**
* 检测属性
* @param clientValue
* @param serverValue
* @returns {boolean}
*/
function checkProp(clientValue:any, serverValue:any){
if (parseInt(clientValue) === clientValue && parseInt(serverValue) === serverValue) {
return clientValue == serverValue;
}
if (Array.isArray(serverValue)) {
if (clientValue.length == 0) return true;
return String(clientValue.sort()) == String(serverValue.sort());
}
let value0:string = String(clientValue);
let value1:string = String(serverValue);
if (value0 == value1) {
return true;
} else {
let value0Arr = value0.split(",");
let value1Arr = value1.split(",");
if (value0Arr.length > 1 || value1Arr.length > 1) {
return false;
} else {
return BigNum.equal(Number(clientValue), BigNum.max(0, Number(serverValue))) ||
MathUtil.easyNumber(Number(clientValue)) == MathUtil.easyNumber(Number(serverValue)) ||
BigNum.equal(clientValue, serverValue) ||
BigNum.greater(BigNum.sub(clientValue, serverValue), 0.00001) && BigNum.greater(0, BigNum.sub(clientValue, serverValue)) ||
BigNum.greater(BigNum.sub(serverValue, clientValue), 0.00001) && BigNum.greater(0, BigNum.sub(serverValue, clientValue));
}
}
}
}
|
71214e94c7e02f00659c6b71a0eaf9772bc7141f
|
TypeScript
|
grimsi/website
|
/script/services/BootscreenService.ts
| 2.59375
| 3
|
import {UtilityService} from "./UtilityService";
export class BootscreenService{
public startBootSequence(): void {
}
public finishBootSequence(): void {
const bootscreen: HTMLElement | null = document.getElementById("bootscreen");
if(bootscreen) {
setTimeout(() => {
if (bootscreen.parentNode) bootscreen.parentNode.removeChild(bootscreen);
}, UtilityService.random(3,5) * 1000);
}
}
}
|
0ead6ea2f439490fa2472f5998483ad073325273
|
TypeScript
|
EdwardHinkle/whereisfelix.today
|
/index.ts
| 2.59375
| 3
|
import * as express from "express";
var needle = require("needle");
var moment = require("moment");
var ical = require("ical");
var app = express();
app.use(function(req, res, next) {
// Website you wish to allow to connect
res.setHeader("Access-Control-Allow-Origin", "https://whereisfelix.today");
// Request methods you wish to allow
res.setHeader("Access-Control-Allow-Methods", "GET");
// Request headers you wish to allow
res.setHeader(
"Access-Control-Allow-Headers",
"X-Requested-With,content-type"
);
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader("Access-Control-Allow-Credentials", true);
// Pass to next layer of middleware
next();
});
// Metadata
let nomadlistUser = "krausefx";
let moodHostUrl = "https://krausefx-mood.herokuapp.com/";
let facebookId = "100000723486971";
let googleMapsKey = "AIzaSyDeiw5iiluUP6Txt7H584no1adlsDj-jUc";
// Interfaces
interface Conference {
location: String;
dates: String;
link: String;
name: String;
}
interface Stay {
name: String;
from: String;
for: String;
toDate: Date;
fromDate: Date;
}
interface Photo {
text: String;
url: String;
link: String;
}
// Cache
let currentCityText: String = null;
let currentLat: Number = null;
let currentLng: Number = null;
let nextCityText: String = null;
let nextCityDate: String = null;
let nextStays: Array<Stay> = [];
let currentMoodLevel: String = null;
let currentMoodEmoji: String = null;
let currentMoodRelativeTime: String = null;
let nextEvents: Array<any> = [];
let nextConferences: Array<Conference> = [];
let recentPhotos: Array<Photo> = null;
let isMoving: Boolean;
// Refresher methods
function updateNomadListData() {
nextStays = [];
let nomadlistUrl = "https://nomadlist.com/@" + nomadlistUser + ".json";
needle.get(nomadlistUrl, function(error, response, body) {
if (error) {
console.log(error);
} else if (response.statusCode == 200) {
let parsedNomadListData = JSON.parse(body);
let now = parsedNomadListData["location"]["now"];
let next = parsedNomadListData["location"]["next"];
if (now["date_start"] == moment().format("YYYY-MM-DD")) {
// Today I'm switching cities, let's show a "moving" status on the website
let previous = parsedNomadListData["location"]["previously"];
currentCityText = "✈️ " + now["city"];
isMoving = true;
} else {
currentCityText = now["city"] + ", " + now["country_code"];
isMoving = false;
}
currentLat = now["latitude"];
currentLng = now["longitude"];
nextCityText = next["city"];
nextCityDate = moment(next["date_start"]).fromNow();
for (let index in parsedNomadListData["trips"]) {
let currentStay = parsedNomadListData["trips"][index];
if (currentStay["epoch_start"] > new Date().getTime() / 1000) {
nextStays.unshift({
name: currentStay["place"] + ", " + currentStay["country"],
from: moment(currentStay["epoch_start"] * 1000).fromNow(),
fromDate: moment(currentStay["epoch_start"] * 1000),
for: currentStay["length"],
toDate: moment(currentStay["epoch_end"] * 1000)
});
}
}
console.log("Successfully loaded nomadlist data");
}
});
}
function updateMood() {
let moodUrl = moodHostUrl + "current_mood.json";
needle.get(moodUrl, function(error, response, body) {
if (error) {
console.log(error);
} else if (response.statusCode == 200) {
let parsedBody = JSON.parse(body);
switch (parseInt(parsedBody["value"])) {
case 5:
currentMoodLevel = "pumped, energized";
currentMoodEmoji = "🤩";
break;
case 4:
currentMoodLevel = "happy, excited";
currentMoodEmoji = "😃";
break;
case 3:
currentMoodLevel = "good, alright";
currentMoodEmoji = "😎";
break;
case 2:
currentMoodLevel = "okay";
currentMoodEmoji = "🙃";
break;
case 1:
currentMoodLevel = "okay";
currentMoodEmoji = "🙃";
break;
case 0:
currentMoodLevel = "okay";
currentMoodEmoji = "🙃";
break;
}
currentMoodRelativeTime = moment(new Date(parsedBody["time"])).fromNow();
}
});
}
function fetchMostRecentPhotos() {
let facebookUrl =
"https://graph.facebook.com/v2.12/" +
process.env.FACEBOOK_USER_ID +
"/photos";
needle.request(
"get",
facebookUrl,
"type=uploaded&fields=name,images,link&limit=8",
{
headers: {
Authorization: "Bearer " + process.env.FACEBOOK_ACCESS_TOKEN
}
},
function(error, response, body) {
if (response.statusCode == 200) {
recentPhotos = [];
let mostRecentData = response["body"]["data"];
for (var i in mostRecentData) {
let currentPhoto = mostRecentData[i];
recentPhotos.push({
text: currentPhoto["name"],
url: currentPhoto["images"][0]["source"],
link: currentPhoto["link"]
});
}
} else {
console.log(error);
console.log(response);
}
}
);
}
function updateCalendar() {
nextEvents = [];
let icsUrls = [process.env.ICS_URL, process.env.WORK_ICS_URL];
for (let index in icsUrls) {
ical.fromURL(icsUrls[index], {}, function(err, data) {
console.log("Loaded calendar data");
for (var k in data) {
if (data.hasOwnProperty(k)) {
var ev = data[k];
// only use calendar invites that within the next 7 days
if (
ev["type"] == "VEVENT" &&
moment(ev["start"]).isBetween(
new Date(),
moment(new Date()).add(5, "days")
) &&
moment(ev["end"]).diff(ev["start"], "hours") < 24 // we don't want day/week long events
) {
nextEvents.push({
rawStart: moment(ev["start"]),
start: moment(ev["start"]).fromNow(),
end: moment(ev["end"]).fromNow(),
duration:
Math.round(
moment(ev["end"]).diff(ev["start"], "hours", true) * 10.0
) / 10.0
});
}
}
}
nextEvents.sort(function(a, b) {
return a["rawStart"] - b["rawStart"];
});
});
}
}
function updateConferences() {
// TODO: fetch them from https://github.com/KrauseFx/speaking
nextConferences = [
{
location: "Vienna, Austria",
dates: "16 - 18 May",
name: "WeAreDevs",
link: "https://www.wearedevelopers.com/congress/"
}
];
}
function generateMapsUrl() {
return (
"https://maps.googleapis.com/maps/api/staticmap?center=" +
currentCityText +
"&zoom=10&size=1200x190&scale=2&maptype=roadmap" +
"&key=" +
googleMapsKey
);
}
function allDataLoaded() {
if (currentCityText == null || nextCityText == null || nextCityDate == null) {
return false;
}
if (nextStays.length == 0) {
// nextEvents.length == 0 // doesn't work if a got nothing on my calendar
return false;
}
if (currentMoodLevel == null) {
return false;
}
// if (recentPhotos == null) {
// return false;
// }
return true;
}
setInterval(updateNomadListData, 60 * 60 * 1000);
setInterval(updateMood, 30 * 60 * 1000);
setInterval(fetchMostRecentPhotos, 30 * 60 * 1000);
setInterval(updateCalendar, 15 * 60 * 1000);
fetchMostRecentPhotos();
updateNomadListData();
updateMood();
updateCalendar();
updateConferences();
function getDataDic() {
return {
currentCityText: currentCityText,
nextCityText: nextCityText,
nextCityDate: nextCityDate,
currentMoodLevel: currentMoodLevel,
currentMoodEmoji: currentMoodEmoji,
currentMoodRelativeTime: currentMoodRelativeTime,
nextConferences: nextConferences,
nextEvents: nextEvents,
nextStays: nextStays,
isMoving: isMoving,
mapsUrl: generateMapsUrl(),
localTime: moment()
.add(2, "hours")
.format("hh:mm a"), // TODO: actually take the current time zone
profilePictureUrl:
"https://graph.facebook.com/" + facebookId + "/picture?type=large",
recentPhotos: recentPhotos
};
}
// // Web server
// app.get("/", function(req, res) {
// // Because we're using the free Heroku tier for now
// // this means the server might just have started up
// // if that's the case, we'll have to wait until all data
// // is fetched
// if (allDataLoaded()) {
// res.render("pages/index", getDataDic());
// } else {
// res.render("pages/loading");
// }
// });
app.get("/api.json", function(req, res) {
if (allDataLoaded()) {
res.json(getDataDic());
} else {
res.json({
loading: true
});
}
});
var port = process.env.PORT || 8080;
app.listen(port);
console.log("server live on port " + port);
|
2c46deeaa652aee5a25399e3532fb7fa91dbf465
|
TypeScript
|
elevu/clinical-genomics-ui
|
/src/api/GitHubApi.ts
| 2.671875
| 3
|
import { OpenNotification } from '../components/Toaster'
const gitHubURL = 'https://api.github.com/'
export type ApiUser = {
role: string
username: string
email: string
status: string
}
type GetUsersResponse = {
users: Array<ApiUser>
}
export const getRepos = async (): Promise<GetUsersResponse> => {
let response = { users: [] as any }
try {
const request = await fetch(`${gitHubURL}orgs/Clinical-Genomics/repos`, {
mode: 'cors',
})
response = await request.json()
} catch (error) {
OpenNotification({
type: 'error',
message: 'Unable to fetch',
description: 'Could not fetch GitHub repos',
})
}
return response
}
|
a705405990dbf5f35ecb7a95b36dd7ba072edd45
|
TypeScript
|
pegaltier/rxjs-primitives
|
/libs/rxjs/string/src/lib/char-code-at.ts
| 3.84375
| 4
|
/**
* @packageDocumentation
* @module string
*/
import { Observable, OperatorFunction } from 'rxjs';
import { map } from 'rxjs/operators';
/**
* The `charCodeAt` operator can be used with an {@link https://rxjs-dev.firebaseapp.com/guide/observable|Observable} string
* value and returns a number of the ASCII code for the character
*
* @param position The character position to return a character code from
*
* @remarks
* Based on [String.prototype.charCodeAt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charCodeAt)
* The position number passed starts from 0
*
* @example
* ```ts
* from(['abcde'])
* .pipe(charCodeAt(4))
* .subscribe(....) // [101]
* ```
*
* @returns The character code of the character located at the passed position
* @category RxJS String Query
*/
export function charCodeAt(position: number): OperatorFunction<string, number> {
return (source: Observable<string>) => source.pipe(map((value) => value.charCodeAt(position)));
}
|
1133b9630935cf06f034e5aa85622f872bc22ccd
|
TypeScript
|
greeeg/paris-subway-map
|
/src/types.ts
| 2.734375
| 3
|
export interface StationLiaison {
id: string;
uuid: string;
}
export interface Station {
uuid: string;
name: string;
geolocation: number[];
accessibility: {
vision: boolean;
mobility: boolean;
};
// List of RATP stations ids
stations: string[];
}
export interface Line {
id: string;
name: string;
code: string;
stations: StationLiaison[];
color: string;
icon: string;
}
export type Stations = {
[key in string]: Station;
};
export type Lines = {
[key in string]: Line;
};
|
68eb03fb93d8dffffbca78f12710eebec5bea5c5
|
TypeScript
|
Ravina1604/File-Upload
|
/file-upload/src/api/fileApi.ts
| 2.796875
| 3
|
import axios from "axios";
const FormData = require("form-data");
interface File {
fieldname: string;
originalname: string;
encoding: string;
mimetype: string;
destination: string;
filename: string;
path: string;
size: number;
}
class FileAPI {
private files: File[] = [];
private url = "http://localhost:9000/files/";
constructor() {
this.get().then((files) => (this.files = files));
}
upload = async (file: any) => {
const form_data = new FormData();
form_data.append("file", file);
return axios
.post(this.url, form_data, {
headers: form_data.getHeaders(),
})
.then(async (res) => {
let {
data: { file },
} = res;
this.files.push({ ...file });
return { success: true };
})
.catch((err) => {
throw err;
});
};
remove = (name: string) => {
return axios
.delete(this.url + name)
.then(async (res) => {
let {
data: { fileId },
} = res;
this.files = this.files.filter((item) => item.filename !== fileId);
return fileId;
})
.catch((err) => {
return { error: true };
});
};
get = () => {
return axios
.get(this.url)
.then(async (res) => {
this.files = res.data.files;
return this.files;
})
.catch((err) => {
throw err;
});
};
}
const api = new FileAPI();
export default api;
|
79eb9088bb0f5b6012b6216cb1c1d19adea8f480
|
TypeScript
|
Sixing/TerisGame
|
/src/core/TerisRule.ts
| 3.4375
| 3
|
/**
* 该类中提供一系列的函数,根基游戏规则判断各种情况
*/
import {Shape, Point, MoveDirection }from './Types'
import {SquareGroup} from './SquareGroup'
import GameConfig from './GameConfig'
function isPoint(obj: any): obj is Point{
if(typeof obj.x === 'undefined') {
return false
}
return true
}
export class TerisRule {
/**
* 判断某个形状的方块,是否能够移动到目标位置
*/
static canIMove(shape: Shape, targetPoint: Point): boolean{
//假设,中心店已经移动到了目标位置,算出每个小方块的坐标
const targetSquarePoints: Point[] = shape.map(item => {
return {
x: item.x + targetPoint.x,
y: item.y + targetPoint.y
}
})
//边界判断
const result = targetSquarePoints.some(p => {
//是否超出边界
if( p.x < 0 || p.x > GameConfig.panelSize.width -1 ||
p.y < 0 || p.y > GameConfig.panelSize.height - 1
){
return true
}
return false
})
if(result){
return false
}
return true
}
static move(teris: SquareGroup, targetPoint:Point):boolean;
static move(teris: SquareGroup, direction:MoveDirection):boolean;
static move(teris: SquareGroup, targetPointOrDirection: Point| MoveDirection): boolean {
if(isPoint(targetPointOrDirection)) {
if(this.canIMove(teris.shape, targetPointOrDirection)) {
teris.centerPoint = targetPointOrDirection;
return true
}
return false
}else {
const direction = targetPointOrDirection;
let targetPoint;
if(direction === MoveDirection.down) {
targetPoint = {
x: teris.centerPoint.x,
y: teris.centerPoint.y + 1
}
}else if(direction === MoveDirection.left) {
targetPoint = {
x: teris.centerPoint.x - 1,
y: teris.centerPoint.y
}
}else if(direction === MoveDirection.right) {
targetPoint = {
x: teris.centerPoint.x + 1,
y: teris.centerPoint.y
}
}else {
targetPoint = {
x: teris.centerPoint.x ,
y: teris.centerPoint.y - 1
}
}
return this.move(teris, targetPoint)
}
}
/**
* 将当前的方块,移动到目标方向的重点
* @param teris
* @param direction
*/
static moveDirectly(teris: SquareGroup, direction:MoveDirection) {
while(true) {
if(!this.move(teris, direction)) {
break
}
}
}
static rotate(teris: SquareGroup):boolean {
const newShape = teris.afterRotateShape();
if(this.canIMove(newShape, teris.centerPoint)) {
teris.rotate()
return true
}else {
return false
}
}
}
|
55ed55dabc1db1232d15dee233cc5fb6b751e53a
|
TypeScript
|
oliver3/goedemorgenbot
|
/src/engine.ts
| 2.84375
| 3
|
import * as Promise from 'bluebird';
import { log } from './common/log';
import { Message } from 'telegram-api-types';
export type CommandFunction = (msg: Message, ...args: string[]) => Promise<string[]>;
export type RespondFunction = (msg: Message, responses: string[]) => Promise<any>;
export const handleMessage = (commands: [string, CommandFunction][]) => (respond: RespondFunction, msg: Message) => {
log(`@${msg.from.username} => ${msg.text}`);
const command = commands.find(([cmd, fn]) => !!msg.text.match(cmd));
if (!command) {
log(`@${msg.from.username} <= ????`);
return respond(msg, ['Ik begrijp niet wat je zegt.. Probeer eens <b>/storingen</b> of <b>trein utln asd</b>']);
}
const [, ...args] = msg.text.match(command[0]);
const fn = command[1];
return fn(msg, ...args)
.then((replies) => respond(msg, replies))
.catch((err) => {
log(`!! Error while handling "@${msg.from.username} => ${msg.text}"`);
log(err);
return respond(msg, [
err && err.message || 'Something went really wrong..',
err && err.error && err.error.message
]);
})
}
|
1b4ee0f4ee091d90c7827de222767de80f1de908
|
TypeScript
|
wuzzabi/price-monitoring-ipz
|
/backend/src/services/product.service.ts
| 2.734375
| 3
|
import HttpException from "@exceptions/HttpException"
import { Products } from "@models/products.model"
import IProduct from '@interfaces/products.interface'
import { isNumber } from "util"
export default class ProductService {
constructor() {}
public async getProductsByCategory(categoryId: number): Promise<IProduct[]> {
categoryId = isNumber(categoryId) ? categoryId : 1
const findProducts: IProduct[] = await Products.findAll({
where: {category_id: categoryId},
attributes: ['id', 'name', 'url_img']
})
if(!findProducts) throw new HttpException(404, 'No products found with this category!')
return findProducts
}
public async createProduct(productData: IProduct): Promise<IProduct> {
const { name, url_img, unit_id, category_id } = productData
if(!(name && unit_id && category_id)) throw new HttpException(409, 'Please enter required data!')
const findProduct: IProduct = await Products.findOne({ where: { name, unit_id, category_id } })
if(findProduct) throw new HttpException(409, 'Product already exists!')
const createProductData = await Products.create({ name, url_img, unit_id, category_id })
return createProductData
}
public async deleteProduct(productId: number): Promise<boolean> {
const findProduct: IProduct = await Products.findOne({ where: { id: productId } })
if(!findProduct) throw new HttpException(404, 'Such product doesn`t exist!')
const delProduct = await Products.destroy({
where: { id: productId }
})
return true
}
public async updateProduct(productId: number, productData: IProduct): Promise<boolean> {
const findProduct = await Products.findOne({ where: { id: productId } })
if(!findProduct) throw new HttpException(404, 'Such product doesn`t exist!')
const updProduct = await Products.update(
productData, {
where: {
id: productId
}}
)
return true
}
}
|
15f4f73b962f6e90a018ec4ba160375899fd3607
|
TypeScript
|
Emobe/croupier
|
/src/Deck.ts
| 3.390625
| 3
|
import { default as Card, Rank, Suit, ranks, suits } from './Card';
interface DeckOptions {
seed?: number;
shuffle?: boolean;
jokers?: boolean;
}
export default class Deck {
private cards: Card[] = [];
/**
* Create a deck of cards
*/
constructor(options: DeckOptions = {}) {
// TODO add jokers
const { seed = Math.random(), shuffle = true } = options;
for (const suit of suits) {
for (const rank of ranks) {
this.cards.push(new Card(suit, rank));
}
}
if (shuffle) {
this.shuffle(seed);
}
}
get Cards(): Card[] {
return this.cards;
}
get Count(): number {
return this.cards.length;
}
public take(amount: number): Card[] {
return this.cards.splice(-Math.abs(amount), amount);
}
public shuffle(seed = Math.random()): void {
let currentIndex = this.cards.length;
let temporaryValue;
let randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(seed * currentIndex);
currentIndex -= 1;
temporaryValue = this.cards[currentIndex];
this.cards[currentIndex] = this.cards[randomIndex];
this.cards[randomIndex] = temporaryValue;
}
}
}
|
78cea1517b62673e3d8149f1f199b5dcbd9b8236
|
TypeScript
|
ray-kay/trip
|
/src/app/shared/helpers.ts
| 2.96875
| 3
|
import {Destination} from './model/destination';
export class Helpers {
static moveArrayElement(arr: any[], old_index: number, new_index: number): any[] {
while (old_index < 0) {
old_index += arr.length;
}
while (new_index < 0) {
new_index += arr.length;
}
if (new_index >= arr.length) {
let k = new_index - arr.length;
while ((k--) + 1) {
arr.push(undefined);
}
}
arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
return arr;
}
static setGeoCoderResultToDestination(result: google.maps.GeocoderResult, destination: Destination): Destination {
destination.fullAddress = result.formatted_address;
if (result.types) {
switch (true) {
case ['premise', 'street_address'].indexOf(result.types[0]) > -1 : // if street level take city
destination.title = result.address_components[2].short_name;
break;
case ['administrative_area_level_1'].indexOf(result.types[0]) === -1 && result.address_components.length > 1 :
// if not administrative_area_level_1 use index 1;
destination.title = result.address_components[1].short_name;
break;
}
}
destination.geocoderResult = result;
return destination;
}
static setPlaceResultToDestination(result: google.maps.places.PlaceResult, destination: Destination): Destination {
destination.fullAddress = result.formatted_address;
destination.title = result.name;
destination.placeResult = {
place_id: result.place_id,
url: result.url,
rating: result.rating || null
};
return destination;
}
}
|
d5dcf23c1cfaa4428a1a5d01d7420a7ad5f5ba2f
|
TypeScript
|
cristianmercado19/Redux-vanilla-js
|
/cart/actions/cart-reducer-initializer.ts
| 2.53125
| 3
|
import { UpdateShippingAddressReducer } from './update-shipping-address/update-shipping-address-action';
import { CartReducer } from './cart-reducer';
import { RequestOrderItemsProgressReducer } from './request-order-items-progress/request-order-items-progress-action';
import { UpdateOrderItemsReducer } from './update-order-items/update-order-items-action';
export class CartReducerInitializer {
private reducersByClassName: { [id: string]: CartReducer<any>; } = {};
constructor() {
this.addReducer(new UpdateShippingAddressReducer())
this.addReducer(new RequestOrderItemsProgressReducer())
this.addReducer(new UpdateOrderItemsReducer())
}
private addReducer(reducer: CartReducer<any>) {
const reducerTypeName = reducer.constructor.name;
this.reducersByClassName[reducerTypeName] = reducer;
}
getReducerByName(reducerTypeName: string): CartReducer<any> {
const handler = this.reducersByClassName[reducerTypeName]
return handler;
}
}
|
edff58c15f8ee2eb1b53dc88d25c6affa17e41bb
|
TypeScript
|
vitaliipetrunenko/substrataTest
|
/code/src/store/bitcoin/main.reducer.ts
| 2.921875
| 3
|
import {
BitcoinActions,
DECREASE_BITCOIN_PRICE,
INCREASE_BITCOIN_PRICE,
PURCHASE_BITCOIN,
SELL_BITCOIN,
TAKE_DEPOSIT,
TAKE_WITHDRAWAL,
} from "./main.types";
import { History, historyService } from "./history.service";
export type BitcoinState = {
balance: number;
bitcoins: number;
bitcoinPrice: number;
history: History[];
};
const initialState: BitcoinState = {
balance: 200,
bitcoins: 0,
bitcoinPrice: 1000,
history: [],
};
export const mainReducer = (
state: BitcoinState = initialState,
action: BitcoinActions
): BitcoinState => {
const spreadState = {
...state,
history: [historyService(action), ...state.history],
};
switch (action.type) {
case TAKE_DEPOSIT:
return {
...spreadState,
balance: state.balance + 100,
};
case TAKE_WITHDRAWAL:
return {
...spreadState,
balance: state.balance - 100,
};
case PURCHASE_BITCOIN:
return {
...spreadState,
balance: state.balance - state.bitcoinPrice,
bitcoins: state.bitcoins + 1,
};
case SELL_BITCOIN:
return {
...spreadState,
balance: state.balance + state.bitcoinPrice,
bitcoins: state.bitcoins - 1,
};
case INCREASE_BITCOIN_PRICE:
return {
...spreadState,
bitcoinPrice: state.bitcoinPrice + 1000,
};
case DECREASE_BITCOIN_PRICE:
return {
...spreadState,
bitcoinPrice: state.bitcoinPrice - 1000,
};
default:
return state;
}
};
|
3b90b3fcbede5e554b19742f97294eb14eab03e9
|
TypeScript
|
AshrafSharf/building-observable
|
/simple-observable/SimpleObservable.ts
| 2.75
| 3
|
function SimpleObservable(observerSetupFunction) {
this.observerSetupFunction = observerSetupFunction;
}
SimpleObservable.prototype.subscribe = function (subscriber) {
let observer = {
next: function (data) {
subscriber(data);
}
}
this.observerSetupFunction(observer);
}
export default SimpleObservable;
|
1115dd582648dba601ea95350d6228a944d4eddf
|
TypeScript
|
GitbookIO/proxies-on-cloudflare
|
/src/firebase/types.ts
| 2.625
| 3
|
export interface FirebaseConfig {
rewrites: FirebaseRewrites;
}
export interface FirebaseRewrites extends Array<FirebaseRewrite> {}
export interface FirebaseFunctionRewrite {
source: string;
function: string;
}
export interface FirebaseDestinationRewrite {
source: string;
destination: string;
}
export type FirebaseRewrite =
| FirebaseFunctionRewrite
| FirebaseDestinationRewrite;
|
fbd11fbf3fcb0f8034abaef9577ae893004b89aa
|
TypeScript
|
K4M1s/typing-grinder
|
/resources/js/TypingField/Letter.ts
| 3.8125
| 4
|
/**
* Letter type
*/
export enum LETTER_TYPE {
PLACEHOLDER,
TYPED_LETTER
}
/**
* Letter class
*/
export default class Letter {
private letter: string;
private typedLetter: string | null = null;
private element: HTMLElement;
/**
* Creates an instance of letter
* @param letter Letter string
* @param letterType Letter type
*/
constructor(letter: string, letterType: LETTER_TYPE) {
this.letter = letter;
this.element = document.createElement('span');
this.createElement(letterType);
}
/**
* Creates element
* @param letterType Type of letter
*/
createElement(letterType: LETTER_TYPE) {
this.element.classList.add('typing-field__letter');
switch(letterType) {
case LETTER_TYPE.PLACEHOLDER:
this.element.classList.add("typing-field__letter--placeholder")
break;
case LETTER_TYPE.TYPED_LETTER:
this.element.classList.add("typing-field__letter--typed")
break;
}
if (this.letter == " ") {
this.element.innerHTML = " ";
} else {
this.element.innerText = this.letter;
}
}
/**
* Gets letter
* @returns String representation of letter
*/
getLetter(): string {
return this.letter;
}
/**
* Gets element
* @returns HTML Element
*/
getElement(): HTMLElement {
return this.element;
}
/**
* Gets typed letter
* @returns typed letter
*/
getTypedLetter(): string | null {
return this.typedLetter;
}
/**
* Sets typed letter
* @param letter typed letter (null if removed)
*/
setTypedLetter(letter: string | null): void {
this.typedLetter = letter;
if (this.typedLetter != null) {
this.element.classList.add("typing-field__letter--typed")
this.validate();
} else {
this.element.classList.remove("typing-field__letter--typed")
this.setNormal();
}
}
/**
* Set letter as correct
*/
setCorrect(): void {
this.element.classList.remove('typing-field__letter--incorrect');
this.element.classList.add('typing-field__letter--correct');
}
/**
* Set letter as incorrect
*/
setIncorrect(): void {
this.element.classList.remove('typing-field__letter--correct');
this.element.classList.add('typing-field__letter--incorrect');
}
/**
* Set letter as normal (without background)
*/
setNormal(): void {
this.element.classList.remove('typing-field__letter--correct');
this.element.classList.remove('typing-field__letter--incorrect');
}
/**
* Display cursor on this letter (only visual)
*/
setCursor(): void {
this.element.classList.add('typing-field__letter--cursor');
}
/**
* Removes cursor
*/
removeCursor(): void {
this.element.classList.remove('typing-field__letter--cursor');
}
/**
* Determines whether typed letter is valid
* @returns true if valid
*/
isValid(): boolean {
return this.typedLetter == this.letter;
}
/**
* Validates letter (adds background)
* @returns true if validate
*/
validate(): boolean {
if (this.isValid()) {
this.setCorrect();
return true;
} else {
this.setIncorrect();
return false;
}
}
/**
* Appends element to parent
* @param parent Parent HTML Element
*/
appendElement(parent: HTMLElement): void {
parent.appendChild(this.element);
}
}
|
272066a067fa9503dfb29ff545bee06c9586a3e4
|
TypeScript
|
brandynm34/SPEDcal
|
/src/mocks/providers/items.ts
| 2.703125
| 3
|
import { Injectable } from '@angular/core';
import { Item } from '../../models/item';
@Injectable()
export class Items {
items: Item[] = [];
defaultItem: any = {
"name": "Burt Bear",
"profilePic": "assets/img/speakers/bear.jpg",
"groupNumber": "Group 1",
};
constructor() {
let items = [
{
"name": "Johnny Smith",
"profilePic": "assets/img/speakers/boy1.jpg",
"groupNumber": "4"
},
{
"name": "Susie Baker",
"profilePic": "assets/img/speakers/girl1.jpg",
"groupNumber": "3"
},
{
"name": "Devin Atmoore",
"profilePic": "assets/img/speakers/boy2.jpg",
"groupNumber": "1"
},
{
"name": "Eva Townsend",
"profilePic": "assets/img/speakers/girl2.jpg",
"groupNumber": "5"
},
{
"name": "Theo Menefee",
"profilePic": "assets/img/speakers/boy3.jpg",
"groupNumber": "2"
},
{
"name": "Ellie Phillips",
"profilePic": "assets/img/speakers/girl3.jpg",
"groupNumber": "3"
},
{
"name": "Eric Hatmaker",
"profilePic": "assets/img/speakers/boy4.jpg",
"groupNumber": "2"
},
{
"name": "Mary Altmire",
"profilePic": "assets/img/speakers/girl4.jpg",
"groupNumber": "1"
},
{
"name": "Grant Copeland",
"profilePic": "assets/img/speakers/boy5.jpg",
"groupNumber": "5"
},
{
"name": "Sandy Jackson",
"profilePic": "assets/img/speakers/girl5.jpg",
"groupNumber": "3"
},
];
for (let item of items) {
this.items.push(new Item(item));
}
}
query(params?: any) {
if (!params) {
return this.items;
}
return this.items.filter((item) => {
for (let key in params) {
let field = item[key];
if (typeof field == 'string' && field.toLowerCase().indexOf(params[key].toLowerCase()) >= 0) {
return item;
} else if (field == params[key]) {
return item;
}
}
return null;
});
}
add(item: Item) {
this.items.push(item);
}
delete(item: Item) {
this.items.splice(this.items.indexOf(item), 1);
}
}
|