Datasets:

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
6bf6b9654bcad5fce4f233464afaa07c5c067f2a
TypeScript
omkarrepal/angular-seed
/src/app/user/user.ts
2.5625
3
export class User{ constructor( public id:number=Math.floor(Math.random()*100), public name:string="", public email:string="", public editable:boolean=false ){} }
96214ad8633bebc47520bcff11acab6f792af59d
TypeScript
tierklinik-dobersberg/cliny
/src/utils/request-context.ts
2.828125
3
import {Request} from 'restify'; export class Context { private _values: {[key: string]: any} = {}; get<T>(name: string): T|undefined { return this._values[name]; } set(name: string, value: any): this { this._values[name] = value; return this; } } declare module 'restify' { interface Request { context?: Context; } } export function getContext(request: Request): Context { let context: Context|undefined = request.context; if (!context) { context = new Context(); request.context = context; } return context; }
9427ffca63f460e5863d6acd3e4f58b3a757e006
TypeScript
strax/bonsai
/packages/core/src/Identity.ts
3.3125
3
import { Generic, Generic1, Kind1, TypeFamily } from "tshkt" interface IdentityF extends TypeFamily<Kind1> { (): Identity<this[0]> } export class Identity<A> { [Generic.Type]!: Generic1<IdentityF, A>; ["constructor"]!: typeof Identity static of<A>(a: A): Identity<A> { return new Identity(a) } constructor(private value: A) {} get(): A { return this.value } map<B>(f: (a: A) => B): Identity<B> { return new Identity(f(this.get())) } ap<B>(fab: Identity<(a: A) => B>): Identity<B> { return new Identity(fab.get()(this.get())) } flatMap<B>(f: (a: A) => Identity<B>): Identity<B> { return f(this.value) } }
55669ac7af28e03bb24cfd745310bc39f9e67e9f
TypeScript
marshall0410/Passenger-App
/app/passenger-dashboard/containers/passenger-dashboard/passenger-dashboard.component.ts
2.625
3
import { Component, OnInit } from "@angular/core"; import { Passenger } from "../../models/passenger"; @Component({ selector: "passenger-dashboard", styleUrls: ["passenger-dashboard.component.scss"], template: ` <div> <passenger-count [items]="passengers"> </passenger-count> <h3>Passengers</h3> <passenger-details *ngFor="let passenger of passengers" [details]="passenger" (edit)="editPassenger($event)" (remove)="removePassenger($event)" > </passenger-details> </div> ` }) export class PassengerDashboardComponent implements OnInit { passengers: Passenger[]; editPassenger(event: Passenger) { console.log("edit: " + event); this.passengers = this.passengers.map((passenger: Passenger) => { if (passenger.id === event.id) { passenger = Object.assign({}, passenger, event); } return passenger; }); } removePassenger(event: Passenger) { this.passengers = this.passengers.filter((passenger: Passenger) => { return passenger.id !== event.id; }); } constructor() {} ngOnInit() { console.log("ngOnInit initialized."); this.passengers = [ { id: 1, name: "marshall", age: 27, male: true, checkedInStatus: false, checkedInDate: null, children: [{ name: "Leeroy", age: 5 }] }, { id: 2, name: "winthrop", age: 31, male: true, checkedInStatus: true, checkedInDate: Date.now(), children: null }, { id: 3, name: "dad", age: 64, male: true, checkedInStatus: true, checkedInDate: Date.now(), children: [ { name: "Marshall", age: 27 }, { name: "Faith", age: 32 }, { name: "Winthrop", age: 30 } ] }, { id: 4, name: "mom", age: 67, male: false, checkedInStatus: false, checkedInDate: null, children: [ { name: "Marshall", age: 27 }, { name: "Faith", age: 32 }, { name: "Winthrop", age: 30 } ] } ]; } }
1a483a5fb1fa48b888d233d3f567d779f7d52007
TypeScript
StarException/promise
/typescript/src/Promise.ts
3.171875
3
export class Promise<Value> { constructor(task: (resolve:(value:Value)=>void, reject:(error: Error)=>void)=>void) { try { task(value => { this.doResolve(value); }, error => { this.doReject(error); }); }catch (e) { console.error(e) this.doReject(e) } } public static reject<Value> (err:Error): Promise<Value> { return new Promise<Value>((resolve, reject)=>{ reject(err); }) } public static resolve (): Promise<void>; public static resolve<Value> (value: Value): Promise<Value>; static resolve (...values:any[]): Promise<any>{ return new Promise((resolve, reject)=>{ resolve(values[0]); }) } public then<Next> (task: (value:Value)=>Promise<Next>|Next): Promise<Next> { return new Promise<Next>((resolve, reject)=>{ this.resolves_.push((value)=>{ setTimeout(()=>{ let retValue: Promise<Next>; try { let ret = task(value); if (ret instanceof Promise) { retValue = ret; } else { retValue = Promise.resolve(ret); } }catch (e) { console.error(e); retValue = Promise.reject(e); } retValue.resolves_.push(resolve); retValue.rejects_.push(reject); retValue.nextCall_(); }, 0); }) this.rejects_.push(reject); this.nextCall_(); }) } public catch (task: (err:Error)=>Promise<Value>|Value): Promise<Value> { return new Promise<Value>((resolve, reject)=>{ this.rejects_.push((err)=>{ setTimeout(()=>{ let retValue: Promise<Value>; try { let ret = task(err); if (ret instanceof Promise) { retValue = ret; } else { retValue = Promise.resolve(ret); } }catch (e) { console.error(e); retValue = Promise.reject(e); } retValue.resolves_.push(resolve); retValue.rejects_.push(reject); retValue.nextCall_(); }, 0); }) this.resolves_.push(resolve); this.nextCall_(); }) } public finally(task:()=>void): Promise<Value> { return new Promise<Value>((resolve, reject)=>{ this.resolves_.push(value=>{ setTimeout(()=>{ try { task(); }catch (e) { console.error(e); reject(e); } resolve(value); }, 0); }) this.rejects_.push(err=>{ setTimeout(()=>{ try { task(); }catch (e) { console.error(e); reject(e); } reject(err); }, 0); }) this.nextCall_(); }) } public static race<Value> (promises:Promise<Value>[]): Promise<Value|void> { return new Promise<Value|void>((resolve, reject)=>{ if (promises.length == 0) { resolve(); return } for (const promise of promises) { promise.then(value => { resolve(value); }).catch(err => { reject(err); }) } }); } public static all<T1, T2, T3, T4, T5, T6>( promises: [Promise<T1>, Promise<T2>, Promise<T3>, Promise<T4>, Promise<T5>, Promise<T6>]) : Promise<[T1, T2, T3, T4, T5, T6]>; public static all<T1, T2, T3, T4, T5>( promises: [Promise<T1>, Promise<T2>, Promise<T3>, Promise<T4>, Promise<T5>]): Promise<[T1, T2, T3, T4, T5]>; public static all<T1, T2, T3, T4>( promises: [Promise<T1>, Promise<T2>, Promise<T3>, Promise<T4>]): Promise<[T1, T2, T3, T4]>; public static all<T1, T2, T3>(Promises: [Promise<T1>, Promise<T2>, Promise<T3>]): Promise<[T1, T2, T3]>; public static all<T1, T2>(promises: [Promise<T1>, Promise<T2>]): Promise<[T1, T2]>; public static all<Value>(Promises: Promise<Value>[]):Promise<Value[]>; public static all(promises: Promise<any>[]): Promise<any> { return this._all(promises); } private static _all<Value> (promises: Promise<Value>[]): Promise<Value[]> { return new Promise<Value[]>((resolve, reject)=>{ if (promises.length == 0) { resolve([]); return; } let cnt = promises.length; let ret = new Array<Value>(promises.length); // 要注意执行与返回结果必须要一一对应 for (let i = 0; i < promises.length; ++i) { promises[i].then(value => { ret[i] = value; cnt--; // 全部成功,才算成功 if (cnt == 0) { resolve(ret); } }).catch(err => { // 有任何一个错误,则认为整个错误 reject(err) }) } }) } private doResolve(value: Value):void { if (!this.pending) { return; } this.pending = false; this.nextCall_ = ()=>{ for (let r of this.resolves_) { r(value) } this.resolves_ = [] } this.nextCall_(); } private doReject(err: Error):void { if (!this.pending) { return; } this.pending = false; this.nextCall_ = ()=>{ for (let r of this.rejects_) { r(err) } this.rejects_ = [] } this.nextCall_(); } private resolves_:((v:Value)=>void)[] = [] private rejects_:((e:Error)=>void)[] = [] private nextCall_ = ()=>{}; private pending = true; }
4cc6611450683cd7f9a4769f75adc22f364cffb5
TypeScript
nguyer/aws-sdk-js-v3
/clients/browser/client-medialive-browser/types/_FrameCaptureSettings.ts
2.875
3
/** * Frame Capture Settings */ export interface _FrameCaptureSettings { /** * The frequency, in seconds, for capturing frames for inclusion in the output. For example, "10" means capture a frame every 10 seconds. */ CaptureInterval: number; } export type _UnmarshalledFrameCaptureSettings = _FrameCaptureSettings;
b1e28db6d8ccb8f9a96b249e8f92e80fcb3d21c8
TypeScript
danglotb/skillful_network
/skillful_network_client/src/app/shared/models/application/notification.ts
2.5625
3
import { FollowStateTracker } from '../user/FollowStateTracker'; export class Notification { public id: number; public followerSet: Set<FollowStateTracker> = new Set(); public label: string; public isRead: boolean; public postId: number; constructor(data: any) { this.id = data.id; this.followerSet = data.followerSet; this.label = data.label; this.isRead = data.read; this.postId = data.postId; } public get getId() { return this.id; } public get getFollowerSet() { return this.followerSet; } public set setFollowerSet(followerSet: Set<FollowStateTracker>) { this.followerSet = followerSet; } public get getLabel() { return this.label; } public set setLabel(label: string) { this.label = label; } public get getIsRead() { return this.isRead; } public set setIsRead(isRead: boolean) { this.isRead = isRead; } public get getPostId() { return this.postId; } public set setPostId(postId: number) { this.postId = postId; } }
a4091246c8ac871043f1cfe33913018132e5c35e
TypeScript
parrada/testBank
/src/models/user.model.ts
2.953125
3
export class User { firstname: string lastname: string identification: string birthdate: string constructor(name,lastName,identification,birthdate){ this.firstname = name this.lastname = lastName this.identification = identification this.birthdate = birthdate } }
847364e6ff3fedf2bf2422b59a192ec3c32f9598
TypeScript
Ryshard/lambda
/app/ts/category-list.pipe.ts
2.515625
3
import {Pipe} from 'angular2/core'; @Pipe({ name: 'catList' }) export class CatListPipe{ transform(mediaItems):string{ var categories = []; mediaItems.forEach(mediaItem => { if (categories.indexOf(mediaItem.category) <= -1) { categories.push(mediaItem.category); } }); var cats:string; cats = ''; cats += '<ul>'; categories.forEach(cat =>{ cats += '<li>' + cat + '</li>'; } ); cats += '</ul>'; return cats; // return categories.join(', '); } }
56c4f5dde850c4b743dcbc9cd924d72f3530650b
TypeScript
rhtua/DevCRUD
/app/api/testes/unitarios/DeleteDeveloperService.tests.ts
2.65625
3
import { describe } from "mocha"; import { assert, expect } from "chai"; import { emulatedDatabase } from "../infra/connections"; import { Connection } from "typeorm"; import { DeleteDeveloperService } from "../../src/services/DeleteDeveloperService"; import { Developer } from "../../src/business/entities/Developer"; describe("ExcluirDesenvolvedorServiceTests", () => { let connection: Connection; let service: DeleteDeveloperService; const TOTAL_RESULTS = 20; const NOT_FOUND_ERROR_MESSAGE = "Não foi possivel deletar"; before(async () => { connection = await emulatedDatabase(); service = new DeleteDeveloperService(); }); it("Deve excluir o desenvolvedor desejado", async () => { await service.delete(TOTAL_RESULTS); expect(await connection.getRepository(Developer).count()).to.be.equal( TOTAL_RESULTS - 1 ); }); it("Deve retornar erro especifico caso não exista o desenvolvedor", async () => { let erroTermo = ""; await service .delete(TOTAL_RESULTS + 1) .catch((err) => (erroTermo = err.message)); assert.equal(erroTermo, NOT_FOUND_ERROR_MESSAGE); }); after(() => { connection.close(); }); });
23e0c4b2a3fc7abb59d5a241e9f2068f97893e94
TypeScript
lanxuexing/waresmgr
/src/app/directives/grid-item.directive.ts
2.6875
3
import { Directive, ElementRef, Renderer2, OnInit, HostBinding } from '@angular/core'; @Directive({ selector: '[appGridItem]' }) export class GridItemDirective implements OnInit { // 第一种写法:HostBinding 绑定宿主的属性or样式 可以指定为@Input() @HostBinding('style.display') display = 'grid'; @HostBinding('style.grid-template-areas') gridTemplate = `'image' 'title'`; @HostBinding('style.place-items') placeItem = 'center'; @HostBinding('style.width') width = '4rem'; constructor( private elementRef: ElementRef, private render: Renderer2 ) { } ngOnInit(): void { // 第二种写法:Renderer2 绘制对象 // this.render.setStyle(this.elementRef.nativeElement, 'display', 'grid'); // this.render.setStyle(this.elementRef.nativeElement, 'grid-template-areas', `'image' 'title`); // this.render.setStyle(this.elementRef.nativeElement, 'place-items', 'center'); // this.render.setStyle(this.elementRef.nativeElement, 'width', '4rem'); } }
f8a020dd6ac57118b6b1c0d8d1676cf336d719a4
TypeScript
RandyCHS/game-of-life-ish
/game.ts
2.671875
3
let selectedTemplate = settings.readNumber("selectedTemplate") || 0; let isRunning = false; let isFilling = false; let cursorX = 1; let cursorY = 1; const cursor = sprites.create(img` 9 9 9 9 9 . . 9 9 . . 9 9 9 9 9 `); updateCursor(); bindControllerDirectionToCursorMovement(controller.up, 0, -1); bindControllerDirectionToCursorMovement(controller.down, 0, 1); bindControllerDirectionToCursorMovement(controller.left, -1, 0); bindControllerDirectionToCursorMovement(controller.right, 1, 0); controller.A.onEvent(ControllerButtonEvent.Pressed, toggleCell); controller.B.onEvent(ControllerButtonEvent.Pressed, toggleIsRunning); game.onUpdateInterval(100, function () { if (isRunning) { tickSimulation(); } }); initFromPreset(selectedTemplate); function bindControllerDirectionToCursorMovement(button: controller.Button, xChange: number, yChange: number) { const moveCursor = () => { if (isRunning) { return; } cursorX = Math.clamp(0, columnCount - 1, cursorX + xChange); cursorY = Math.clamp(0, rowCount - 1, cursorY + yChange); updateCursor(); if (controller.A.isPressed()) { fillCell(scene.backgroundImage(), cursorX, cursorY, isFilling ? undefined : 0); } } button.onEvent(ControllerButtonEvent.Pressed, moveCursor); button.onEvent(ControllerButtonEvent.Repeated, moveCursor); } function updateCursor() { cursor.top = cursorY * cellSize; cursor.left = cursorX * cellSize; } function toggleCell() { if (isRunning) { return; } const isCellAlive = !!score(cursorX, cursorY); isFilling = !isCellAlive; fillCell(scene.backgroundImage(), cursorX, cursorY, isFilling ? undefined : 0); } function toggleIsRunning() { setIsRunning(!isRunning); } function setIsRunning(newIsRunning: boolean) { isRunning = newIsRunning; cursor.setFlag(SpriteFlag.Invisible, isRunning); }
ba02f21f8d0b2e319d24ea582f05a11597a0148a
TypeScript
Evanion/calculator
/src/Screens/Calculator/Calculator.interfaces.ts
2.90625
3
import { ACTIONS } from './Calculator.reducer'; export enum Operator { product = 'product', dividend = 'dividend', sum = 'sum', difference = 'difference', } export interface State { operator: Operator; values: number[]; total: number; } export interface AddValueAction { type: ACTIONS.ADD_VALUE; payload?:any; } export interface UpdateValueAction { type: ACTIONS.UPDATE_VALUE; payload: { index: number; value: number; }; } export interface RemoveValueAction { type: ACTIONS.REMOVE_VALUE; payload: { index: number; }; } export interface SetOperator { type: ACTIONS.SET_OPERATOR; payload: { operator: Operator; }; } export type Action = | AddValueAction | UpdateValueAction | RemoveValueAction | SetOperator;
a7291eb094adca77401a157fa8f678529cebf2c7
TypeScript
HendrikCammann/thesis
/src/models/State/StateModel.ts
2.546875
3
import {ActivityClusterTypeCountModel} from '../Activity/ActivityClusterModel'; import {getWeeksBetweenDates} from '../../utils/time/time-formatter'; export enum ClusterTypes { Halfmarathon = 'Halbmarathon', Marathon = 'Marathon', TenK = '10 km' } export class ClusterItem { clusterName: string; id: string; isIndividual: boolean; timeRange: { start: Date, end: Date, }; duration: any; type: ClusterTypes; eventId: number; constructor(name, id, individual, timeRange, type, eventId) { this.clusterName = name; this.id = id; this.isIndividual = individual; this.timeRange = timeRange; this.duration = getWeeksBetweenDates(timeRange.end, timeRange.start); this.type = type; this.eventId = eventId; } } class ClusterStatsModel { distance: number; time: number; count: number; intensity: number; typeCount: ActivityClusterTypeCountModel; constructor() { this.distance = null; this.intensity = null; this.time = null; this.count = null; this.typeCount = new ActivityClusterTypeCountModel(); } } export class ClusterWrapper { stats: ClusterStatsModel; unsorted: any; byYears: any; byMonths: any; byWeeks: any; constructor() { this.stats = new ClusterStatsModel(); this.unsorted = {}; this.byYears = {}; this.byMonths = {}; this.byWeeks = {}; } }
a57f2dcf906aef57adf3612a87960e2d4ef98f88
TypeScript
yaroslav-nikolaiko/LingvoMovieV2
/domain/webapp/src/main/ui/app/src/hal.client/paging.entity.ts
2.71875
3
import {Observable} from "rxjs/Rx"; interface Page{ size: number; totalElements: number; totalPages: number; number: number; } export class PagingEntity<T>{ constructor(public list: T[], public page :Page){} first: ()=>Observable<PagingEntity<T>>; next: ()=>Observable<PagingEntity<T>>; prev: ()=>Observable<PagingEntity<T>>; last: ()=>Observable<PagingEntity<T>>; goToPage: (page: number)=>Observable<PagingEntity<T>>; }
fb0ea2a9ff0e556a185e763eafb7c87705941548
TypeScript
juancpulidos/dance-til-you-drop
/website/src/Scripts/danceCalibration.ts
2.671875
3
import { Pose } from "@tensorflow-models/posenet"; let calibrationNumber = 0; export const getCalibrationNumber = () => calibrationNumber; export const setCalibrationNumber = (calNumber: number) => { calibrationNumber = calNumber; }; const minPartConfidence = 0.1; const minPoseConfidence = 0.15; export declare interface Calibration { upperArmLength: number; foreArmLength: number; upperLegLength: number; lowerLegLength: number; wasitLength: number; shoulderLength: number; torsoLength: number; } const getCalibrationHelper = (pose: Pose): Calibration | null => { //TODO: Add Error Checking if pose does not have all points. let valid = true; const keypoints = pose.keypoints; for (let i = 5; i < 17; i++) { if (keypoints[i].score < minPartConfidence) { valid = false; } } if (valid) { return { upperArmLength: Math.max( Math.sqrt( Math.pow(keypoints[5].position.x - keypoints[7].position.x, 2) + Math.pow(keypoints[5].position.y - keypoints[7].position.y, 2) ), Math.sqrt( Math.pow(keypoints[6].position.x - keypoints[8].position.x, 2) + Math.pow(keypoints[6].position.y - keypoints[8].position.y, 2) ) ), foreArmLength: Math.max( Math.sqrt( Math.pow(keypoints[7].position.x - keypoints[9].position.x, 2) + Math.pow(keypoints[7].position.y - keypoints[9].position.y, 2) ), Math.sqrt( Math.pow(keypoints[8].position.x - keypoints[10].position.x, 2) + Math.pow(keypoints[8].position.y - keypoints[10].position.y, 2) ) ), upperLegLength: Math.max( Math.sqrt( Math.pow(keypoints[11].position.x - keypoints[13].position.x, 2) + Math.pow(keypoints[11].position.y - keypoints[13].position.y, 2) ), Math.sqrt( Math.pow(keypoints[12].position.x - keypoints[14].position.x, 2) + Math.pow(keypoints[12].position.y - keypoints[14].position.y, 2) ) ), lowerLegLength: Math.max( Math.sqrt( Math.pow(keypoints[13].position.x - keypoints[15].position.x, 2) + Math.pow(keypoints[13].position.y - keypoints[15].position.y, 2) ), Math.sqrt( Math.pow(keypoints[14].position.x - keypoints[16].position.x, 2) + Math.pow(keypoints[14].position.y - keypoints[16].position.y, 2) ) ), wasitLength: Math.sqrt( Math.pow(keypoints[11].position.x - keypoints[12].position.x, 2) + Math.pow(keypoints[11].position.y - keypoints[12].position.y, 2) ), shoulderLength: Math.sqrt( Math.pow(keypoints[5].position.x - keypoints[6].position.x, 2) + Math.pow(keypoints[5].position.y - keypoints[6].position.y, 2) ), torsoLength: Math.max( Math.sqrt( Math.pow(keypoints[5].position.x - keypoints[11].position.x, 2) + Math.pow(keypoints[5].position.y - keypoints[11].position.y, 2) ), Math.sqrt( Math.pow(keypoints[6].position.x - keypoints[12].position.x, 2) + Math.pow(keypoints[6].position.y - keypoints[12].position.y, 2) ) ), }; } else { return null; } }; export const getCalibration = (poses: Pose[]): Calibration | null => { for (let i = 0; i < poses.length; i++) { const temp = getCalibrationHelper(poses[i]); if (minPoseConfidence < poses[i].score && temp) { return temp; } } return null; };
5b74fbd9d139c9bd3bb2d1d0860490fe6c1621ce
TypeScript
kevin-west-10x/bioinformatics-algorithms
/problems/chapter-1/BA1L.ts
3.03125
3
import { DNA, patternToIndex } from "../../utilities/lexographic"; import { assertEqual } from "../../utilities/test"; // Convert a pattern into it's lexographical index among all patterns of the same size const BA1L = (pattern: string) => patternToIndex(DNA)(pattern); // Test data assertEqual( "BA1L", BA1L("AGT"), 11 );
ef4cd53efcf75e282647816456ebb92acc74b8bd
TypeScript
seekseep/rescue-helicopter-simulation
/src/ts/simulator/services/ScheduleService.ts
2.59375
3
import { GeneralTask, Mission, Schedule, Task } from '../entities' import * as builders from '../builders' import * as utils from '../utilities' import { DAY, MINUTE } from '../constants' import { ScheduleCache } from '../entities/schedules' import { mission } from '../builders/missions' export default class ScheduleService<TT, T extends Task<TT>, M extends Mission<TT, T>, C extends ScheduleCache<TT, T, M>> { schedule: Schedule<TT, T, M, C> constructor (schedule: Schedule<TT, T, M, C>) { this.schedule = schedule } get missions (): M[] { return this.schedule.missions } get lastMission (): M { return this.schedule.cache.lastMission } get freeTasks (): GeneralTask[] { return this.schedule.cache.freeTasks } get isWorking (): boolean { return this.schedule.cache.activeMissions.size >= this.schedule.parallelMissionsCount } isActive (date: Date): boolean { const { startHours, startMinutes, endHours, endMinutes } = this.schedule const start = startHours * 60 + startMinutes const time = date.getHours() * 60 + date.getMinutes() const end = endHours * 60 + endMinutes return start <= time && time <= end } getActiveMissionsCount (missions:M[], date: Date): number { return missions.reduce((count, {duration, startedAt, finishedAt}) => { return (duration > 0 && startedAt <= date && date < finishedAt) ? count + 1 : count }, 0) } getStartDate (current: Date): Date { const { startHours, startMinutes } = this.schedule return utils.dateFromDateAndHoursAndMinutes(current, startHours, startMinutes) } getFinishDate (current: Date): Date { const { endHours, endMinutes } = this.schedule return utils.dateFromDateAndHoursAndMinutes(current, endHours, endMinutes) } getStartDateOfNextDay (current: Date): Date { const nextDate = utils.addDateAndTime(current, DAY) const { startHours, startMinutes } = this.schedule return utils.dateFromDateAndHoursAndMinutes(nextDate, startHours, startMinutes) } getTasksByFinishedAtTime (finishedAtTime: number): Map<number, T>|null { return this.schedule.cache.finishedAtTimeToTasks.get(finishedAtTime) || null } getMissionsByStartedAtTime (startedAtTime: number): Map<number, M>|null { return this.schedule.cache.startedAtTimeToMissions.get(startedAtTime) || null } getMissionsByFinishedAtTime (finishedAtTime: number): Map<number, M>|null { return this.schedule.cache.finishedAtTimeToMissions.get(finishedAtTime) || null } addMission (mission: M, current: Date): void { if (mission.startedAt < current) { console.warn('invalid mission', mission) debugger; } this.missions.push(mission) this.updateCacheWithNewMission(mission, current) if (utils.equalDate(mission.startedAt, current)) { this.updateCacheWithStartedMission(mission) mission.tasks.forEach(task => { if (utils.equalDate(task.finishedAt, current)) { this.updateCacheWithFinishedTask(task) } }) } if (utils.equalDate(mission.finishedAt, current)) { this.updateCacheWithFinishedMission(mission) } } updateCacheWithFinishedTask (finishedTask: T): void { // do nothing } updateCacheWithStartedMission (startedMission: M): void { this.schedule.cache.activeMissions.set(startedMission.id, startedMission) } updateCacheWithFinishedMission (finishedMission: M): void { this.schedule.cache.activeMissions.delete(finishedMission.id) this.schedule.cache.notFinishedMissions.delete(finishedMission.id) } updateCacheWithNewMission (mission: M, current: Date): void { const { cache } = this.schedule cache.lastMission = mission { const startedAtTime = mission.startedAt.getTime() if (!cache.startedAtTimeToMissions.has(startedAtTime)) { cache.startedAtTimeToMissions.set(startedAtTime, new Map()) } cache.startedAtTimeToMissions.get(startedAtTime).set(mission.id, mission) cache.notPassedMissionPoints.set(startedAtTime, mission.startedAt) const finishedAtTime = mission.finishedAt.getTime() if (!cache.finishedAtTimeToMissions.has(finishedAtTime)) { cache.finishedAtTimeToMissions.set(finishedAtTime, new Map()) } cache.finishedAtTimeToMissions.get(finishedAtTime).set(mission.id, mission) cache.notPassedMissionPoints.set(finishedAtTime, mission.finishedAt) } mission.tasks.forEach(task => { const tasks = cache.taskTypeToTasks.get(task.type) || [] tasks.push(task) cache.taskTypeToTasks.set(task.type, tasks) const finishedAtTime = task.finishedAt.getTime() if (!cache.finishedAtTimeToTasks.has(finishedAtTime)) { cache.finishedAtTimeToTasks.set(finishedAtTime, new Map()) } cache.finishedAtTimeToTasks.get(finishedAtTime).set(task.id, task) }) this.schedule.cache.notFinishedMissions.set(mission.id, mission) cache.freeTasks = this.buildFreeTasks(current) } updateCacheWithCurrent(current: Date) { const prev = current.getTime() - MINUTE if (this.schedule.cache.notPassedMissionPoints.has(prev)) { this.schedule.cache.notPassedMissionPoints.delete(prev) } const currentTime = current.getTime() const finishedTasks = this.getTasksByFinishedAtTime(currentTime) if (finishedTasks) { finishedTasks.forEach(finishedTask => { this.updateCacheWithFinishedTask(finishedTask) }) } const startedMissions = this.getMissionsByStartedAtTime(currentTime) if (startedMissions) { startedMissions.forEach(startedMission => { this.updateCacheWithStartedMission(startedMission) }) } const finishedMissions = this.getMissionsByFinishedAtTime(currentTime) if (finishedMissions) { finishedMissions.forEach(finishedMission => { this.updateCacheWithFinishedMission(finishedMission) }) } } buildFreeTasks (current: Date): GeneralTask[] { const { parallelMissionsCount } = this.schedule const notFinishedMissions = Array.from(this.schedule.cache.notFinishedMissions.values()) const points = [current, ...Array.from(this.schedule.cache.notPassedMissionPoints.values())].sort((a, b) => a > b ? 1 : -1) const freeTasks = points.reduce((tasks: GeneralTask[], current: Date, index: number, points: Date[]): GeneralTask[] => { if(index === 0) return tasks const prev = points[index - 1] if (this.getActiveMissionsCount(notFinishedMissions, prev) >= parallelMissionsCount) { return tasks } const lastTask = tasks.splice(-1, 1)[0] const task = builders.tasks.free(prev, current) if (!lastTask) return [...tasks, task] if (lastTask.finishedAt < task.startedAt) return [...tasks, lastTask, task] const unionedTask = builders.tasks.free(lastTask.startedAt, task.finishedAt) return [...tasks, unionedTask] }, []) return freeTasks } }
1e980841abbf7bbe9867f92a0f37de00f03c0f7c
TypeScript
AlvinSaldanha/Angular4
/AngularApp/src/app/player/player.component.ts
2.515625
3
import {Component, OnInit} from '@angular/core' @Component({ selector: 'app-player', templateUrl: './player.component.html', styleUrls: ['./player.component.css'] }) export class PlayerComponent implements OnInit { title: string = "This is a Player Component!!!!"; imageSrc = "http://imgsv.imaging.nikon.com/lineup/lens/zoom/normalzoom/af-s_dx_18-140mmf_35-56g_ed_vr/img/sample/sample1_l.jpg"; isDisabled: boolean = false; players: any; inputValue:string = "Default Value"; constructor() { console.log('Constructor Called'); } onButtonClick() { alert('Button clicked!'); } ngOnInit() { console.log('Component Initialised'); this.players = [ { name: 'sachin', age: 44 }, { name: 'dravid', age: 42 }, { name: 'virat', age: 27 } ] } }
5c2f9df0029c52469532597806fce81bfdab9cc4
TypeScript
nutgaard/maybe-ts
/test/maybe-ts.classical.test.ts
3.34375
3
import { MaybeCls as Maybe } from '../src/maybe-ts'; describe('Maybe', () => { describe('class', () => { describe('of', () => { it('should create Just(3)', () => { expect(Maybe.just(3).withDefault(0)).toBe(3); expect(Maybe.of(3).withDefault(0)).toBe(3); }); it('should create Nothing from null', () => { expect(Maybe.just(null).withDefault(0)).toBe(0); expect(Maybe.of(null).withDefault(0)).toBe(0); }); it('should create Nothing from undefind', () => { expect(Maybe.just(undefined).withDefault(0)).toBe(0); expect(Maybe.of(undefined).withDefault(0)).toBe(0); }); }); describe('withDefault', () => { it('should return value', () => { const maybeNumber = Maybe.just(3); expect(maybeNumber.withDefault(0)).toBe(3); expect(maybeNumber.getOrElse(0)).toBe(3); }); it('should return defaultValue', () => { const nothing = Maybe.nothing(); expect(nothing.withDefault(3)).toBe(3); expect(nothing.getOrElse(3)).toBe(3); }); it('should return defaultValue even if null', () => { const nothing = Maybe.nothing(); expect(nothing.withDefault(null)).toBe(null); expect(nothing.getOrElse(null)).toBe(null); }); }); describe('withDefaultLazy', () => { it('should return value', () => { const defaultValue = jest.fn().mockReturnValue(0); const maybeNumber = Maybe.just(3); expect(maybeNumber.withDefaultLazy(defaultValue)).toBe(3); expect(maybeNumber.getOrElseGet(defaultValue)).toBe(3); expect(defaultValue).toHaveBeenCalledTimes(0); }); it('should return defaultValue', () => { const defaultValue = jest.fn().mockReturnValue(3); const nothing = Maybe.nothing(); expect(nothing.withDefaultLazy(defaultValue)).toBe(3); expect(nothing.getOrElseGet(defaultValue)).toBe(3); expect(defaultValue).toHaveBeenCalledTimes(2); }); it('should return defaultValue even if null', () => { const defaultValue = jest.fn().mockReturnValue(null); const nothing = Maybe.nothing(); expect(nothing.withDefaultLazy(defaultValue)).toBe(null); expect(nothing.getOrElseGet(defaultValue)).toBe(null); expect(defaultValue).toHaveBeenCalledTimes(2); }); }); describe('map', () => { it('should ignore Nothing value', () => { expect(Maybe.nothing().map(() => 3)).toEqual(Maybe.nothing()); }); it('should map using function value', () => { expect(Maybe.just('').map(() => 3)).toEqual(Maybe.just(3)); }); it('should convert to Nothing if function return null', () => { expect(Maybe.just('').map(() => null)).toEqual(Maybe.nothing()); }); }); describe('map2', () => { const nullNumber = Maybe.just((null as unknown) as number); const add = (a: number, b: number) => a + b; it('should ignore if both value is Nothing', () => { expect(nullNumber.map2(add, Maybe.nothing())).toEqual(Maybe.nothing()); }); it('should ignore if first value is Nothing', () => { expect(Maybe.just(4).map2(add, Maybe.nothing())).toEqual(Maybe.nothing()); }); it('should ignore if second value is Nothing', () => { expect(nullNumber.map2(add, Maybe.just(3))).toEqual(Maybe.nothing()); }); it('should map user function if both are Just', () => { expect(Maybe.just(4).map2(add, Maybe.just(3))).toEqual(Maybe.just(7)); }); it('should convert to Nothing if function return null', () => { expect(Maybe.just(4).map2(() => null, Maybe.just(3))).toEqual(Maybe.nothing()); }); }); describe('map2', () => { const nullNumber = Maybe.just((null as unknown) as number); const add = (a: number, b: number, c: number) => a + b + c; it('should ignore if both value is Nothing', () => { expect(nullNumber.map3(add, Maybe.nothing(), Maybe.nothing())).toEqual(Maybe.nothing()); }); it('should ignore if first value is Nothing', () => { expect(nullNumber.map3(add, Maybe.just(3), Maybe.just(5))).toEqual(Maybe.nothing()); }); it('should ignore if second value is Nothing', () => { expect(Maybe.just(4).map3(add, Maybe.nothing(), Maybe.just(5))).toEqual(Maybe.nothing()); }); it('should ignore if third value is Nothing', () => { expect(Maybe.just(4).map3(add, Maybe.just(5), Maybe.nothing())).toEqual(Maybe.nothing()); }); it('should map user function if both are Just', () => { expect(Maybe.just(4).map3(add, Maybe.just(3), Maybe.just(5))).toEqual(Maybe.just(12)); }); it('should convert to Nothing if function return null', () => { expect(Maybe.just(4).map3(() => null, Maybe.just(3), Maybe.just(5))).toEqual( Maybe.nothing() ); }); }); describe('filter', () => { it('should propagate Nothing', () => { expect(Maybe.nothing().filter(() => true)).toEqual(Maybe.nothing()); }); it('should convert to Nothing if predicate fails', () => { expect(Maybe.just(3).filter(() => false)).toEqual(Maybe.nothing()); }); it('should keep Mayeb if predicate is ok', () => { const maybe = Maybe.just(3); expect(maybe.filter(() => true)).toEqual(maybe); }); }); describe('join', () => { it('should return Just if both is Just', () => { expect(Maybe.join(Maybe.just(Maybe.just(3)))).toEqual(Maybe.just(3)); }); it('should return Nothing if outer is Nothing', () => { expect(Maybe.join(Maybe.nothing())).toEqual(Maybe.nothing()); }); it('should return Nothing if inner is Nothing', () => { expect(Maybe.join(Maybe.just(Maybe.nothing()))).toEqual(Maybe.nothing()); }); }); describe('andThen', () => { it('should propagate Nothing', () => { expect(Maybe.just(null).andThen(() => Maybe.just(3))).toEqual(Maybe.nothing()); expect(Maybe.just(null).flatMap(() => Maybe.just(3))).toEqual(Maybe.nothing()); }); it('should flatten nested Maybe', () => { expect(Maybe.just(0).andThen(() => Maybe.just(3))).toEqual(Maybe.just(3)); expect(Maybe.just(0).flatMap(() => Maybe.just(3))).toEqual(Maybe.just(3)); }); it('should convert to Nothing if null is returned', () => { expect(Maybe.just(0).andThen(() => null as any)).toEqual(Maybe.nothing()); expect(Maybe.just(0).flatMap(() => null as any)).toEqual(Maybe.nothing()); }); }); describe('or', () => { it('should keep first if Just', () => { expect(Maybe.just(3).or(Maybe.just(4))).toEqual(Maybe.just(3)); expect(Maybe.just(3).or(Maybe.nothing())).toEqual(Maybe.just(3)); }); it('should keep second if Just', () => { expect(Maybe.nothing().or(Maybe.just(4))).toEqual(Maybe.just(4)); }); it('should return Nothing if both are Nothing', () => { expect(Maybe.nothing().or(Maybe.nothing())).toEqual(Maybe.nothing()); }); }); describe('toArray', () => { it('should return empty array if Nothing', () => { expect(Maybe.nothing().toArray()).toEqual([]); }); it('should return array with value if Just', () => { expect(Maybe.just(3).toArray()).toEqual([3]); }); }); describe('isJust', () => { expect(Maybe.just(3).isJust()).toBe(true); expect(Maybe.just(null).isJust()).toBe(false); expect(Maybe.nothing().isJust()).toBe(false); }); it('isNothing', () => { expect(Maybe.just(3).isNothing()).toBe(false); expect(Maybe.just(null).isNothing()).toBe(true); expect(Maybe.nothing().isNothing()).toBe(true); }); }); });
203cc708912fa90eba0bf35e4d4d414f04c454b2
TypeScript
jramstedt/collisions
/src/lib/Circle.ts
3.453125
3
import {Body} from './Body'; /** * A circle used to detect collisions */ export class Circle extends Body { radius: number; scale: number; override readonly _circle = true; /** * x: The starting X coordinate * y: The starting Y coordinate * radius * scale * padding: The amount to pad the bounding volume when testing for potential collisions */ constructor(x = 0, y = 0, radius = 0, scale = 1, padding = 0) { super(x, y, padding); this.radius = radius; this.scale = scale; } /** * Draws the circle to a CanvasRenderingContext2D's current path * context: The context to add the arc to */ draw(context: CanvasRenderingContext2D): void { const x = this.x; const y = this.y; const radius = this.radius * this.scale; context.moveTo(x + radius, y); context.arc(x, y, radius, 0, Math.PI * 2); } }
f410d66635bc9055fc2aa8a3de8071cf61edee3f
TypeScript
Oda2/graphql-api-estudo
/src/models/UserModel.ts
2.796875
3
import * as Sequelize from 'sequelize'; import { genSaltSync, hashSync, compareSync } from 'bcryptjs'; import { BaseModelInterface } from '../interfaces/BaseModelInterface'; export interface UserAttributes { id?: number; name?: string; email?: string; password?: string; photo?: string; createdAt?: string; updatedAt?: string; } export interface UserInstance extends Sequelize.Instance<UserAttributes>, UserAttributes { isPassword(encodedPassword: string, password: string): boolean; } export interface UserModel extends BaseModelInterface, Sequelize.Model<UserInstance, UserAttributes> { } export default (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes): UserModel => { const User: UserModel = sequelize.define('User', { id: { type: DataTypes.INTEGER, primaryKey: true, allowNull: false, autoIncrement: true }, name: { type: DataTypes.STRING(128), allowNull: false }, email: { type: DataTypes.STRING, allowNull: true, unique: true }, password: { type: DataTypes.STRING, allowNull: false, validate: { notEmpty: true } }, photo: { type: DataTypes.BLOB({ length: 'long' }), allowNull: true, defaultValue: null } }, { tableName: 'users', hooks: { beforeCreate: (user: UserInstance, options: Sequelize.CreateOptions): void => { const salt = genSaltSync(); user.password = hashSync(user.password, salt); }, beforeUpdate: (user: UserInstance, options: Sequelize.CreateOptions): void => { if (user.changed('password')) { const salt = genSaltSync(); user.password = hashSync(user.password, salt); } } } }); //User.associate = (models: ModelsHashInterface) => {}; User.prototype.isPassword = (encodedPassword: string, password: string): boolean => { return compareSync(password, encodedPassword); }; return User; };
4214d0c2c3034d8c155a347b960ea89b88221405
TypeScript
g4rcez/dont-need-for-speed
/src/services/settings.ts
2.546875
3
import { SessionStorage } from "storage-manager-js"; import { COLORS } from "components/car"; const storage = new SessionStorage(); enum StorageKeys { CAR_COLOR = "carColor", RACE_TIME = "raceTime" } export const getCarColor = (): COLORS => storage.get(StorageKeys.CAR_COLOR) ?? "original"; export const setCarColor = (color: COLORS) => { storage.set(StorageKeys.CAR_COLOR, color); return; };
af0c2a10c42731a5ebcc6dba8aca6f872f047a63
TypeScript
horacehylee/workenv-cli
/src/modules/workenv/__tests__/dao/program.dao.spec.ts
2.9375
3
import { connect, resetDb } from "../../../../db"; import { addProgram, deletePrograms, getAllPrograms, getProgramsByName } from "../../daos/program.dao"; import { Program } from "../../models/program.model"; export const addTestPrograms = () => Promise.all([ addProgram( "telegram", "C:\\Users\\xxx\\AppData\\Roaming\\Telegram Desktop\\telegram.exe" ), addProgram("trello", "C:\\Program Files\\WindowsApps\\xxx\\app\\Trello.exe") ]); describe("Program Dao", () => { beforeAll(async () => { await connect({ testing: true }); }); beforeEach(async () => { await resetDb(); await addTestPrograms(); }); describe("Add Program", () => { it("should be able to add program", async () => { await addProgram("test", "C:\\test\\test.exe"); const programs = await getAllPrograms(); expect(programs.length).toEqual(3); }); it("should throw error if name already exists", async () => { await expect( addProgram("telegram", "C:\\test\\telegram.exe") ).rejects.toEqual(new Error("Program(telegram) already exists")); }); it("should be rejected for invalid program path", async () => { await expect(addProgram("test", "C:\\test\\test")).rejects.toEqual( new Error("programPath is invalid") ); }); }); describe("Get All Programs", () => { it("should return a list of programs", async () => { const programs = await getAllPrograms(); expect(programs.length).toEqual(2); expect(programs[0].location).toEqual( "C:\\Users\\xxx\\AppData\\Roaming\\Telegram Desktop" ); expect(programs[1].location).toEqual( "C:\\Program Files\\WindowsApps\\xxx\\app" ); }); }); describe("Get Programs By Name", () => { it("should return all named programs", async () => { const [program] = await getProgramsByName(["telegram"]); expect(program).not.toBeNull(); expect(program.executable).toEqual("telegram.exe"); expect(program.location).toEqual( "C:\\Users\\xxx\\AppData\\Roaming\\Telegram Desktop" ); expect(program.name).toEqual("telegram"); }); it("should throw error if named program does not exists", async () => { await expect( getProgramsByName(["telegram", "unknownProgram"]) ).rejects.toEqual(new Error("Programs(unknownProgram) do not exist")); }); }); describe("Delete program", () => { it("should delete all programs", async () => { const programs = await getAllPrograms(); await deletePrograms(...programs); const programsAfter = await getAllPrograms(); expect(programsAfter).toEqual([]); }); }); });
b37da66ca4c5c79b01c5dcebe7d13cbb3930e1f2
TypeScript
yoxjs/yox-template-compiler
/test/event.test.ts
2.75
3
import { compile } from 'yox-template-compiler/src/compiler' import * as nodeType from 'yox-template-compiler/src/nodeType' import Node from 'yox-template-compiler/src/node/Node' import Element from 'yox-template-compiler/src/node/Element' import Directive from 'yox-template-compiler/src/node/Directive' test('event', () => { // 事件名转成驼峰 let ast = compile('<Component on-get-out="click"></Component>') expect(ast.length).toBe(1) let root = ast[0] as Element expect(root.type).toBe(nodeType.ELEMENT) expect((root as Element).tag).toBe('Component') expect((root as Element).isComponent).toBe(true) let attrs = root.attrs as Node[] expect(attrs.length).toBe(1) expect(attrs[0].type).toBe(nodeType.DIRECTIVE) expect((attrs[0] as Directive).name).toBe('getOut') expect((attrs[0] as Directive).modifier).toBe(undefined) // 命名空间 ast = compile('<Button on-submit.button="click"/>') root = ast[0] as Element expect(root.type).toBe(nodeType.ELEMENT) expect((root as Element).tag).toBe('Button') expect((root as Element).isComponent).toBe(true) attrs = root.attrs as Node[] expect(attrs.length).toBe(1) expect(attrs[0].type).toBe(nodeType.DIRECTIVE) expect((attrs[0] as Directive).name).toBe('submit') expect((attrs[0] as Directive).modifier).toBe('button') // 转驼峰 ast = compile('<Button on-submit-test.button-test="click"></Button>') root = ast[0] as Element expect(root.type).toBe(nodeType.ELEMENT) expect((root as Element).tag).toBe('Button') expect((root as Element).isComponent).toBe(true) attrs = root.attrs as Node[] expect(attrs.length).toBe(1) expect(attrs[0].type).toBe(nodeType.DIRECTIVE) expect((attrs[0] as Directive).name).toBe('submitTest') expect((attrs[0] as Directive).modifier).toBe('buttonTest') }) test('error', () => { let hasError = false try { compile('<div on-=></div>') } catch (e) { hasError = true } expect(hasError).toBe(true) hasError = false // 只能调用 methods 定义的方法 try { compile('<div on-click="a.b()"></div>') } catch (e) { hasError = true } expect(hasError).toBe(true) hasError = false // 事件名只能用标识符和命名空间的标识符 try { compile('<div on-tap="123"></div>') } catch (e) { hasError = true } expect(hasError).toBe(true) hasError = false // 事件名只能用标识符和命名空间的标识符 try { compile('<div on-tap="[]"></div>') } catch (e) { hasError = true } expect(hasError).toBe(true) hasError = false // 只能是 name.namespace try { compile('<div on-tap="a.b.c"></div>') } catch (e) { hasError = true } expect(hasError).toBe(true) hasError = false // 事件名只能用标识符和命名空间的标识符 try { compile('<div on-tap="list.0"></div>') } catch (e) { hasError = true } expect(hasError).toBe(true) hasError = false // 可以是一个字母 try { compile('<div on-click="x"></div>') } catch (e) { hasError = true } expect(hasError).toBe(false) hasError = false // 可以是单词 try { compile('<div on-click="submit"></div>') } catch (e) { hasError = true } expect(hasError).toBe(false) hasError = false // 可以是一个字母 try { compile('<div on-click="x.y"></div>') } catch (e) { hasError = true } expect(hasError).toBe(false) hasError = false // 可以是单词 try { compile('<div on-click="name.namespace"></div>') } catch (e) { hasError = true } expect(hasError).toBe(false) hasError = false // dom 可以转换相同的事件 try { compile('<div on-click="click"></div>') } catch (e) { hasError = true } expect(hasError).toBe(false) hasError = false // 组件不能转换相同的事件 try { compile('<Component on-click="click"></Component>') } catch (e) { hasError = true } expect(hasError).toBe(true) hasError = false // 转换后的名称不是连字符 try { compile('<Component on-click="test-case"></Component>') } catch (e) { hasError = true } expect(hasError).toBe(true) hasError = false // 命名空间只能有一个 . try { compile('<Component on-a.b.c="xx"></Component>') } catch (e) { hasError = true } expect(hasError).toBe(true) })
46b398dcdc6b739dad5ee89fbc4c80d90d6ba246
TypeScript
MetaNews/meta-news-ng-app
/src/app/articles-list/articles.service.ts
2.546875
3
import { Injectable, OnInit} from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Filter } from '../models/filter.model'; import { Article } from '../models/article.model'; import { Vote } from '../models/vote.model'; import { Authentication} from '../authentication/authentication'; @Injectable() export class ArticlesService implements OnInit { private articles: Article[] = []; private articlesRoute: string = 'https://gi4ftaly2c.execute-api.us-east-1.amazonaws.com/dev/articles'; constructor(private http: HttpClient) { } ngOnInit() { } /** * * @param {number} page * @param {number} size * @param {Filter} filter * @returns {Promise<Article[]>} */ fetchArticles(page: number, size: number, filter: Filter): Promise<Article[]> { let articles: Article[] = []; const getUrl: string = this.articlesRoute; return this.http.get(getUrl, { }).toPromise().then((data) => { articles = data['Items']; return this.setArticles(articles); }, (error) => { console.log('Failure', error); return error; }).catch(() => { console.log('Something Went Wrong in FetchArticles') }); } /** * Maps the articlesObj array of generic Objects to * an array of Article instances. * * @param {Object[]} articlesObj */ private setArticles(articlesObj: Object[]): Article[] { articlesObj.forEach((articleObj) => { this.articles.push(new Article( articleObj['author'], // Author articleObj['article_id'], // ID articleObj['website'], // Publisher articleObj['title'], // Title articleObj['url'], // URL // Vote )); }); return this.articles; } /** * // TODO getArticles Documentation * * @returns {Article[]} */ getArticles() { return this.articles.slice(); } /** * * @param {number} id * @param {Vote} vote */ sendVote(articleID: string, vote: Vote) { if (Authentication.getUserSession()) { console.log('TODO - Lambda Vote Function'); } else { console.log('Cannot Vote, No One Signed In.'); } } }
e9c66117f5f938cfb311d89ccb5cb255ba909102
TypeScript
darthtrevino/sigma.js
/src/core/domain/renderers/webgl/nodesFast.ts
2.796875
3
import floatColor from "../../utils/misc/floatColor"; import loadShader from "../../utils/webgl/loadShader"; import loadProgram from "../../utils/webgl/loadProgram"; import { Node, WebGLNodeDrawer } from "../../../interfaces"; import { Settings } from "../../classes/Configurable"; import { shaders } from "./utils"; // @ts-ignore import vertexShaderSource from "./shaders/nodesFast.vs"; // @ts-ignore import fragmentShaderSource from "./shaders/nodesFast.fs"; /** * This node renderer will display nodes in the fastest way: Nodes are basic * squares, drawn through the gl.POINTS drawing method. The size of the nodes * are represented with the "gl_PointSize" value in the vertex shader. * * It is the fastest node renderer here since the buffer just takes one line * to draw each node (with attributes "x", "y", "size" and "color"). * * Nevertheless, this method has some problems, especially due to some issues * with the gl.POINTS: * - First, if the center of a node is outside the scene, the point will not * be drawn, even if it should be partly on screen. * - I tried applying a fragment shader similar to the one in the default * node renderer to display them as discs, but it did not work fine on * some computers settings, filling the discs with weird gradients not * depending on the actual color. */ export default { POINTS: 1, ATTRIBUTES: 4, addNode( node: Node, data: Float32Array, i: number, prefix: string, settings: Settings ) { const color = floatColor(node.color || settings("defaultNodeColor")); data[i++] = node[`${prefix}x`]; data[i++] = node[`${prefix}y`]; data[i++] = node[`${prefix}size`]; data[i++] = color; }, render(gl: WebGLRenderingContext, program: WebGLProgram, data, params) { // Define attributes: const positionLocation = gl.getAttribLocation(program, "a_position"); const sizeLocation = gl.getAttribLocation(program, "a_size"); const colorLocation = gl.getAttribLocation(program, "a_color"); const resolutionLocation = gl.getUniformLocation(program, "u_resolution"); const matrixLocation = gl.getUniformLocation(program, "u_matrix"); const ratioLocation = gl.getUniformLocation(program, "u_ratio"); const scaleLocation = gl.getUniformLocation(program, "u_scale"); const buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, data, gl.DYNAMIC_DRAW); gl.uniform2f(resolutionLocation, params.width, params.height); gl.uniform1f( ratioLocation, 1 / params.ratio ** params.settings("nodesPowRatio") ); gl.uniform1f(scaleLocation, params.scalingRatio); gl.uniformMatrix3fv(matrixLocation, false, params.matrix); gl.enableVertexAttribArray(positionLocation); gl.enableVertexAttribArray(sizeLocation); gl.enableVertexAttribArray(colorLocation); gl.vertexAttribPointer( positionLocation, 2, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 0 ); gl.vertexAttribPointer( sizeLocation, 1, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 8 ); gl.vertexAttribPointer( colorLocation, 4, gl.UNSIGNED_BYTE, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 12 ); gl.drawArrays( gl.POINTS, params.start || 0, params.count || data.length / this.ATTRIBUTES ); }, initProgram(gl: WebGLRenderingContext) { const vertexShader = loadShader(gl, vertexShaderSource, gl.VERTEX_SHADER); const fragmentShader = loadShader( gl, fragmentShaderSource, gl.FRAGMENT_SHADER ); const program = loadProgram(gl, shaders(vertexShader, fragmentShader)); return program; } } as WebGLNodeDrawer;
53ad0d395ac10ff27187245913343662ea200368
TypeScript
ihigani/frontegg-react
/packages/rest-api/src/fetch.ts
2.53125
3
import { ContextHolder } from './ContextHolder'; import { ContextOptions, KeyValuePair } from './interfaces'; interface RequestOptions { url: string; method: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'; body?: any; params?: any; contentType?: string; responseType?: 'json' | 'plain' | 'blob'; headers?: Record<string, string>; credentials?: RequestCredentials; } async function getBaseUrl(context: ContextOptions): Promise<string> { let baseUrl = context.baseUrl; const prefix = context.urlPrefix || 'frontegg'; if (!baseUrl.endsWith('/')) { baseUrl += '/'; } if (!baseUrl.endsWith(prefix)) { baseUrl += prefix; } return baseUrl; } async function prepareUrl(context: ContextOptions, url: string, params?: any): Promise<string> { const baseUrl = await getBaseUrl(context); const paramsToSend = await buildQueryParams(context, params); let finalUrl = url.startsWith('http') ? url : `${baseUrl}${url}`; const hasKeys = Object.keys(paramsToSend).length > 0; if (paramsToSend && hasKeys) { const urlParams = new URLSearchParams(paramsToSend); finalUrl += `?${urlParams}`; } return finalUrl; } async function buildRequestHeaders( context: ContextOptions, contentType: string | undefined ): Promise<Record<string, string>> { const authToken = await (context?.tokenResolver ?? ContextHolder.getAccessToken)(); const headers: Record<string, string> = {}; if (authToken) { headers.Authorization = `Bearer ${authToken}`; } if (contentType) { headers['Content-Type'] = contentType; } for (const additionalHeader of await getAdditionalHeaders(context)) { headers[`${additionalHeader.key}`] = `${additionalHeader.value}`; } headers['x-frontegg-source'] = 'frontegg-react'; return headers; } async function buildQueryParams(context: ContextOptions, params?: any) { if (!params) { params = {}; } const additionalQueryParams = await getAdditionalQueryParams(context); for (const queryParam of additionalQueryParams) { params[queryParam.key] = queryParam.value; } const keys = Object.keys(params); for (const key of keys) { const value = params[key]; params[key] = typeof value === 'object' ? JSON.stringify(value) : value; } return params; } async function getAdditionalQueryParams(context: ContextOptions): Promise<KeyValuePair[]> { let output: KeyValuePair[] = []; if (context.additionalQueryParamsResolver) { output = await context.additionalQueryParamsResolver(); } return output; } async function getAdditionalHeaders(context: ContextOptions): Promise<KeyValuePair[]> { let output: KeyValuePair[] = []; if (context.additionalHeadersResolver) { output = await context.additionalHeadersResolver(); } return output; } const sendRequest = async (opts: RequestOptions) => { const context = ContextHolder.getContext(); const headers = await buildRequestHeaders(context, opts.contentType); const url = await prepareUrl(context, opts.url, opts.params); const response = await fetch(url, { body: opts.body ? (opts.contentType === 'application/json' ? JSON.stringify(opts.body) : opts.body) : null, method: opts.method ?? 'GET', headers: { ...headers, ...opts.headers, }, credentials: opts.credentials ?? context.requestCredentials ?? 'same-origin', }); if (!response.ok) { if (response.status === 413) { throw new Error('Error request is too large'); } let errorMessage; try { errorMessage = await response.text(); errorMessage = JSON.parse(errorMessage); } catch (e) {} if (errorMessage.errors) { errorMessage = errorMessage.errors.join(', '); } else if (typeof errorMessage !== 'string') { errorMessage = `Error ${response.status} - ${response.statusText}`; } throw new Error(errorMessage); } if (!opts.responseType || opts.responseType === 'json') { try { return await response.json(); } catch (e) { return {}; } } else if (opts.responseType === 'blob') { const { outputFileName } = opts.params; return await response .blob() .then((blob) => URL.createObjectURL(blob)) .then((url) => { let tempLink = document.createElement('a'); tempLink.href = url; tempLink.setAttribute('download', outputFileName || 'output'); tempLink.click(); }); } else { return await response.text(); } }; export const Get = async (url: string, params?: any, opts?: Omit<RequestOptions, 'method' | 'url'>) => sendRequest({ url, method: 'GET', contentType: 'application/json', params, ...opts, }); export const Post = async (url: string, body?: any, opts?: Omit<RequestOptions, 'method' | 'url'>) => sendRequest({ url, method: 'POST', contentType: 'application/json', body, ...opts, }); export const Patch = async (url: string, body?: any, opts?: Omit<RequestOptions, 'method' | 'url'>) => sendRequest({ url, method: 'PATCH', contentType: 'application/json', body, ...opts, }); export const Put = async (url: string, body?: any, opts?: Omit<RequestOptions, 'method' | 'url'>) => sendRequest({ url, method: 'PUT', contentType: 'application/json', body, ...opts, }); export const Delete = async (url: string, body?: any, opts?: Omit<RequestOptions, 'method' | 'url'>) => sendRequest({ url, method: 'DELETE', contentType: 'application/json', body, ...opts, }); export const PostDownload = async (url: string, body?: any, params?: any, opts?: any) => sendRequest({ url, method: 'POST', contentType: 'application/json', responseType: 'blob', body, params, ...opts, });
59ca139ec3648e011916451f7e3b59ad01464579
TypeScript
USTCLX/DSA
/src/leetcode/567-字符串的排列/index.ts
3.9375
4
import { permutation } from "../offer38-字符串的全排列"; /** * 暴力 * 列举s1的全排列,然后依次验证其是否是s2的子串 * @param s1 * @param s2 */ export const checkInclusion = function(s1: string, s2: string): boolean { if (s2.length < s1.length) return false; const allS1 = permutation(s1); let result = false; for (let str of allS1) { if (s2.includes(str)) { result = true; break; } } return result; }; /** * 解法2,统计s1中字母的个数。可以用哈希表,但是由于小写字母种类有限,因此可以使用数组来表示 * 使用滑动区间遍历s2,统计s2 中的字母个数。然后不断的和s1的字母个数比较。 * @param s1 * @param s2 */ const compare = function(a1: Array<number>, a2: Array<number>): boolean { if (a1.length !== a2.length) return false; return a1.join("") === a2.join(""); }; export const checkInclusion2 = function(s1: string, s2: string): boolean { if (s2.length < s1.length) return false; // init codes which save s1 const s1Code = Array(26).fill(0); const s2Code = Array(26).fill(0); const baseCode = "a".charCodeAt(0); for (let i = 0; i < s1.length; i++) { s1Code[s1.charCodeAt(i) - baseCode]++; s2Code[s2.charCodeAt(i) - baseCode]++; } // compare for (let i = 0; i + s1.length <= s2.length; i++) { if (compare(s1Code, s2Code)) { return true; } // update s2Code s2Code[s2.charCodeAt(i) - baseCode]--; s2Code[s2.charCodeAt(i + s1.length) - baseCode]++; } return false; };
a5ed249ed4a3d013fb019dd46876f8a582c5e5d7
TypeScript
JoseRubioC/D10
/ejemplo.ts
3.359375
3
export class Person{ name : string; private age : number; yearOfBirth: number; address : string; constructor(newName:string, yearOfBirth:number, newAddress:string, currentYear:number){ this.name = newName; this.yearOfBirth = yearOfBirth; this.address = newAddress; this.age = currentYear - yearOfBirth; } printName (){ console.log(this.name); } getAge():number{ return this.age; } }
43353107c5f860fd30abc39111128b8aed26b78c
TypeScript
RicardoGorki/bm-teste-01
/backend/src/modules/shareholders/repositories/implementations/ShareholdersRepository.ts
2.75
3
import { getRepository, Repository } from "typeorm"; import { Shareholder } from "../../entities/Shareholder"; import { ICreateShareholderDTO, IShareholdersRepository, } from "../IShareholdersRepository"; class ShareholdersRepository implements IShareholdersRepository { private repository: Repository<Shareholder>; constructor() { this.repository = getRepository(Shareholder); } async create({ name, email, cpf, birthdate, salary, }: ICreateShareholderDTO): Promise<void> { const shareholder = this.repository.create({ name, email, cpf, birthdate, salary, }); await this.repository.save(shareholder); } async findByName(cpf: string): Promise<Shareholder> { const shareholder = await this.repository.findOne({ cpf }); return shareholder; } async findById(id: string): Promise<Shareholder> { const shareholder = await this.repository.findOne({ id }); return shareholder; } async list(): Promise<Shareholder[]> { const shareholders = await this.repository.find(); return shareholders; } async update( id, { name, email, birthdate, salary }: ICreateShareholderDTO ): Promise<Shareholder|void> { await this.repository.findOne(id); const shareholder = await this.repository.update(id, { name, email, birthdate, salary, updated_at: new Date() }); await this.repository.save({id ,shareholder}) } async delete(id): Promise<void> { await this.repository.findOne(id) await this.repository.delete(id) } } export { ShareholdersRepository };
0855707889575a25d8c931d8ebb41f63e2ede7d7
TypeScript
alexhg128/SimpleAssembly
/src/app/models/codeloader.ts
2.609375
3
export default class CodeLoader { static instance: CodeLoader; private constructor() { } static get Instance(): CodeLoader { if(!this.instance) { this.instance = new CodeLoader(); } return this.instance; } code:string; write(code:string) { this.code = code; } read() : string { return this.code; } }
ddd3da94286ee2ffc6a3fff33b9c94bac645ce35
TypeScript
jasonjmcghee/web-blocks
/worker/Player.ts
2.640625
3
"use strict"; /// <reference path="../typings/tsd.d.ts" /> import THREE = require('three'); import World from './World'; import com from '../common/WorldInfo'; import { Movement } from '../common/Types'; export default class Player { gravity = 0.002; changeListener: ((position: THREE.Vector3, target: THREE.Vector3) => void); print: ((msg: string) => void); rightClicked: boolean = false; mousePosition: { pos: com.IntVector3, side: number }; boundScripts: { number: Function } | {} = {}; private world: World; private position: THREE.Vector3; private velocity: THREE.Vector3; private lastMovement: Movement; private lon = 180; private lat = 20; private xDelta = 0; private zDelta = 0; private lastFrame = Date.now(); rightClick: Function = () => console.log("Right clicked!"); constructor(world: World) { this.world = world; this.position = new THREE.Vector3(100, 24, 120); this.velocity = new THREE.Vector3(0, 0, 0); this.lastMovement = { move: new THREE.Vector3(0, 0, 0), turn: new THREE.Vector2(0, 0) }; } move(movement: Movement) { this.lastMovement = movement; } jump() { if (this.gravity !== 0) this.velocity.y = 0.1; } tick() { if (this.gravity !== 0) { this.walk(); } else { this.fly(); } } fly() { const now = Date.now(); const correction = (now - this.lastFrame) / (1000 / 60); this.lastFrame = now; this.zDelta += this.lastMovement.move.z * 0.01; // Creep speed up as user presses W if (this.lastMovement.move.z === 0) this.zDelta = 0; // Full stop this.lon -= this.lastMovement.turn.x * correction * 2; this.lat -= this.lastMovement.turn.y * correction * 2; this.lat = Math.max(-89.9, Math.min(89.9, this.lat)); const phi = (90 - this.lat) * Math.PI / 180; const theta = (this.lon * Math.PI / 180); this.position.x += correction * ((this.zDelta * 0.5) * Math.cos(theta) + (this.lastMovement.move.x * 0.5) * Math.sin(theta)); this.position.z += correction * ((this.zDelta * 0.5) * Math.sin(theta) - (this.lastMovement.move.x * 0.5) * Math.cos(theta)); this.position.y += correction * ((this.zDelta * 0.5) * Math.cos(phi)); const targetX = 2.0 * Math.sin(phi) * Math.cos(theta) + this.position.x; const targetY = 2.0 * Math.cos(phi) + this.position.y; const targetZ = 2.0 * Math.sin(phi) * Math.sin(theta) + this.position.z; const target = new THREE.Vector3(targetX, targetY, targetZ); if (this.changeListener) this.changeListener(this.position, target); } walk() { const now = Date.now(); const correction = (now - this.lastFrame) / (1000 / 60); this.lastFrame = now; this.zDelta += this.lastMovement.move.z * correction * 0.02; // Creep speed up as user presses W/S this.zDelta = this.lastMovement.move.z * Math.min(Math.abs(this.zDelta), 0.2); this.xDelta += this.lastMovement.move.x * correction * 0.02; // Creep speed up as user presses A/D this.xDelta = this.lastMovement.move.x * Math.min(Math.abs(this.xDelta), 0.1); if (this.lastMovement.move.z === 0) this.zDelta = 0; // Full stop if (this.lastMovement.move.x === 0) this.xDelta = 0; // Full stop this.lon += this.lastMovement.turn.x * correction * 2; this.lat += this.lastMovement.turn.y * correction * 2; this.lat = Math.max(-89.9, Math.min(89.9, this.lat)); const phi = this.lat * Math.PI / 180; const theta = this.lon * Math.PI / 180; this.velocity.y -= this.gravity; // Gravity const moveStep = new THREE.Vector3(this.xDelta, 0, this.zDelta); moveStep.multiplyScalar(correction); const shift = this.rotateStep(moveStep, phi, theta); shift.y = this.velocity.y; const nextPosition = this.position.clone().add(shift); const boundary = this.position.clone().add(shift.normalize()); if (this.onGround(nextPosition)) { nextPosition.y = Math.floor(nextPosition.y) + 0.5; this.velocity.y = 0; } if (this.canMove(boundary)) { this.position = nextPosition; } else { this.zDelta = 0; if (this.position.y > nextPosition.y) { this.position.y = nextPosition.y; } else { this.velocity.y = 0; } } // Camera target is 2 units (arbitary distance) in front of the view point const targetStep = new THREE.Vector3(0, 0, 2); const target = this.position.clone().add(this.rotateStep(targetStep, phi, theta)); if (this.changeListener) this.changeListener(this.position, target); } rotateStep(step: THREE.Vector3, phi: number, theta: number) { const rotationZ = new THREE.Matrix4().makeRotationZ(0); const rotationX = new THREE.Matrix4().makeRotationX(phi); const rotationY = new THREE.Matrix4().makeRotationY(theta); const rotationXY = rotationY.multiply(rotationX); const shift = step.clone().applyMatrix4(rotationZ).applyMatrix4(rotationXY); return shift; } canMove(position: THREE.Vector3) { const x = Math.floor(position.x); const y = Math.floor(position.y); const z = Math.floor(position.z); // I'm two blocks tall! const blockHead = this.world.getBlock(x, y + 1, z); const blockBody = this.world.getBlock(x, y, z); return blockBody === 0 && blockHead === 0; } onGround(position: THREE.Vector3) { const x = Math.floor(position.x); const y = Math.round(position.y) - 1; const z = Math.floor(position.z); const block = this.world.getBlock(x, y, z); return block !== 0; } update(position: THREE.Vector3, direction: THREE.Vector2) { this.position = position; this.lat = direction.x; this.lon = direction.y; } getPosition() { return this.position; } getDirection() { return new THREE.Vector2(this.lat, this.lon); } setPosition(position: THREE.Vector3) { this.position = position; } setDirection(direction: THREE.Vector2) { this.lat = direction.x; this.lon = direction.y; } }
2b3757f537292f0b491d373f00a54067c842d49b
TypeScript
hanzo2001/gi-json
/sources/Nodes/Utils.ts
2.890625
3
/// <reference path="../typings/index.d.ts" /> export var isFloatRE = /^-?(0|[1-9]\d*)(((\.\d+)|([eE]-?\d+))|(\.\d+[eE]-?\d+))$/; export var isIntRE = /^-?(0|[1-9]\d*)$/; export class ElementParser { static parseBool(v: string): boolean { if (v === 'false') {return false;} if (v === 'true') {return true;} return !!v; } static parseNumber(v: string): number { if (isFloatRE.test(v)) {return parseFloat(v);} if (isIntRE.test(v)) {return parseInt(v);} return NaN; } static str2html(s: string): string { return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/"/g,'&quot;'); } static html2str(s: string): string { return s.replace(/"/g,'&quot;').replace(/&lt;/g,'<').replace(/&amp;/g,'&'); } static str2json(s: string): string { return s.replace(/"/g,'\\"') } } export function clearTextNodes(e: Node): Node { let c: Node = e.firstChild; let n: Node; while (c) { n = c.nextSibling; if (!(c instanceof HTMLElement)) {e.removeChild(c);} c = n; } return e; } export function nullO(debug?: boolean) { return Object.create(debug?{hasOwnPropery:Object.prototype.hasOwnProperty}:null); }
9377ceb5921a4e6c86aa317d8781a8cce7f1dbb8
TypeScript
ltruchot/fantasyland-deno-ts
/01_callbacks.ts
3.109375
3
import { randomTime } from "./helpers.ts"; // callback hell: pyramid of doom let val = ""; setTimeout(() => { val += "it begin. "; setTimeout(() => { val += "it continue. "; setTimeout(() => { val += "it end. "; setTimeout(() => { console.log(val), randomTime(); }); }, randomTime()); }, randomTime()); }, randomTime()); // callback hell: spaghetti code const start = (val: string, callback: Function) => { setTimeout(() => callback(val + "it begin. ", addEnd), randomTime()); }; const addContinue = (val: string, callback: Function) => { setTimeout(() => callback(val + "it continue. ", console.log), randomTime()); }; const addEnd = (val: string, callback: Function) => { setTimeout(() => callback(val + "it end. "), randomTime()); }; start("", addContinue);
5fbdf39fbdbd7e871e2d3bd9c6041c4769d2d0ae
TypeScript
primemaster-git/nsfw-heroku-tg-bot
/src/lib/appBotRouter.ts
2.796875
3
import express, { Router } from "express"; import * as dotenv from "dotenv"; import type TelegramBot from "./telegramBot"; dotenv.config(); const BASE_URL = process.env.APP_URL || "https://nfsw-telegram-bot.herokuapp.com:443"; /** * @typedef {import('../lib/telegramBot.js')} TelegramBot */ /** * Создание роутера для телеграмм-бота: * 1. Создаёт веб-хук для бота * 2. Содержит метод поиска подписчиков */ class AppBotRouter<TypeBot extends TelegramBot> { bot: TypeBot; router: Router; /** * Создаёт для бота веб=хук и привязывает его к адресу. * @param {TelegramBot} bot Бот * @param {string} baseUrl URL апи, к которому привязать веб-хук */ constructor(bot: TypeBot, baseUrl: string) { this.bot = bot; const urlWebHook = `${BASE_URL}${baseUrl}/webhook`; this.router = express.Router(); this.router.post("/webhook", (req, res) => { bot.bot.processUpdate(req.body); res.sendStatus(200); }); bot.bot.setWebHook(urlWebHook); } /** * Возвращает список ID чатов для рассылки */ async getChatForMailing() { const ids = await this.bot.manageSubscribe?.getChatIdsForMailing(); if (!ids) return []; const promiseArray = []; for (const chatId of ids) { promiseArray.push( this.canSendMessage(chatId).catch(() => ({ chatId: chatId, possibleSend: false, })) ); } const promise = Promise.all(promiseArray); return promise.then((array) => array.reduce((acc: string[], item) => { if (item && item.possibleSend) { acc.push(item.chatId); } return acc; }, []) ); } /** * Проверка того, что можно отправить сообщение * @param {string | number} chatId ID чата * @returns {Promise<Object>} */ private async canSendMessage(chatId: string) { const { bot } = this.bot; try { const info = await bot.getChat(chatId); if (info.permissions) { const { permissions: { can_send_media_messages = false }, } = info; return { chatId, possibleSend: can_send_media_messages }; } // Если юзер, то он всегда может получать сообщения return chatId ? { chatId, possibleSend: true } : { chatId, possibleSend: false }; } catch (e) { return false; } } } export default AppBotRouter;
43e6e7996bbcd9a6099e832562fd63983c8ba73c
TypeScript
aws-amplify/amplify-cli
/packages/amplify-provider-awscloudformation/src/iterative-deployment/helpers.ts
2.515625
3
import { DeployMachineContext, DeploymentMachineOp } from './state-machine'; export const collectError = (context: DeployMachineContext, err: any, meta: any) => { return { ...context, errors: [ ...(context.errors ? context.errors : []), { error: err.data, stateValue: JSON.stringify(meta.state.value), currentIndex: context.currentIndex }, ], }; }; export const isRollbackComplete = (context: DeployMachineContext) => { return context.currentIndex < 0; }; export const isDeploymentComplete = (context: DeployMachineContext) => { return context.currentIndex >= context.stacks.length; }; const getOperationPollerActivityHandler = ( stackEventPollFn: (stack: Readonly<DeploymentMachineOp>) => () => void, operation: 'deploying' | 'rollingback', ) => { return (context: Readonly<DeployMachineContext>) => { if (context.currentIndex >= 0 && context.currentIndex < context.stacks.length) { const stack = context.stacks[context.currentIndex]; const step = operation == 'deploying' ? stack.deployment : stack.rollback; return stackEventPollFn(step); } return () => { // empty }; }; }; export const getDeploymentActivityPollerHandler = (fn) => getOperationPollerActivityHandler(fn, 'deploying'); export const getRollbackActivityPollerHandler = (fn) => getOperationPollerActivityHandler(fn, 'rollingback'); const getOperationHandler = ( fn: (stack: Readonly<DeploymentMachineOp>) => Promise<void>, operation: 'deploying' | 'rollingback', ): ((context: Readonly<DeployMachineContext>) => Promise<void>) => { return (context: DeployMachineContext) => { if (context.currentIndex >= 0 && context.currentIndex < context.stacks.length) { const stack = context.stacks[context.currentIndex]; const step = operation == 'deploying' ? stack.deployment : stack.rollback; return fn(step); } return Promise.resolve(); }; }; export const getDeploymentOperationHandler = (fn) => getOperationHandler(fn, 'deploying'); export const getRollbackOperationHandler = (fn) => getOperationHandler(fn, 'rollingback'); export const getBucketKey = (keyOrUrl: string, bucketName: string): string => { if (keyOrUrl.startsWith('https://') && keyOrUrl.includes(bucketName)) { return keyOrUrl.substring(keyOrUrl.indexOf(bucketName) + bucketName.length + 1); } return keyOrUrl; }; export const getHttpUrl = (keyOrUrl: string, bucketName: string): string => { return keyOrUrl.startsWith('https://') ? keyOrUrl : `https://s3.amazonaws.com/${bucketName}/${keyOrUrl}`; }; export const getPreRollbackOperationHandler = ( fn: (stack: Readonly<DeploymentMachineOp>) => Promise<void>, ): ((context: Readonly<DeployMachineContext>) => Promise<void>) => { return (context: DeployMachineContext) => { if (context.previousDeploymentIndex >= 0 && context.previousDeploymentIndex < context.stacks.length) { const stack = context.stacks[context.previousDeploymentIndex]; const step = stack.rollback; return fn(step); } return Promise.resolve(); }; };
95955c57124f7091454f592836ffffa2a774dac7
TypeScript
IIpocTo/reLease
/frontend/src/app/core/dto.ts
2.828125
3
export class Page<T> { content: T[]; currentPage: number; totalPages: number; totalElements: number; constructor(content: T[], currentPage: number, totalPages: number, totalElements: number) { this.content = content; this.currentPage = currentPage; this.totalElements = totalElements; this.totalPages = totalPages; } } export class PageRequest { page: number; size: number; constructor(page: number, size: number) { this.page = page; this.size = size; } } export interface UserParams { email?: string; password?: string; login?: string; } export interface ProductParams { price?: number; title?: string; description?: string; }
236e1ca4ad68c82254bad984c0ed31ebd769007e
TypeScript
serrodale/ng-trello
/src/app/model/alert.model.ts
2.84375
3
import { Icon } from './icon.model'; export interface Alert { id: number; icon: string; message: string; autoHide: boolean; type: AlertType; } export class SuccessAlert implements Alert { id: number; icon: Icon; message: string; autoHide: boolean; type: AlertType; constructor(message: string, autoHide: boolean = true) { this.message = message; this.autoHide = autoHide; this.icon = Icon.CHECK; this.type = AlertType.SUCCESS; } } export class ErrorAlert implements Alert { id: number; icon: Icon; message: string; autoHide: boolean; type: AlertType; constructor(message: string, autoHide: boolean = true) { this.message = message; this.autoHide = autoHide; this.icon = Icon.WARNING; this.type = AlertType.ERROR; } } export enum AlertType { ERROR, SUCCESS, }
ab5ab7b0ea472242c0b896dc4358de143d711bd7
TypeScript
IvanKomar/scalors-list
/src/hooks/useDialog.ts
2.703125
3
import { useState, useCallback } from "react"; type UseDialog = { isModalOpen: boolean; handleOpenModal: () => void; handleCloseModal: () => void; }; const useDialog = (): UseDialog => { const [isModalOpen, setIsModalOpen] = useState(false); const handleOpenModal = useCallback(() => { setIsModalOpen(true); }, []); const handleCloseModal = useCallback(() => { setIsModalOpen(false); }, []); return { isModalOpen, handleOpenModal, handleCloseModal }; }; export default useDialog;
336ce781a329eea514f258036c5131da18e156fb
TypeScript
jayvhaile/telegraf-bot-lib
/src/message/my_message.ts
2.546875
3
import {TelegrafContext} from "telegraf/typings/context"; import {Message} from "telegraf/typings/telegram-types"; import {Wrapped} from "../types"; import MyExtra, {MyExtraParams} from "./extra/my_extra"; import MyBody from "./body/my_body"; export class MyMessage { constructor( readonly body: MyBody, readonly extra: MyExtra, ) { } send(ctx: TelegrafContext, chatId: string): Promise<Message> { return this.body.send(ctx, chatId, this.extra.build(ctx)); }; reply(ctx: TelegrafContext): Promise<Message> { return this.body.reply(ctx, this.extra.build(ctx)); } editBody(ctx: TelegrafContext, messageId: number): Promise<Message | boolean> { return this.body.edit(ctx, messageId); } editBodyIn(ctx: TelegrafContext, messageId: number, chatId: string): Promise<Message | boolean> { return this.body.editIn(ctx, messageId, chatId); } editExtra(ctx: TelegrafContext): Promise<Message | boolean> { return this.extra.edit(ctx); } editExtraIn(ctx: TelegrafContext, messageId: number, chatId: string): Promise<Message | boolean> { return this.extra.editIn(ctx, messageId, chatId); } static text(text: Wrapped<string>, extra?: MyExtra|MyExtraParams): MyMessage { return new MyMessage(MyBody.text(text), extra instanceof MyExtra?extra:MyExtra.from(extra)); } static photo(file: Wrapped<string>, extra?: MyExtra|MyExtraParams): MyMessage { return new MyMessage(MyBody.photo(file), extra instanceof MyExtra?extra:MyExtra.from(extra)); } static video(file: Wrapped<string>, extra?: MyExtra|MyExtraParams): MyMessage { return new MyMessage(MyBody.video(file), extra instanceof MyExtra?extra:MyExtra.from(extra)); } static audio(file: Wrapped<string>, extra?: MyExtra|MyExtraParams): MyMessage { return new MyMessage(MyBody.audio(file), extra instanceof MyExtra?extra:MyExtra.from(extra)); } static voice(file: Wrapped<string>, extra?: MyExtra|MyExtraParams): MyMessage { return new MyMessage(MyBody.voice(file), extra instanceof MyExtra?extra:MyExtra.from(extra)); } static document(file: Wrapped<string>, extra?: MyExtra|MyExtraParams): MyMessage { return new MyMessage(MyBody.document(file), extra instanceof MyExtra?extra:MyExtra.from(extra)); } }
87aaa861a375101cad106e045b470e2f38674482
TypeScript
shileen/Cracking-the-Coding-Interview-TypeScript
/src/chapter08_recursion-and-dynamic-programming/8.8_permutations-with-dups/index.ts
3.390625
3
class CharFrequencies { static fromString = (str: string) => new CharFrequencies(CharFrequencies.getFreqsFromString(str)); private static getFreqsFromString = (str: string) => str.split('').reduce( (frqs, c) => ({ ...frqs, [c]: (frqs[c] || 0) + 1, }), {} as { [c: string]: number }, ); constructor(private readonly freqs: { [c: string]: number }) {} decrementChar = (c: string) => new CharFrequencies({ ...this.freqs, [c]: this.freqs[c] - 1, }); getAvailableChars = () => Object.keys(this.freqs).filter(c => this.freqs[c] > 0); } const recursiveDupeSafeStringPermutations: ( freqs: CharFrequencies, prefix?: string, ) => string[] = (freqs, prefix = '') => { const chars = freqs.getAvailableChars(); if (chars.length === 0) return prefix === '' ? [] : [prefix]; return chars.reduce( (perms, c) => [ ...perms, ...recursiveDupeSafeStringPermutations( freqs.decrementChar(c), prefix + c, ), ], [] as string[], ); }; export const dupeSafeStringPermutations = (str: string) => recursiveDupeSafeStringPermutations(CharFrequencies.fromString(str));
8a51e9af8b5da43d66ab376487e80938d93e4f71
TypeScript
NguyenVuNhan/ng-path-finder
/src/app/classes/base/node.ts
3.09375
3
import {IPoint, PointType} from "../../interfaces/grid-map"; export class Node implements IPoint { x: number; y: number; cost: number; type: PointType; visited: boolean; preNode: Node; currentCost: number; constructor(x: number, y: number, type: PointType, preNode: Node = null, currentCost: number = 0) { this.x = x; this.y = y; this.type = type; this.visited = false; switch (this.type) { case "B": this.cost = 1; break; case "M": this.cost = 5; break; default: this.cost = -1; } this.preNode = preNode; this.currentCost = currentCost; } }
ea237f71471b8bc27e197e41331a831ab82eec5e
TypeScript
isamed92/rxjs
/src/observables/02-unsubscribe-add.ts
3.3125
3
import { Observable, Observer, observable } from 'rxjs'; const observer: Observer<any> = { next: value => console.log('next:', value), error: err => console.warn('error:', err), complete: () => console.info('completed') }; const interval$ = new Observable<number>(subscriber => { // Crear un contador 1, 2, 3, 4, 5 let contador: number = 0; const interevalo = setInterval(()=>{ //cada segundo contador++; subscriber.next(contador); console.log(contador); }, 1000); setTimeout(() => { subscriber.complete(); }, 2500); return () => { clearInterval(interevalo); console.log('intervalo destruido'); }; }); const subscription1 = interval$.subscribe(observer); const subscription2 = interval$.subscribe(observer); const subscription3 = interval$.subscribe(observer); // Para encadenar observables subscription1.add(subscription2) .add(subscription3); setTimeout(()=>{ subscription1.unsubscribe(); // subscription1.unsubscribe(); // subscription2.unsubscribe(); // subscription3.unsubscribe(); console.log('completado timeout'); }, 6000)
6eb4eeb02023c5724035d98012c087df2314d1b2
TypeScript
pongkot/learn-di
/src/modules/user/interfaces/IUserRepository.ts
2.5625
3
export interface IUserRepository { listUsers(): Array<{ id: number, name: string }> }
4b389ecead04c4ee2d6ba284f662c4b0a3240fd5
TypeScript
iyosayi/inbranded
/src/helpers/create.dir.ts
2.84375
3
import { existsSync, mkdir } from 'fs' import path from 'path' /** * @function createDir checks if the pdf directory exists already, * If not, it creates it on server startup */ export const createDir = function createDir(directory: string) { if (!existsSync(directory)) { mkdir(path.resolve(directory), { recursive: true }, (err) => { if (err) { throw err } return 'done' }) } }
d2e368c657ae271ca6b6950a92a0ab9a55cf4e5c
TypeScript
kaorun343/vue-property-decorator
/src/decorators/Ref.ts
2.5625
3
import Vue from 'vue' import { createDecorator } from 'vue-class-component' /** * decorator of a ref prop * @param refKey the ref key defined in template */ export function Ref(refKey?: string) { return createDecorator((options, key) => { options.computed = options.computed || {} options.computed[key] = { cache: false, get(this: Vue) { return this.$refs[refKey || key] }, } }) }
14385caa61a638d6e0b4ac07f2b1a0f5c250bca3
TypeScript
alex-alina/dinner-planner-server
/src/recipes/entity.ts
2.515625
3
import { BaseEntity, Entity, PrimaryGeneratedColumn, Column, OneToMany } from 'typeorm' import { IsString } from 'class-validator'; import RecipeIngredient from '../recipeIngredients/entity'; import Day from '../days/entity'; import Rating from '../ratings/entity'; @Entity() export default class Recipe extends BaseEntity { @PrimaryGeneratedColumn() id?: number @IsString() @Column('text') name: string @Column('text', { nullable: true }) image?: 'string' @Column('integer', { nullable: true }) cookingTime: number @IsString() @Column('text', { nullable: true }) instructions: string @IsString() @Column('text', { nullable: true }) diffLevel: string @IsString() @Column('text', { nullable: true }) season: string @IsString() @Column('text', { nullable: true }) dietary: string @OneToMany(() => RecipeIngredient, recipeIngredient => recipeIngredient.recipe) recipeIngredients: RecipeIngredient[] @OneToMany(() => Day, day => day.recipe) days: Day[] @OneToMany(() => Rating, rating => rating.recipe) ratings: Rating[] }
e2b69928c1ac180f666a21d3d2d4cdef05d9fbd9
TypeScript
Samyuktaa-Balaji/Trello-sample
/apps/myapp-e2e/src/support/drag-support.ts
2.546875
3
export function drag(dragSelector: string, dropSelector: string) { cy.get(dragSelector).should('exist').get(dropSelector).should('exist'); const draggable = Cypress.$(dragSelector)[0]; // Pick up this const droppable = Cypress.$(dropSelector)[0]; // Drop over this const coords = droppable.getBoundingClientRect(); draggable.dispatchEvent(<any>new MouseEvent('mousedown')); draggable.dispatchEvent(<any>new MouseEvent('mousemove', {clientX: 10, clientY: 0})); draggable.dispatchEvent(<any>new MouseEvent('mousemove', { // I had to add (as any here --> maybe this can help solve the issue??) clientX: coords.left + 10, clientY: coords.top + 10 // A few extra pixels to get the ordering right })); draggable.dispatchEvent(new MouseEvent('mouseup')); return cy.get(dropSelector); }
4afb0e4c1c6acfa47e2649e4b216ecdb748d9a92
TypeScript
murindwaz/qwik
/src/core/util/dom.ts
2.703125
3
/** * @license * Copyright Builder.io, Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://github.com/BuilderIO/qwik/blob/main/LICENSE */ /** * Remove `childNode` from `parentNode` and return `nextSibling` */ export function removeNode(parentNode: Node, childNode: Node): Node | null { const nextSibling = childNode.nextSibling as Node | null; previousParent.set(childNode, parentNode as Element); parentNode.removeChild(childNode); return nextSibling; } /** * Replace `existingNode` with `newNode` */ export function replaceNode<T extends Node>( parentNode: Node, existingNode: Node | null, newNode: T ): T { parentNode.insertBefore(newNode, existingNode); if (existingNode) { previousParent.set(existingNode, parentNode as Element); parentNode.removeChild(existingNode); } return newNode; } export function getParentElement(node: Node): Element | null { return node.parentElement || previousParent.get(node) || null; } export const previousParent = new WeakMap<Node, Element>();
efad1ad035c97cf39e067459ed42898e32df9b54
TypeScript
Ecodev/my-ichtus
/client/app/shared/validators.spec.ts
2.6875
3
import {UntypedFormControl, ValidatorFn} from '@angular/forms'; import {iban} from './validators'; function validate(validatorFn: ValidatorFn, expected: boolean, value: any): void { const control = new UntypedFormControl(); control.setValidators(validatorFn); control.setValue(value); expect(control.valid) .withContext(JSON.stringify(value) + ' should be ' + (expected ? 'valid' : 'invalid')) .toBe(expected); } describe('iban', () => { it('should validate IBAN', () => { validate(iban, true, 'CH8589144971834589944'); }); it('should validate formatted IBAN', () => { validate(iban, true, 'CH85 8914 4971 8345 8994 4'); }); it('should validate weirdly formatted IBAN', () => { validate(iban, true, ' D E 9 3 5 0 0 1 05 1 7 9 98 67 78 92 4 '); }); it('should not validate non-SEPA countries', () => { validate(iban, false, 'SN68Y23411897738779716761865'); }); });
f6b01233234a8250665f72974b8f8970c4240aff
TypeScript
bogdanq/tic-tac
/client/src/api/ws/types/ws.ts
2.578125
3
import { GetMessagesResponse, SendMessagesResponse, SendMessagesParams, GetMessagesParams, } from "./chat"; export enum Type { default = "default", event = "event", } export enum Methods { fetchUser = "session.get", signUp = "session.create", signIn = "session.entry", chatMessages = "chat.messages", chatSendMessage = "chat.send.message", } export enum SubscriptionMethods { chatMessages = "chat.messages", } export type DefaultResponse = { method: Methods | SubscriptionMethods; type: Type; payload: { payload: any; params: any; }; isSuccess: boolean; reqId: string; code: number; error?: string; }; export type CommonResponse = { isSuccess: boolean; reqId: string; code: number; }; export type Response = { method: Methods; type: Type; payload: { payload: object; params: object | null; } | null; isSuccess: boolean; reqId: string; code: number; }; export type DefaultEventResponse = Omit<Response, "reqId">; export type wsRequest = SendMessagesParams | GetMessagesParams; export type ErrorResponse = { payload: null; error: string; } & Omit<Response, "payload" | "type">; export type wsResponse = | ErrorResponse | GetMessagesResponse | SendMessagesResponse | DefaultEventResponse;
05392ac9faa76dbbc7b117a93a76feb3bd9dc8d3
TypeScript
kaw2k/ownitama
/src/actions.ts
2.984375
3
import { Absolute, Card, Coordinate, Game, LobbyState, PlayerLobby, } from './interfaces' import { Cards } from './data/cards' import { InitialBoard } from './data/board' import { clone } from './helpers/clone' import { possibleMoves, doesCardHaveMove } from './helpers/moves' import { equalCoordinates } from './helpers/coordinates' import { shuffle } from './helpers/shuffle' export function makeMove( game: Game, origin: Coordinate<Absolute>, target: Coordinate<Absolute>, card?: Card ): Game | 'specify-card' { let nextGame = clone(game) // Find all our possible moves, we will use this to see if it is valid // or needs more information from the player const possibleMoveOptions = possibleMoves(nextGame, origin).filter(c => equalCoordinates(c, target) ) // If there are multiple cards that get us to our target if (possibleMoveOptions.length > 1 && !card) return 'specify-card' // Swap the card that was used for the next card if (possibleMoveOptions.length > 1 && card) { const cardIndex = nextGame.players[0].cards[0].name === card.name ? 0 : 1 nextGame.players[0].cards[cardIndex] = nextGame.card nextGame.card = card } else if ( doesCardHaveMove(nextGame, origin, target, nextGame.players[0].cards[0]) ) { nextGame.card = game.players[0].cards[0] nextGame.players[0].cards[0] = game.card } else { nextGame.card = game.players[0].cards[1] nextGame.players[0].cards[1] = game.card } nextGame.lastMove = { origin, target } // Move the piece nextGame.board[target[0]][target[1]] = game.board[origin[0]][origin[1]] nextGame.board[origin[0]][origin[1]] = false // Rotate the players nextGame.players = [nextGame.players[1], nextGame.players[0]] return nextGame } export function makeGame( players: [PlayerLobby, PlayerLobby], initialCards?: LobbyState['cards'] ): Game { let cards = shuffle( (initialCards || ([] as Card[])).concat(shuffle(Cards)).slice(0, 5) ) const shuffledPlayers = shuffle(players) return { card: cards[0], players: [ { cards: [cards[1], cards[2]], color: 'blue', id: shuffledPlayers[0].id, name: shuffledPlayers[0].name, }, { cards: [cards[3], cards[4]], color: 'red', id: shuffledPlayers[1].id, name: shuffledPlayers[1].name, }, ], board: InitialBoard, lastMove: null, } }
c37beea2aa7a52797a8c75a66b8e08d91f91aa27
TypeScript
Keith-CY/molecule-javascript
/src/struct/struct.spec.ts
2.515625
3
import { serializeStruct, deserializeStruct } from '.' import { serialize as serializeFixture, deserialize as deserializeFixture } from './fixture.json' describe('Test serialize struct', () => { const fixtureTable = serializeFixture.map(({ source, expected, exception }) => [source, expected, exception]) test.each(fixtureTable)(`%s => %s ? %s`, (source: any, expected: any, exception: any) => { if (exception) { expect(() => serializeStruct(source)).toThrow(exception) } else { const actual = serializeStruct(source) expect(actual).toBe(expected) } }) }) describe('Test deserialize struct', () => { const fixtureTable = deserializeFixture.map(({ source, expected, exception }: any) => [source, expected, exception]) test.each(fixtureTable)(`%s => %s ? %s`, (source: any, expected: any, exception: any) => { if (exception) { expect(() => deserializeStruct(source.serialized, source.sizes)).toThrow(exception) } else { const actual = deserializeStruct(source.serialized, source.sizes) expect(actual).toEqual(expected) } }) })
d33e2d0b9b5715f967c01e9bb6af02f0595cb489
TypeScript
cristaltae/rome
/packages/@romejs/js-ast-utils/doesNodeMatchPattern.ts
3.078125
3
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {AnyNode} from '@romejs/js-ast'; import getNodeReferenceParts from './getNodeReferenceParts'; // TODO make this accept multiple matches export default function doesNodeMatchPattern( member: AnyNode, match: string | Array<string>, allowPartial: boolean = false, ): boolean { // Not a member expression if (member.type !== 'MemberExpression' && member.type !== 'Identifier') { return false; } const expectedParts: Array<string> = Array.isArray(match) ? match.slice() : match.split('.'); const [bailed, actualParts] = getNodeReferenceParts(member); // Bailed will be true if we were unable to derive a name for one of the parts if (bailed && !allowPartial) { return false; } // If there's less parts than the amount we expect then it's never going to match if (actualParts.length < expectedParts.length) { return false; } // I there's more parts than we expect and we weren't passed the allowPartial flag then it's never going to match either if (allowPartial === false && actualParts.length > expectedParts.length) { return false; } // Loop over the parts we received and match them while (actualParts.length > 0) { // If we have no more expected parts then return based on if we allow partial matches if (expectedParts.length === 0) { return allowPartial; } const actual = actualParts.shift(); const expected = expectedParts.shift(); // A star part can accept anything if (expected === '*') { continue; } // A double star will eat as many parts from 'actual until we find the next expected part if (expected === '**') { const next = expectedParts.shift(); if (next === '*' || next === '**') { throw new Error( `The next expected part was ${next} but this isn't allowed since we're processing a double star`, ); } let found = false; while (actualParts.length > 0) { const actual = actualParts.shift(); if (actual === next) { found = true; break; } } if (found) { continue; } else { return false; } } if (expected !== actual) { return false; } } return true; }
63b568a7f03e2705ed7bedab64bbba0684fd1b8c
TypeScript
CaptainOfPhB/yuque-plugin
/src/actions/copyUrl.ts
2.515625
3
import copyToClipboard from '@/helper/copyToClipboard'; /** * Copy the current page url to markdown format * @returns {Promise<void>} */ async function copyUrl(): Promise<void> { const markdownLink = `[${document.title}](${location.href})`; await copyToClipboard(markdownLink, '页面链接'); } export default copyUrl;
e6dfa99eabc0cbb7d8cce62e3ea7270c7a9c2097
TypeScript
KostiaSA/happylook-wms-obmen
/wms-import/processRequest.ts
2.703125
3
import { isNumber, isString } from "util"; import { stringAsSql } from './stringAsSql'; import { executeSql } from "./executeSql"; import { sleep } from "./sleep"; interface IAns { Ошибка: number, ТекстОшибки: string } function checkPackage(body: any): IAns { if (!body.НомерПакета) return { Ошибка: 3, ТекстОшибки: "нет тэга 'НомерПакета'" }; if (!body.Данные) return { Ошибка: 3, ТекстОшибки: "нет тэга 'Данные'" }; body.НомерПакета = Number.parseInt(body.НомерПакета); if (isNaN(body.НомерПакета)) return { Ошибка: 3, ТекстОшибки: "неверный тэг 'НомерПакета'" }; if (!Array.isArray(body.Данные) || body.Данные.length == 0) return { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Данные'" }; if (!body.Комментарий) body.Комментарий = " "; if (!body.ФИОМенеджера) body.ФИОМенеджера = ""; return { Ошибка: 0, ТекстОшибки: "OK" }; } async function saveErrorToLog(body: any, err: IAns): Promise<IAns> { if (!body.Тип) body.Тип = "?"; if (isNaN(parseInt(body.НомерПакета))) body.НомерПакета = 0; try { await executeSql(` insert _JSON_IN_LOG([Номер пакета],[Тип пакета],Сообщение,[Время создания],[Дата создания],Длительность,SQL,Обработан,Ошибка) values( ${body.НомерПакета}, ${stringAsSql(body.Тип.toString())}, ${stringAsSql(JSON.stringify(body))}, getdate(), convert(date,getdate()), 0, '', 0, ${stringAsSql(err.ТекстОшибки)} )`); } catch{ } return err; } async function executeSqlInCycle() { } let sqlQueue: { sql: string[], body: any }[] = []; async function runSqlQueue() { while (true) { if (sqlQueue.length > 0) { var q = sqlQueue.shift(); try { if (q) await executeImportPackageEx(q.sql, q.body); } catch (e) { console.log(e); } } else { await sleep(1000); console.log("wait", new Date()); } } } runSqlQueue().then(); async function executeImportPackage(sql: string[], body: any): Promise<IAns> { sqlQueue.push({ sql, body }); // setTimeout(async () => { // await executeImportPackageEx(sql, body); // }, 1000); return { Ошибка: 0, ТекстОшибки: "OK" }; } async function executeImportPackageEx(sql: string[], body: any): Promise<IAns> { let duration = 0; let startTime: Date = new Date(); try { await executeSql(sql.join("\n")); let endTime = new Date(); duration = endTime.getTime() - startTime.getTime(); await executeSql(` insert _JSON_IN_LOG([Номер пакета],[Тип пакета],Сообщение,[Время создания],[Дата создания],Длительность,SQL,Обработан,Ошибка) values( ${body.НомерПакета}, ${stringAsSql(body.Тип.toString())}, ${stringAsSql(JSON.stringify(body))}, getdate(), convert(date,getdate()), ${duration}, ${stringAsSql(sql.join("\n"))}, 1, 'OK' )`); return { Ошибка: 0, ТекстОшибки: "OK" }; } catch (err) { let endTime = new Date(); duration = endTime.getTime() - startTime.getTime(); await executeSql(` insert _JSON_IN_LOG([Номер пакета],[Тип пакета],Сообщение,[Время создания],[Дата создания],Длительность,SQL,Обработан,Ошибка) values( ${body.НомерПакета}, ${stringAsSql(body.Тип.toString())}, ${stringAsSql(JSON.stringify(body))}, getdate(), convert(date,getdate()), ${duration}, ${stringAsSql(sql.join("\n"))}, 0, ${stringAsSql(err.toString())} )`); return { Ошибка: 3, ТекстОшибки: err.toString() }; } } export async function processRequest(body: any): Promise<IAns> { if (body.Тип == "Справочник.НоменклатурныеГруппы") { let err = checkPackage(body); if (err.Ошибка != 0) return saveErrorToLog(body, err); let sql: string[] = []; sql.push("BEGIN TRAN;"); for (let obj of body.Данные) { if (!isString(obj.IDD) || obj.IDD.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'IDD'" }); if (!isString(obj.Код) || obj.Код.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Код'" }); if (!isString(obj.Наименование) || obj.Наименование.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Наименование'" }); if (!isString(obj.Родитель) || obj.Родитель.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Родитель'" }); sql.push(` delete from [_JSON_IN_Вид ТМЦ] where _1С_GUID=${stringAsSql(obj.IDD)}; insert [_JSON_IN_Вид ТМЦ]([_1С_GUID],[Код],[Наименование],[Родитель]) values( ${stringAsSql(obj.IDD)}, ${stringAsSql(obj.Код)}, ${stringAsSql(obj.Наименование)}, ${stringAsSql(obj.Родитель)} );`); } sql.push("EXEC [_JSON_IN_Импорт];"); sql.push("COMMIT;"); return executeImportPackage(sql, body); } else if (body.Тип == "Справочник.Номенклатура") { let err = checkPackage(body); if (err.Ошибка != 0) return saveErrorToLog(body, err); let sql: string[] = []; sql.push("BEGIN TRAN;"); for (let obj of body.Данные) { if (!obj.Комментарий) obj.Комментарий = ""; if (!isString(obj.IDD) || obj.IDD.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'IDD'" }); if (!isString(obj.Код) || obj.Код.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Код'" }); if (!isString(obj.Наименование) || obj.Наименование.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Наименование'" }); if (!isString(obj.Родитель) || obj.Родитель.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Родитель'" }); if (!isString(obj.Бренд) || obj.Бренд.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Бренд'" }); if (!isString(obj.ЕдИзм) || obj.ЕдИзм.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'ЕдИзм'" }); if (!isString(obj.Артикул) || obj.Артикул.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Артикул'" }); if (typeof obj.КолВУпаковке != "number") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный тэг 'КолВУпаковке'" }); sql.push(` delete from [_JSON_IN_ТМЦ] where _1С_GUID=${stringAsSql(obj.IDD)}; insert [_JSON_IN_ТМЦ]([_1С_GUID],[Код],[Наименование],[Родитель],[Бренд],[Ед.изм.],[Кол. в упаковке],[Артикул]) values( ${stringAsSql(obj.IDD)}, ${stringAsSql(obj.Код)}, ${stringAsSql(obj.Наименование)}, ${stringAsSql(obj.Родитель)}, ${stringAsSql(obj.Бренд)}, ${stringAsSql(obj.ЕдИзм)}, ${obj.КолВУпаковке}, ${stringAsSql(obj.Артикул)} );`); } sql.push("EXEC [_JSON_IN_Импорт];"); sql.push("COMMIT;"); return executeImportPackage(sql, body); } else if (body.Тип == "Справочник.Контрагенты") { let err = checkPackage(body); if (err.Ошибка != 0) return saveErrorToLog(body, err); let sql: string[] = []; sql.push("BEGIN TRAN;"); for (let obj of body.Данные) { if (!isString(obj.IDD) || obj.IDD.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'IDD'" }); if (!isString(obj.Код) || obj.Код.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Код'" }); if (!isString(obj.Наименование) || obj.Наименование.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Наименование'" }); if (!isString(obj.ИНН) || obj.ИНН.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'ИНН'" }); if (!isString(obj.КПП) || obj.КПП.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'КПП'" }); if (!isString(obj.Адрес) || obj.Адрес.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Адрес'" }); if (!isString(obj.ГрузополучательАдрес) || obj.ГрузополучательАдрес.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'ГрузополучательАдрес'" }); if (!isString(obj.ФИОМенеджера)) return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'ФИОМенеджера'" }); sql.push(` delete from [_JSON_IN_Организация] where _1С_GUID=${stringAsSql(obj.IDD)}; insert [_JSON_IN_Организация]([_1С_GUID],[Код],[Наименование],[ИНН],[КПП],[Адрес],[ГрузополучательАдрес],[ФИОМенеджера]) values( ${stringAsSql(obj.IDD)}, ${stringAsSql(obj.Код)}, ${stringAsSql(obj.Наименование.toString().substr(0, 100))}, ${stringAsSql(obj.ИНН.toString().substr(0, 15))}, ${stringAsSql(obj.КПП.toString().substr(0, 12))}, ${stringAsSql(obj.Адрес.toString().substr(0, 200))}, ${stringAsSql(obj.ГрузополучательАдрес.toString().substr(0, 100))}, ${stringAsSql(obj.ФИОМенеджера)} );`); } sql.push("EXEC [_JSON_IN_Импорт];"); sql.push("COMMIT;"); return executeImportPackage(sql, body); } else if (body.Тип == "РегистрСведений.Штрихкоды") { let err = checkPackage(body); if (err.Ошибка != 0) return saveErrorToLog(body, err); let sql: string[] = []; sql.push("BEGIN TRAN;"); for (let obj of body.Данные) { if (!isString(obj.Код) || obj.Код.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Код'" }); if (!isString(obj.Товар) || obj.Товар.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Товар'" }); if (typeof obj.Количество != "number") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный тэг 'Количество'" }); sql.push(` delete from [_JSON_IN_ШтрихКод] where [Код]=${stringAsSql(obj.Код)}; insert [_JSON_IN_ШтрихКод]([Код],[ТМЦ],[Количество]) values( ${stringAsSql(obj.Код)}, ${stringAsSql(obj.Товар)}, ${obj.Количество} );`); } sql.push("EXEC [_JSON_IN_Импорт];"); sql.push("COMMIT;"); return executeImportPackage(sql, body); } else if (body.Тип == "Документ.ПоступлениеТоваровУслуг" || body.Тип == "Документ.РеализацияТоваровУслуг") { let err = checkPackage(body); if (err.Ошибка != 0) return saveErrorToLog(body, err); let sql: string[] = []; let docvid: string = '1'; let dateOtgr: string = ''; if (body.Тип == "Документ.РеализацияТоваровУслуг") docvid = '2'; sql.push("BEGIN TRAN;"); for (let obj of body.Данные) { if (!obj.Комментарий) obj.Комментарий = ""; if (!isString(obj.IDD) || obj.IDD.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'IDD'" }); // if (!isString(obj.Вид) || obj.Вид.trim() == "") // return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Вид'" }); if (!isString(obj.Номер) || obj.Номер.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Номер'" }); if (!isString(obj.Дата) || obj.Дата.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Дата'" }); if (!isString(obj.Комментарий)) return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "тэг 'Комментарий'" }); if (!isString(obj.Поставщик) || obj.Поставщик.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Поставщик'" }); if (!isString(obj.Грузоотправитель) || obj.Грузоотправитель.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Грузоотправитель'" }); if (!isString(obj.Получатель) || obj.Получатель.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Получатель'" }); if (!isString(obj.Грузополучатель) || obj.Грузоотправитель.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Грузополучатель'" }); if (isString(obj.ДатаОтгрузки)) dateOtgr = obj.ДатаОтгрузки; sql.push(` delete from [_JSON_IN_Договор] where _1С_GUID=${stringAsSql(obj.IDD)}; delete from [_JSON_IN_Догспец] where Договор=${stringAsSql(obj.IDD)}; insert [_JSON_IN_Договор]([_1С_GUID],[Вид],[Номер документа],[ДатаВремяИз1С],[Комментарий],[Поставщик],[Грузоотправитель],[Получатель],[Грузополучатель],[ДатаОтгрузкиИз1С]) values( ${stringAsSql(obj.IDD)}, ${docvid}, ${stringAsSql(obj.Номер)}, ${stringAsSql(obj.Дата)}, ${stringAsSql(obj.Комментарий)}, ${stringAsSql(obj.Поставщик)}, ${stringAsSql(obj.Грузоотправитель)}, ${stringAsSql(obj.Получатель)}, ${stringAsSql(obj.Грузополучатель)}, ${stringAsSql(dateOtgr)} );`); for (let spc of obj.Товары) { if (!isString(spc.Номенклатура) || spc.Номенклатура.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Номенклатура'" }); if (typeof spc.Количество != "number") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный тэг 'Количество'" }); if (typeof spc.ПорядокВвода != "number") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный тэг 'ПорядокВвода'" }); if (typeof spc.Цена != "number") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный тэг 'Цена'" }); if (typeof spc.Сумма != "number") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный тэг 'Сумма'" }); sql.push(` insert [_JSON_IN_Догспец]([Договор],[ТМЦ],[Количество],[Цена],[Сумма],[Порядок ввода]) values( ${stringAsSql(obj.IDD)}, ${stringAsSql(spc.Номенклатура)}, ${spc.Количество}, ${spc.Цена}, ${spc.Сумма}, ${spc.ПорядокВвода} );`); } } sql.push("EXEC [_JSON_IN_Импорт];"); sql.push("COMMIT;"); return executeImportPackage(sql, body); } else if (body.Тип == "Документ.КомплектацияНоменклатуры") { let err = checkPackage(body); if (err.Ошибка != 0) return saveErrorToLog(body, err); let sql: string[] = []; let docvid: string = '200'; let KomplIDD: string = ''; sql.push("BEGIN TRAN;"); for (let obj of body.Данные) { if (!isString(obj.IDD) || obj.IDD.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'IDD'" }); if (!isString(obj.Номер) || obj.Номер.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Номер'" }); if (!isString(obj.Дата) || obj.Дата.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Дата'" }); if (!isString(obj.Поставщик) || obj.Поставщик.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Поставщик'" }); if (!isString(obj.Номенклатура) || obj.Номенклатура.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Номенклатура'" }); KomplIDD = obj.Номенклатура; sql.push(` delete from [_JSON_IN_Договор] where _1С_GUID=${stringAsSql(obj.IDD)}; delete from [_JSON_IN_Догспец] where Договор=${stringAsSql(obj.IDD)}; insert [_JSON_IN_Договор]([_1С_GUID],[Вид],[Номер документа],[ДатаВремяИз1С],[Поставщик]) values( ${stringAsSql(obj.IDD)}, ${docvid}, ${stringAsSql(obj.Номер)}, ${stringAsSql(obj.Дата)}, ${stringAsSql(obj.Поставщик)} );`); for (let spc of obj.Товары) { if (!isString(spc.Номенклатура) || spc.Номенклатура.trim() == "") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный или пустой тэг 'Номенклатура'" }); if (typeof spc.Количество != "number") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный тэг 'Количество'" }); if (typeof spc.НомерСтроки != "number") return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный тэг 'НомерСтроки'" }); sql.push(` insert [_JSON_IN_Догспец]([Договор],[ТМЦ],[Комплектующий],[Количество],[Порядок ввода]) values( ${stringAsSql(obj.IDD)}, ${stringAsSql(KomplIDD)}, ${stringAsSql(spc.Номенклатура)}, ${spc.Количество}, ${spc.НомерСтроки} );`); } } sql.push("EXEC [_JSON_IN_Импорт];"); sql.push("COMMIT;"); return executeImportPackage(sql, body); } //////////////////////////////////////////////////////// Справочник.Контрагенты ///////////////////////////////////////////////// // копать тут else { return saveErrorToLog(body, { Ошибка: 3, ТекстОшибки: "неверный 'Тип' пакета: '" + body.Тип + "'" }); } }
ab7cfa0987791e5d49826cbdec6dcb062044d40f
TypeScript
JainUdit/todo-list
/src/redux-app/selectors/getFilteredTodos.ts
2.625
3
import { Filter } from "../enums"; import { ITodo, ITodoListGlobalState } from "../interfaces"; export const getFilteredTodos = (state: ITodoListGlobalState): Array<ITodo> => { switch (state.domain.filterType) { case Filter.ALL: return state.domain.todoList; case Filter.ACTIVE: return state.domain.todoList.filter(todo => !todo.completed); case Filter.COMPLETED: return state.domain.todoList.filter(todo => todo.completed); default: return state.domain.todoList; } }
5e4901705584a28078b1e7a2a3841d4b232c3457
TypeScript
andigibson93/tnt-microsoft-wk1
/TypeScriptPractice.ts
4.03125
4
// 11111111111111 // basic dataTypes console.log("basic types and constants"); // constants const myNumber: number = 1; const myWord: string = "tree"; console.log(myNumber); console.log(myWord); // const vs let const constantNumber: number = 2; console.log(constantNumber); // To-do: constantNumber = 3; // const doesn't work use let instead if you want to reassign a value // Enums console.log("enums"); enum newcolor { yellow, green, blue, black, pink, white } let textColor: newcolor = newcolor.green; console.log(`textColor: ${textColor}`); // To-do: show that textColor can't be assigned anything else // Arrays console.log("arrays"); const scores = [1, 2, 3]; console.log(scores); console.log(`scores[1]: ${scores[1]}`); // To-do: do a lot to print all the elements of scores // 222222222222222222 console.log("functions"); // Named function function addf(a: number, b: number): number { return a + b; } console.log(add(2, 3)); // Anonymous function let addedf = function (x: number, y: number) { return x + y }; // To-do: Create more basic anonymous arithmetic functions to practice // To-do: write addfa, a version of add and added that uses fat arrow // Compute 6+12 with addfa // 3333333333333333 // Objects console.log("objects"); const rectangle = { length: 4, width: 5 }; console.log(rectangle); console.log(`rectangle.length ${rectangle.length}`); rectangle.width = 7; console.log(`rectangle.width: ${rectangle.width}`); // Reference vs copy console.log("Reference"); const polygon = rectangle; polygon.width = 1; console.log(`polygon.width: ${polygon.width}`); console.log(`rectangle.width: ${rectangle.width}`); // Did the value of rectangle.width change? console.log("Copy"); const copyRect = { ...rectangle }; // can also choose to use Object.assign copyRect.width = 10; console.log(`copyRect.width: ${copyRect.width}`); console.log(`rectangle.width: ${rectangle.width}`); // Interfaces console.log("interfaces"); // Show Purpose requiring type in function and attempting to send in wrong object interface alien { name: string; color: newcolor; height: number; powerLevel: number; } function getStrongerAlien(alien1: alien, alien2: alien) { if (alien1.powerLevel > alien2.powerLevel) { return alien1; } else { return alien2; } } const namekian = { name: "namekian", color: newcolor.green, height: 7, powerLevel: 3000 }; const saiyan = { color: newcolor.yellow, powerLevel: 9001 }; const majin: alien = { name: "majin", color: newcolor.pink, height: 6.5, powerLevel: 1000000 }; // To-do: show and explain that this doesn't work // const strongerAlien = getStrongerAlien(namekian, saiyan); const strongestAlien = getStrongerAlien(namekian, majin); console.log(`Strongest Alien: ${strongestAlien.name}`); // another example of interface // passing the interface as a parameter of a function interface SquareConfig { color?: string; // ? means optional fields width?: number; } function createSquare(config: SquareConfig): { color: string; area: number } { let newSquare = { color: "white", area: 100 }; if (config.color) { // Error: Property 'clor' does not exist on type 'SquareConfig' newSquare.color = config.color; } if (config.width) { newSquare.area = config.width * config.width; } return newSquare; } // To-do: What is the result of the 2 createSquare below and why? let mySquare = createSquare({ width: 10 }); console.log("mySquare " + mySquare.color + " " + mySquare.area); let mySquare1 = createSquare({ color: "black" }); console.log("mySquare " + mySquare1.color + " " + mySquare1.area); // 4444444444444444444 // Class console.log("classes"); // To-do: add the subtract function (without parameters like add) // To-do: explain constructor // To-do: see how inheritance is implemented class Calculator { a: number; b: number; constructor(_firstNumber: number, secondNumber: number) { this.a = _firstNumber; this.b = secondNumber; } add() { return this.a + this.b; } } const myCal = new Calculator(2, 5); myCal.a = 3; console.log(`myCal.add: ${myCal.add()}`); // class inheritance class comparisonCalculator extends Calculator { findGreaterValue() { if (this.a > this.b) { return this.a; } else { return this.b; } } } const compCalc = new comparisonCalculator(6, 7); console.log(`compCalc.add: ${compCalc.add()}`); console.log(`compCalc.findGreaterValue: ${compCalc.findGreaterValue()}`); // 55555555555555555 // Generics // generic class // class as custom array of elements of type T class myCustomArray<T> { items: T[]; constructor() { this.items = [] } getItems(): T[] { return this.items; } addItem(item: T): void { this.items.push(item); } } // create an array of numbers, add elements to the array, and print the array let narray = new myCustomArray<number>(); narray.addItem(10); narray.addItem(18); narray.addItem(-5); // To-do: Add a function reverse that reverse the elements in items // To-do: Test your code
ddc5efb7f60c6b8f06303e49724fa4697de288b5
TypeScript
angular-package/property
/src/test/get-exist-property.spec.ts
3.328125
3
// Function to test. import { getExistProperty } from '../lib/get-exist-property.function'; // Object. import { OBJECT_ONE, OBJECT_TWO, ObjectOne } from './constants/object.const'; import { TRUE } from './constants/boolean.const'; /** * Test `getExistProperty()` function. */ describe(getExistProperty.name, () => { let OBJECT_ONE_CLONE: ObjectOne; beforeEach(() => OBJECT_ONE_CLONE = { ...{}, ...OBJECT_ONE }); const property = 'test'; function updateProperty(value: any, key: string): ObjectOne { value[key] = undefined; delete value[key]; return value as ObjectOne; } function removeObject(value: any): ObjectOne { value = undefined; return value; } // Defined. it('is DEFINED', () => expect(getExistProperty).toBeDefined()); describe('get property', () => { describe('from the OBJECT_ONE', () => { it('when OBJECT_ONE and its property exists', () => { expect(getExistProperty(OBJECT_ONE_CLONE, 'key as string')).toEqual(TRUE); expect(getExistProperty(OBJECT_TWO, 'x')).toEqual('One Two Three'); }); it('when OBJECT_ONE does not exist and the default callback throws an error', () => { try { getExistProperty(removeObject(OBJECT_ONE_CLONE), property); } catch (error) { expect(error.message).toContain('Object with the specified key does not exist'); } }); it('when OBJECT_ONE property does not exists and the default callback throws an error', () => { updateProperty(OBJECT_ONE_CLONE, property); try { const get = getExistProperty(OBJECT_ONE_CLONE, property); } catch (error) { expect(error.message).toContain('Object with the specified key does not exist'); } }); }); it('when OBJECT_ONE exists but its property does not exist and custom callback does not throw an error', () => { updateProperty(OBJECT_ONE_CLONE, property); getExistProperty(OBJECT_ONE_CLONE, property, (result: boolean, value: any) => { expect(result).toBeFalse(); expect(value[property]).toBeUndefined(); return result; }); }); }); });
87f6944fbed634672c770e6049fbe194f510f547
TypeScript
bcherny/mapf
/index.ts
3.421875
3
/** * Better than `Promise.all`. * * `const [a, b, c] = await mapf([1, 2, 3], async _ => await foo(_) )` */ export function mapf<T, U, V>(array: T[], cb: (this: V, t: T, index: number, array: T[]) => Promise<U>, thisArg?: V): Promise<U[]> { return Promise.all<U>(array.map(cb, thisArg)) }
607077b169f01b0b4ad21b37ed2a33ae8ec2f0e1
TypeScript
jimmy-e/visx-demo
/src/utils/scales/getXScale.ts
2.59375
3
import { scaleBand } from '@visx/scale'; import { BandScale, Data } from 'src/types'; interface Props { data: Data; index: string; xMax: number; } export default ({ data, index, xMax }: Props): BandScale => { const xScale = scaleBand<string>({ domain: data.map((datum) => String(datum[index])), padding: 0.2, }); xScale.rangeRound([0, xMax]); return xScale; }
2bd3a92599d2bf328e7d7daaf687cde1ed1dacd5
TypeScript
vuepress-theme-hope/vuepress-theme-hope
/packages/theme/src/client/composables/autoLink.ts
2.578125
3
import { useRouter } from "vue-router"; import type { AutoLinkOptions } from "../../shared/index.js"; import { resolveLinkInfo } from "../utils/index.js"; /** * Resolve AutoLink props from string * * @example * - Input: "/README.md" * - Output: { text: "Home", link: "/" } */ export const useAutoLink = ( item: string, preferFull = false, ): AutoLinkOptions => { const router = useRouter(); return resolveLinkInfo(router, item, preferFull); };
2d08cb75e658d089c6b497258f264f55e1050148
TypeScript
dylanrenwick/Canvity
/src/Canvity/Aspect.ts
3.09375
3
import { Component } from "./Component/Component"; import { HashSet } from "./Util/HashSet"; export class Aspect extends HashSet<Component> { public Get<T extends Component>(c: new(id: number) => T): T { return this.filter(this.typeCheck<T>(c)).ToArray()[0] as T; } private typeCheck<T extends Component>(c: new(id: number) => T): (value: Component, index: number, array: Array<Component>) => boolean { return value => value instanceof c; } }
95e4bcd10b516dbadc0f422e53f49239873c867d
TypeScript
DivineCross/DesignPattern
/ts/src/iterator/cat-family.ts
2.75
3
import { Cat } from './cat.js'; import { CatIterator } from './cat-iterator.js'; import { IIterable } from './i-iterable.js'; import { IIterator } from './i-iterator.js'; export class CatFamily implements IIterable<Cat> { #cats: Cat[]; constructor(cats: Cat[] = []) { this.#cats = cats; } getIterator(): IIterator<Cat> { return new CatIterator(this); } getCats(): Cat[] { return this.#cats; } }
a1ec8786704e79c8689005e4cfa8bb9cd7bb720a
TypeScript
coingaming/moon-design
/workspaces/base/src/private/helper/ServerOnlyContext.ts
2.734375
3
// @ts-ignore import { cache } from 'react'; export default <T>(defaultValue: T): [() => T, (v: T) => void] => { const getRef = cache(() => ({ current: defaultValue })); const getValue = (): T => getRef().current; const setValue = (value: T) => { getRef().current = value; }; return [getValue, setValue]; }; // const [getCurrentPage, setCurrentPage] = serverContext(1); // const [getTotalPages, setTotalPages] = serverContext(1); // setCurrentPage(currentPage); // setTotalPages(totalPages); // const currentPage = getCurrentPage(); // const totalPages = getTotalPages();
b8a76e5a4582476ca70a241867caaee7370ef2a2
TypeScript
lulijuner/bilibili-live-video-noty
/server/api/link.ts
2.578125
3
/** * Created by allen on 2016/6/29. */ import {httpGet} from './req'; import {parseString} from 'xml2js'; /** * getDownloadUrlByVideoId * 通过Video ID获取下载地址 * * @return {Promise<string>} 下载地址Promise对象 */ export function getDownloadUrlByVideoId(videoId:number):Promise<string> { /** * 以下请求会返回XML字符串, 该XML字符串为B站可下载的服务站点 */ return httpGet('http://live.bilibili.com/api/playurl', {cid: videoId}).then((xml:string)=> { let downloadUrl = null; parseString(xml, function (err, result) { if (!err && Object.keys(result)) { downloadUrl = result.video.durl[0].url[0] } }); return downloadUrl; } ) }
d7e0dd669cc3791291efebfd691f0816e237e4fc
TypeScript
zekroTJA/supercharge
/WebApp/src/app/shared/timeout.ts
3
3
/** @format */ export type Timer = ReturnType<typeof setTimeout>; export class Timeout { private timer: Timer; constructor(private delayMS: number) {} public cancel() { if (this.timer) { clearTimeout(this.timer); } } public schedule(cb: () => void) { this.cancel(); this.timer = setTimeout(cb, this.delayMS); } }
3663174eef79eb6f4723ca4b88345bcfe19889e8
TypeScript
domoritz/encodable
/packages/encodable/test/typeGuards/Base.test.ts
3.3125
3
import { isDefined, isArray, isNotArray, isEveryElementDefined } from '../../src/typeGuards/Base'; describe('type guards: Base', () => { describe('isArray<T>(maybeArray)', () => { it('returns true and converts to type T[] if is array', () => { const x: string | string[] = ['abc']; // eslint-disable-next-line jest/no-if if (isArray(x)) { // x is now known to be an array expect(x[0]).toEqual('abc'); } }); it('returns false if not', () => { expect(isArray('abc')).toBeFalsy(); }); }); describe('isNotArray<T>(maybeArray)', () => { it('returns true and converts to type T if not array', () => { const x: string | string[] = 'abc'; // eslint-disable-next-line jest/no-if if (isNotArray(x)) { // x is now known to be a string expect(x.startsWith('a')).toBeTruthy(); } }); it('returns false if is array', () => { expect(isNotArray(['def'])).toBeFalsy(); }); }); describe('isDefined<T>(value)', () => { it('returns true and converts to type T if value is defined', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const x: any = 'abc'; // eslint-disable-next-line jest/no-if if (isDefined<string>(x)) { expect(x.startsWith('a')).toBeTruthy(); } }); it('returns false if not defined', () => { expect(isDefined(null)).toBeFalsy(); expect(isDefined(undefined)).toBeFalsy(); }); }); describe('isEveryElementDefined<T>(array)', () => { it('returns true and remove undefined from possible return type', () => { expect(isEveryElementDefined(['a', 'b'])).toBeTruthy(); expect(isEveryElementDefined([])).toBeTruthy(); const array: (string | undefined)[] = ['a', 'b']; if (isEveryElementDefined(array)) { expect(array.every(a => a.length === 1)).toBeTruthy(); } }); it('returns false otherwise', () => { expect(isEveryElementDefined([undefined])).toBeFalsy(); expect(isEveryElementDefined([undefined, 'a'])).toBeFalsy(); }); }); });
3f56e9ec62eea7d4fc71e33f10b92eb22ecc28b8
TypeScript
swarmbase/swarmbase
/packages/collabswarm/src/auth-provider.ts
2.59375
3
// Restrict access to those on ACL export type EncryptionResult = { data: Uint8Array; nonce?: Uint8Array; }; export interface AuthProvider<PrivateKey, PublicKey, DocumentKey = string> { sign(data: Uint8Array, privateKey: PrivateKey): Promise<Uint8Array>; verify( data: Uint8Array, publicKey: PublicKey, signature: Uint8Array, ): Promise<boolean>; encrypt( data: Uint8Array, documentKey: DocumentKey, ): Promise<EncryptionResult>; decrypt( data: Uint8Array, documentKey: DocumentKey, nonce?: Uint8Array, ): Promise<Uint8Array>; readonly nonceBits: number; }
edbb41b4bcc54763b81340700b9a17d1fab204b9
TypeScript
ARGO2006/legends-of-zeldathe-master-maze
/main.ts
3.09375
3
scene.onOverlapTile(SpriteKind.Player, sprites.dungeon.stairNorth, function (sprite, location) { game.over(true) }) sprites.onOverlap(SpriteKind.Player, SpriteKind.Food, function (sprite, otherSprite) { mySprite2.setPosition(randint(1, 160), randint(1, 160)) info.changeScoreBy(1) mySprite.say("Yay", 1000) }) let mySprite2: Sprite = null let mySprite: Sprite = null mySprite = sprites.create(img` ......ffffff...... .....ff7777ff..... ....ff777777ff.... ...ff77777777ff... ...f7f555555f7f... ...ff55555555ff... ..ff55f5555f55ff.. ffff5f5555fff5ffff fddff5555ffdf5fddf .ffff55fffddf5fff. ..f5fffffdffff5f.. ..f5f181dd181f5f.. ...ffd81dd18dfff.. ...fffddddddfff... ....ffffffffff.... ...f7f777777f7f... ..f77f777777f77f.. .fddff777777ffddf. .ffdf7ff55ff7fdff. ..fff77f55f77fff.. ....fff7777fff.... ...feeeffffeeef... ...feeff..ffeef... ....fff....fff.... `, SpriteKind.Player) controller.moveSprite(mySprite, 100, 100) tiles.setTilemap(tilemap`level1`) tiles.placeOnRandomTile(mySprite, sprites.dungeon.stairLadder) scene.cameraFollowSprite(mySprite) info.startCountdown(20) mySprite2 = sprites.create(img` . . b b b b b b b b b b b b . . . b e 4 4 4 4 4 4 4 4 4 4 e b . b e 4 4 4 4 4 4 4 4 4 4 4 4 e b b e 4 4 4 4 4 4 4 4 4 4 4 4 e b b e 4 4 4 4 4 4 4 4 4 4 4 4 e b b e e 4 4 4 4 4 4 4 4 4 4 e e b b e e e e e e e e e e e e e e b b e e e e e e e e e e e e e e b b b b b b b b d d b b b b b b b c b b b b b b c c b b b b b b c c c c c c c b c c b c c c c c c b e e e e e c b b c e e e e e b b e e e e e e e e e e e e e e b b c e e e e e e e e e e e e c b b b b b b b b b b b b b b b b b . b b . . . . . . . . . . b b . `, SpriteKind.Food) mySprite.say("Help Me Escape", 1000) mySprite2.setPosition(20, 50) game.splash("Help Link Escape")
0530ccd8369dd0c38d2745e1acfddb9aa3396e75
TypeScript
amatiasq/discord-bots
/descord/structure/EditMessagePayload.ts
2.8125
3
import { RawEditMessagePayload } from '../raw/RawEditMessagePayload.ts'; import { MessageFlag } from '../enum/MessageFlag.ts'; import { Embed, wrapEmbed, unwrapEmbed } from './Embed.ts'; // https://discord.com/developers/docs/resources/channel#edit-message-json-params export interface EditMessagePayload { /** the new message contents (up to 2000 characters) */ content?: string; /** embedded rich content */ embed?: Embed; /** edit the flags of a message (only SUPPRESSEMBEDS can currently be set/unset) */ flags?: MessageFlag; } export function wrapEditMessagePayload(x: RawEditMessagePayload): EditMessagePayload { return { ...x, embed: x.embed && wrapEmbed(x.embed), }; } export function unwrapEditMessagePayload(x: EditMessagePayload): RawEditMessagePayload { return { ...x, embed: x.embed && unwrapEmbed(x.embed), }; } export const wrapEditMessagePayloadPartial = wrapEditMessagePayload as (x: Partial<RawEditMessagePayload>) => Partial<EditMessagePayload>; export const unwrapEditMessagePayloadPartial = unwrapEditMessagePayload as (x: Partial<EditMessagePayload>) => Partial<RawEditMessagePayload>;
14b7494e3a4d8cabc46e97f3d4c390703dceb132
TypeScript
mtgibbs/d3-source-sink
/src/d3-source-sink.ts
2.71875
3
/// <reference types="d3" /> (<any>d3).sourceSink = (): SourceSink => { let _nodeHeight: number = 24; let _nodeWidth: number = 24; let _nodePadding: number = 10; let _nodes: Array<INode> = []; let _links: Array<ILink> = []; const _sourceSink: SourceSink = {}; _sourceSink.nodeHeight = (height) => { if (typeof height === 'undefined') return _nodeHeight; _nodeHeight = height; return _sourceSink; }; _sourceSink.nodeWidth = (nodewidth) => { if (typeof nodewidth === 'undefined') return _nodeWidth; _nodeWidth = nodewidth; return _sourceSink; }; _sourceSink.nodePadding = (nodepadding) => { if (typeof nodepadding === 'undefined') return _nodePadding; _nodePadding = nodepadding; return _sourceSink; }; _sourceSink.links = (links) => { if (typeof links === 'undefined') return _links; _links = links; return _sourceSink; }; _sourceSink.nodes = (nodes) => { if (typeof nodes === 'undefined') return _nodes; _nodes = nodes; return _sourceSink; }; _sourceSink.layout = () => { SourceSinkHelper.initializeLinks(_nodes, _links); SourceSinkHelper.computeNodeDepth(_nodes, _nodeHeight, _nodePadding); SourceSinkHelper.computeNodeBreadths(_nodes, _links, _nodeWidth, _nodePadding); return _sourceSink; }; _sourceSink.link = () => { let _curvature = .5; const _link = (link: ILink): string => { return SourceSinkHelper.computeLinkPath(link, _nodeHeight, _curvature); }; // HACK: Find a better way to make this function in a more typescripty way (<any>_link).curvature = (curvature: number): any => { if (typeof curvature === 'undefined') return _curvature; _curvature = curvature; return _link; }; return _link; }; return _sourceSink; }; class SourceSinkHelper { public static initializeLinks(nodes: Array<INode>, links: Array<ILink>): void { nodes.forEach(node => { node.sourceLinks = []; node.sinkLinks = []; }); links.forEach(link => { let source = link.source; let sink = link.sink; link.rootIds = []; if (typeof source === 'number') source = link.source = nodes[source]; if (typeof sink === 'number') sink = link.sink = nodes[sink]; const rootIds = (<INode>source).rootIds; if (rootIds && rootIds.length) link.rootIds = link.rootIds.concat(rootIds); (<INode>source).sinkLinks.push(link); (<INode>sink).sourceLinks.push(link); }); } public static computeNodeDepth(nodes: Array<INode>, nodeHeight: number, nodePadding: number) { let remainingNodes = nodes; let y = 0; while (remainingNodes.length) { const nextNodes: Array<INode> = []; for (let node of remainingNodes) { node.y = y; node.dy = nodeHeight; for (let link of node.sinkLinks) { if (nextNodes.indexOf(<INode>link.sink) < 0) nextNodes.push(<INode>link.sink); } } remainingNodes = nextNodes; y++; } nodes.filter(node => { return !node.sinkLinks.length; }).forEach(node => { node.y = y - 1; }); for (let node of nodes) { node.y *= nodeHeight + nodePadding; } } public static computeLinkPath(link: ILink, nodeHeight: number, curvature: number): string { const sourceNode = <INode>link.source; const sinkNode = <INode>link.sink; let x0 = 0; if (sourceNode.sinkLinks.length === 1) x0 = sourceNode.x + (sourceNode.dx / 2); else { let centerOffset = (sourceNode.dx / 2); const index = sourceNode.sinkLinks.indexOf(link); let midpoint = 0; if (sourceNode.sinkLinks.length % 2 === 0) { midpoint = sourceNode.sinkLinks.length / 2 - 1; } else { midpoint = (sourceNode.sinkLinks.length - 1) / 2; } const distanceCalc = index - midpoint; centerOffset = centerOffset + distanceCalc; x0 = sourceNode.x + centerOffset; } const x1 = sinkNode.x + sinkNode.dx / 2, y0 = sourceNode.y + nodeHeight, y1 = sinkNode.y, yi = d3.interpolateNumber(y0, y1), y2 = yi(curvature), y3 = yi(1 - curvature); return `M${x0},${y0} C${x0},${y2} ${x1},${y3} ${x1},${y1}`; } public static computeNodeBreadths(nodes: Array<INode>, links: Array<ILink>, nodeWidth: number, nodePadding: number) { const nodesByDepth = d3.nest() .key((d: any) => { return d.y; }) .sortKeys(d3.ascending) .entries(nodes) .map((d: any) => { return d.values; }); const widestRowCount = Math.max.apply(Math, nodesByDepth.map((row) => { return row.length; })); const maxX = widestRowCount * (nodeWidth + nodePadding); nodesByDepth.forEach((nodes: Array<INode>) => { const rowOffset = (maxX - (nodes.length * (nodeWidth + nodePadding))) / 2; nodes.forEach((node, i) => { node.x = i * (nodeWidth + nodePadding) + rowOffset; node.dx = nodeWidth; }); }); links.forEach((link) => { link.dx = (nodeWidth + nodePadding); }); } } interface SourceSink { nodeHeight?: (height?: number) => SourceSink | number; nodeWidth?: (width?: number) => SourceSink | number; nodePadding?: (padding?: number) => SourceSink | number; nodes?: (nodes?: Array<INode>) => SourceSink | Array<INode>; links?: (links?: Array<ILink>) => SourceSink | Array<ILink>; layout?: () => SourceSink; link?: Function; } interface SourceSinkLink { curvature: (curvature?: number) => SourceSinkLink | number; link: (link: ILink) => string; } interface INode { x: number; dx: number; y: number; dy: number; sourceLinks: Array<ILink>; sinkLinks: Array<ILink>; rootIds: Array<number>; }; interface ILink { source: INode | number; sink: INode | number; dx: number; dy: number; rootIds?: Array<number>; }
0553d5d09bb168973b645e00cf728f6afd77e6b4
TypeScript
Vovanisimous/gayaz-frontend
/src/hooks/useOrder.ts
2.578125
3
import {IOrder, IOrderRequestData} from "../entities/order.entity"; import {order} from "../database/order"; import {v4 as uuidv4} from 'uuid'; import {dealer} from "../database/dealer"; import {manager} from "../database/manager"; import {contract} from "../database/contract"; import {IDealer} from "../entities/dealer.entity"; import {IManager} from "../entities/manager.entity"; import {IContract} from "../entities/contract.entity"; interface IOrderHook { getOrders: () => Promise<IOrder[]> getOrder: (orderId: string) => Promise<IOrder | undefined> deleteOrder: (orderId: string) => Promise<void> createOrder: (order: IOrderRequestData) => Promise<IOrder | undefined> } export const useOrder = (): IOrderHook => { const getOrders = async () => { // return await transport.get<IOrder[]>('order') return order } const getOrder = async (orderId: string) => { // return await transport.get<IOrder>(`order/${orderId}`) return order.find((item) => item.id === orderId) } const deleteOrder = async (orderId: string) => { // return await transport.post<any, {}>(`order/delete/${orderId}`, {}) const orderIndex = order.findIndex((item) => item.id === orderId); order.splice(orderIndex, 1) } const createOrder = async (order1: IOrderRequestData) => { // return await transport.post<IOrder, IOrderRequestData>('order', order) const id = uuidv4(); const dealer1 = dealer.find((item) => item.id === order1.dealerId); const manager1 = manager.find((item) => item.id === order1.managerId); const contract1 = contract.find((item) => item.id === order1.contractId); const {dealerId, managerId, contractId, ...data} = order1; order.push({ id: id, order_date: new Date().toDateString(), order_status: "not_done", dealer: dealer1 as IDealer, manager: manager1 as IManager, contract: contract1 as IContract, createdAt: new Date(), updatedAt: new Date(), ...data }) return order.find((item) => item.id === id) } return {getOrders, getOrder, deleteOrder, createOrder} }
d4503f4d98257f9537012598855dc3a2a46e0d3a
TypeScript
Stdev17/nozomi
/src/__tests__/csharp.test.ts
2.984375
3
import { TSC } from '../compiler'; import { CSharpContext } from '../transform/csharp'; const csharpContext = new CSharpContext(); const tsc = new TSC({}, csharpContext); function assertType(code: string, expectType: string) { const ast = tsc.compile(code)!; const checker = tsc.checker; const node = tsc.getIdentifier(ast, 'a')!; const type = checker.getTypeAtLocation(node); expect(tsc.transform.obtainTypeName(type)).toBe(expectType); } describe('obtainTypeName', () => { test('string', () => assertType('var a: string;', 'string')); test('boolean', () => assertType('var a: boolean;', 'bool')); test('number', () => assertType('var a: number;', 'int')); test('type array string', () => assertType('var a: string[];', 'List<string>')); test('string array', () => assertType('var a: Array<string>;', 'List<string>')); test('typealias number', () => assertType('type int = number; var a: int;', 'int')); test('non-primitive object', () => assertType('var a: { b: number }', '__type')); test('regexp object', () => assertType('var a: { b: RegExp }', '__type')); });
2111d5304b3644e3870aeda6725e16c65c4e6c39
TypeScript
web-liuyang/l-native-tools
/src/object/deepClone.ts
3.46875
3
import { typeOf } from "../common"; /** * 深拷贝 * @template T * @param {T} origin - 拷贝的源对象 * @return 拷贝后的对象 */ function deepClone<T = {} | any[]>(origin: T): T { let clone = (typeOf(origin) === "array" ? [] : {}) as T; if (typeOf(origin) === "object" || typeOf(origin) === "array") { for (const key in origin) { if (typeOf(origin[key]) === "object" || typeOf(origin[key]) === "array") { clone[key] = deepClone(origin[key]); } else { clone[key] = origin[key]; } } } return clone; } export default deepClone;
5b41b31ec65504a7da7315b284dbd59ee540911c
TypeScript
blind675/StocksImporter
/src/actions/importTickers.ts
2.515625
3
import {fetchTickers} from "../services/API/Polygon"; import Ticker from "../models/Ticker"; const cliProgress = require('cli-progress'); export async function importTickers() { console.log('Importer : Start fetch tickers'); // fetch ticker const tickers = await fetchTickers(); if(tickers) { console.log(`Importer : Got ${tickers.length} tickers`); console.log('Importer : Save to DB '); // create a new progress bar instance and use shades_classic theme const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic); // start the progress bar with a total value of 200 and start value of 0 progressBar.start(tickers.length - 1, 0); // save in DB for (let i = 0; i < tickers.length; i++) { const ticker = tickers[i]; const tick = new Ticker({ symbol: ticker.ticker, name: ticker.name, type: ticker.type, details: { exchange: ticker.primary_exchange, county: ticker.locale, currency: ticker.currency_name, isin: ticker.cik } }); await tick.save(); progressBar.update(i); } // stop the progress bar progressBar.stop(); console.log('Importer : Done '); } else { console.log('Importer : No tickers found'); } }
74d139cdb72afc734a656254473398b16e4a8905
TypeScript
Dvalmont07/Deck2Deck
/src/app/Classes/Deck.ts
3.484375
3
import { Card } from "./Card"; export class Deck { suits: string[] = []; cardValues: string[] = []; addCard({ myDeck, card }: { myDeck: Card[]; card: Card; }): boolean { try { myDeck.unshift(card); return true; } catch (e) { console.log('Error:', e); } return false; } removeCard(myDeck: Card[], card: Card): boolean { try { myDeck.splice(myDeck.findIndex(element => { return element.suit == card.suit && element.value == card.value; }), 1); return true; } catch (e) { console.log('Error:', e); } return false; } getCardValues() { return ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]; } getSuits() { return ["Clubs", "Spades", "Diamonds", "Hearts"] } mountNormalDeck() { let myDeck: Card[] = []; for (let i = 0; i < this.getSuits().length; i++) { for (let j = 0; j < this.getCardValues().length; j++) { myDeck.push({ suit: this.getSuits()[i], value: this.getCardValues()[j], order: i }); } } return myDeck.sort((a, b) => { return a.order - b.order; }); } mountRandomDeck() { let myDeck: Card[] = []; for (let i = 0; i < 10; i++) { const cardSuitIndex = Math.ceil(Math.random() * this.getSuits().length - 1); const cardValueIndex = Math.ceil(Math.random() * this.getCardValues().length - 1); myDeck.push({ suit: this.getSuits()[cardSuitIndex], value: this.getCardValues()[cardValueIndex], order: i }); } return myDeck.sort((a, b) => { return a.order - b.order; }); } }
40e00a6b36f5733de19f98fd77c2d661349d7ec9
TypeScript
00zhengfu00/svg-icon
/svg-generator/ast.ts
2.75
3
import { createModifier, factory, NodeFlags, SyntaxKind } from 'typescript'; import kebabCase from 'lodash.kebabcase'; import camelcase from 'camelcase'; interface Base { identifierName: string; iconName: string; } export function createStatement({ identifierName, svgContent, iconName }: Base & { svgContent: string }) { return factory.createVariableStatement( [createModifier(SyntaxKind.ExportKeyword)], factory.createVariableDeclarationList( [ factory.createVariableDeclaration( factory.createIdentifier(identifierName), undefined, undefined, factory.createObjectLiteralExpression( [ factory.createPropertyAssignment( factory.createIdentifier('data'), factory.createNoSubstitutionTemplateLiteral(svgContent) ), factory.createPropertyAssignment( factory.createIdentifier('name'), factory.createStringLiteral(kebabCase(iconName), true) ) ], true ) ) ], NodeFlags.Const ) ); } export function createExportDeclaration({ identifierName, iconName }: Base) { return factory.createExportDeclaration( undefined, undefined, false, factory.createNamedExports([factory.createExportSpecifier( undefined, factory.createIdentifier(identifierName) )]), factory.createStringLiteral(`./${iconName}`, true) ); } export function createImportDeclaration({ identifierName, iconName }: Base) { return factory.createImportDeclaration( undefined, undefined, factory.createImportClause( false, undefined, factory.createNamedImports([factory.createImportSpecifier( undefined, factory.createIdentifier(identifierName) )]) ), factory.createStringLiteral( `./${iconName}`, true ) ); } export function createArrayExport(arrayName: string, identifiers: string[]) { return factory.createVariableStatement( [createModifier(SyntaxKind.ExportKeyword)], factory.createVariableDeclarationList( [factory.createVariableDeclaration( factory.createIdentifier(camelcase(`${arrayName}Icons`)), undefined, undefined, factory.createArrayLiteralExpression( identifiers.map(id => factory.createIdentifier(id)), false ) )], NodeFlags.Const ) ); }
da91e4c0535482664069c88e3964777206eeff07
TypeScript
fkobon/Ivoiro.js
/dist/ivoiro.d.ts
3.1875
3
declare class Ivoiro { propertyGetter: Object; propertyType: String; property: any; /** * Constructeur de la classe prend en paramètre l'object * * @param propertyGetter */ constructor(propertyGetter: Object); /** * Initialisation du composant html servant à gérer les données * * Cette fonction sert principalement à vérifie si le composant html * est récupérer par son id ou sa className ensuite elle récupère * l'élement par le moyen spécifié lors de l'initialisation du composant */ initialyzeProperty(): void; /** * Formattage des valeurs en CFA * * Cette fonction sert principalement à formatter un chiffre * AU format CFA * * @param separator * @param suffix * @param symbole */ formatToCfa(separator: string, suffix?: boolean, symbole?: string): void; /** * cette fonction transforme le chiffre en fonction de sa longeur * * @param number * @param separator */ translateNumber(number: string, separator: string): String; /** * * @param numberArray * @param separator * @param splicer */ translator(numberArray: Array<any>, separator: string, splicer: number): string; /** * Cette fonction génère l'opérateur qui permet de savoir à quel moment * mettre le separateur * * @param i * @param splicer */ translatorSlicer(i: number, splicer: number): number; }
dbbcb61fe8998e339f11d002ee7ff644f70db346
TypeScript
IceFrost925/greedy-snake
/src/modules/Snake.ts
3.25
3
/* * @Description: 蛇 * @Author: WaynePeng * @Date: 2021-08-26 23:14:20 * @LastEditTime: 2021-08-31 02:16:14 * @LastEditors: WaynePeng */ class Snake { head: HTMLElement // 蛇头 body: HTMLCollection // 蛇身-包括蛇头 element: HTMLElement // 蛇容器 isLive: Boolean = true // 是否存活 constructor() { this.element = document.getElementById('snake')! // // 不加!可以改为as HTMLElement this.head = document.querySelector('#snake > div')! this.body = this.element.getElementsByTagName('div')! } // 获取/设置 蛇头坐标 get X() { return this.head.offsetLeft } set X(value: number) { this.head.style.left = `${value}px` } get Y() { return this.head.offsetTop } set Y(value: number) { this.head.style.top = `${value}px` } // 蛇吃食物的 eat() { this.element.insertAdjacentHTML('beforeend', '<div></div>') } // 是否在合法范围内 (0 ~ 400) isRange(x: number, y: number): boolean { if (x >= 0 && x <= 400 && y >= 0 && y <= 400) { return true } else { return false } } // 移动身体位置,从后往前移动否者会丢失前面位置的信息 moveBody() { // i === 0 为头部 for (let i = this.body.length - 1; i > 0; i--) { // 获取前一节身体位置 const X = (this.body[i - 1] as HTMLElement).offsetLeft const Y = (this.body[i - 1] as HTMLElement).offsetTop // 设置当前节点位置 ;(this.body[i] as HTMLElement).style.top = `${Y}px` ;(this.body[i] as HTMLElement).style.left = `${X}px` } } // 头部与身体是否重叠 isOverlap(x: number, y: number): boolean { let result: boolean = false for (let i = 1; i < this.body.length; i++) { const element = this.body[i] if ( (element as HTMLElement).offsetLeft === x && (element as HTMLElement).offsetTop === y ) { result = true break } } return result } } export default Snake
0c4f3d3f2eb49d9885608702d2c3b9f5b8c6d9ba
TypeScript
hinogi/d3
/typescript/arrays/quantile.ts
3.203125
3
// R-7 per <http://en.wikipedia.org/wiki/Quantile> export default function quantile(values: Array<number>, p: number): number { let H: number = (values.length - 1) * p + 1, h: number = Math.floor(H), v: number = +values[h - 1], e: number = H - h; return e ? v + e * (values[h] - v) : v; }
a0bf319f5d6ba97820ae17d549f0cea71c971c91
TypeScript
alexlyul/WebpackCustomDeployPlugin
/src/types.ts
2.875
3
import { Schema } from 'schema-utils/declarations/validate'; export type TFileDeployer = (path: string[], fileContent: string) => Promise<void>; export type TMapping = { entry: string, path: string[], isProduction: boolean, }[]; // schema for config object. export const configSchema:Schema = { type: 'object', properties: { destinationMapping: { instanceof: 'Array', description: 'Array of items with type: {\n' + ' entry: string,\n' + ' path: string[],\n' + ' isProduction: boolean,\n' + '}\n', }, isProductionMode: { type: 'boolean', description: 'If "true" passed - plugin will deploy also files marked as production', }, deployer: { instanceof: 'Function', description: 'Your deployment callback. Should deploy single file to destination, returns a Promise', }, }, additionalProperties: false, }; export const destinationMappingItemSchema:Schema = { instanceof: 'Object', properties: { entry: { type: 'string', description: 'Entry file name', }, path: { instanceof: 'Array', description: 'Example: ["path", "to", "file.js"]', }, isProduction: { type: 'boolean', }, } }
a2c4e3c95bb1a1f5e90fa1bf9dcec1ee5db8fe74
TypeScript
river0825/gitlab-redmine-migrator
/src/App/Infra/MigrateRecordRepo.ts
2.59375
3
import {MigrateRepo} from "../../Migrate/Domain/MigrateRecord/MigrateRepo"; import {IssueInfo} from "../../Migrate/Domain/MigrateRecord/IssueInfo"; import {MigrateRecord, MigrateRecordProp} from "../../Migrate/Domain/MigrateRecord/MigrateRecord"; import * as fs from "fs"; import * as Path from "path"; export class MigrateRecordRepo implements MigrateRepo { get directory(): string { return this._directory; } private _directory: string; constructor(directory?: string) { if (directory) { this._directory = directory; } else { this._directory = process.cwd() + Path.sep + "data" + Path.sep + 'merge_record' } if (!fs.existsSync(this._directory)) { fs.mkdirSync(this._directory, {recursive: true}) } } private getFilePath(issueInfo: IssueInfo): string { const path = this._directory + Path.sep + issueInfo.props.id!.issuer + "_" + issueInfo.props.projectId! + "_" + issueInfo.props.id!.id + ".json"; return path; // return this._directory + Path.sep + issueInfo.props.id!.issuer + "_" + issueInfo.props.projectId! + "_" + issueInfo.props.id!.id + ".json"; } getRecord(fromIssue: IssueInfo): Promise<MigrateRecord> { const self = this; return new Promise<MigrateRecord>((resolve, reject) => { if (!fs.existsSync(this.getFilePath(fromIssue))) { resolve(undefined); return; } fs.readFile(this.getFilePath(fromIssue), (err, data: Buffer) => { if (err) { reject(err); return; } if (!data) { resolve(undefined); return; } const obj = JSON.parse(data.toString()); const props: MigrateRecordProp = { issueInfo: obj._issueInfo, fromIssueId: obj._fromIssueId, toIssueId: obj._toIssueId }; const record = new MigrateRecord(obj._id, props, self); resolve(record) }) }) } save(record: MigrateRecord): Promise<void> { return new Promise<void>((resolve, reject) => { fs.writeFile(this.getFilePath(record.issueInfo), JSON.stringify(record), {}, (err) => { if (err) { reject(err); } else { resolve(); } }) }) } }
158e622e35d34da783870ec2494e757c90feabfa
TypeScript
GretaBerlin/harp.gl
/@here/harp-datasource-protocol/lib/Expr.ts
2.75
3
/* * Copyright (C) 2017-2019 HERE Europe B.V. * Licensed under Apache 2.0, see full license in LICENSE * SPDX-License-Identifier: Apache-2.0 */ import { ExprEvaluator, ExprEvaluatorContext, OperatorDescriptor } from "./ExprEvaluator"; import { ExprParser } from "./ExprParser"; import { ExprPool } from "./ExprPool"; const exprEvaluator = new ExprEvaluator(); export interface ExprVisitor<Result, Context> { visitNullLiteralExpr(expr: NullLiteralExpr, context: Context): Result; visitBooleanLiteralExpr(expr: BooleanLiteralExpr, context: Context): Result; visitNumberLiteralExpr(expr: NumberLiteralExpr, context: Context): Result; visitStringLiteralExpr(expr: StringLiteralExpr, context: Context): Result; visitObjectLiteralExpr(expr: ObjectLiteralExpr, context: Context): Result; visitVarExpr(expr: VarExpr, context: Context): Result; visitHasAttributeExpr(expr: HasAttributeExpr, context: Context): Result; visitContainsExpr(expr: ContainsExpr, context: Context): Result; visitCallExpr(expr: CallExpr, context: Context): Result; visitMatchExpr(expr: MatchExpr, context: Context): Result; visitCaseExpr(expr: CaseExpr, context: Context): Result; } export type JsonExpr = unknown[]; export function isJsonExpr(v: any): v is JsonExpr { return Array.isArray(v) && v.length > 0 && typeof v[0] === "string"; } /** * Abstract class defining a shape of a [[Theme]]'s expression */ export abstract class Expr { /** * Creates an expression from the given `code`. * * @param code The code to parse. * @returns The parsed [[Expr]]. */ static parse(code: string): Expr | never { const parser = new ExprParser(code); const expr = parser.parse(); return expr; } static fromJSON(node: unknown): Expr { if (Array.isArray(node)) { return Expr.parseCall(node); } else if (node === null) { return NullLiteralExpr.instance; } else if (typeof node === "boolean") { return new BooleanLiteralExpr(node); } else if (typeof node === "number") { return new NumberLiteralExpr(node); } else if (typeof node === "string") { return new StringLiteralExpr(node); } throw new Error("failed to create expression"); } private static parseCall(node: any[]): Expr { const op = node[0]; if (typeof op !== "string") { throw new Error("expected a builtin function name"); } switch (op) { case "get": if (typeof node[1] !== "string") { throw new Error(`expected the name of an attribute`); } return new VarExpr(node[1]); case "has": if (typeof node[1] !== "string") { throw new Error(`expected the name of an attribute`); } return new HasAttributeExpr(node[1]); case "in": const elements = node[2]; if (!Array.isArray(elements)) { // tslint:disable-next-line: max-line-length throw new Error( `'${op}' expects an expression followed by an array of literals` ); } elements.forEach(element => { if (typeof element === "object" || typeof element === "function") { throw new Error("expected an array of constant values"); } }); return new ContainsExpr(this.fromJSON(node[1]), elements); case "literal": if (typeof node[1] !== "object") { throw new Error("expected an object or array literal"); } return new ObjectLiteralExpr(node[1]); case "match": { if (node.length < 4) { throw new Error("not enough arguments"); } if (!(node.length % 2)) { throw new Error("fallback is missing in 'match' expression"); } const value = this.fromJSON(node[1]); const conditions: Array<[MatchLabel, Expr]> = []; for (let i = 2; i < node.length - 1; i += 2) { const label = node[i]; if ( !( typeof label === "number" || typeof label === "string" || Array.isArray(label) ) ) { throw new Error(`parse error ${JSON.stringify(label)}`); } const expr = this.fromJSON(node[i + 1]); conditions.push([label, expr]); } const fallback = this.fromJSON(node[node.length - 1]); return new MatchExpr(value, conditions, fallback); } case "case": { if (node.length < 3) { throw new Error("not enough arguments"); } if (node.length % 2) { throw new Error("fallback is missing in 'case' expression"); } const branches: Array<[Expr, Expr]> = []; for (let i = 1; i < node.length - 1; i += 2) { const condition = this.fromJSON(node[i]); const expr = this.fromJSON(node[i + 1]); branches.push([condition, expr]); } const caseFallback = this.fromJSON(node[node.length - 1]); return new CaseExpr(branches, caseFallback); } default: return new CallExpr(op, node.slice(1).map(childExpr => this.fromJSON(childExpr))); } // switch } /** * Evaluate an expression returning a [[Value]] object. * * @param env The [[Env]] used to lookup symbols. * @param cache A cache of previously computed results. */ evaluate(env: Env, cache?: Map<Expr, Value>): Value | never { return this.accept(exprEvaluator, new ExprEvaluatorContext(exprEvaluator, env, cache)); } /** * Create a unique object that is structurally equivalent to this [[Expr]]. * * @param pool The [[ExprPool]] used to create a unique * equivalent object of this [[Expr]]. */ intern(pool: ExprPool): Expr { return pool.add(this); } toJSON(): unknown { return new ExprSerializer().serialize(this); } abstract accept<Result, Context>( visitor: ExprVisitor<Result, Context>, context: Context ): Result; } /** * @hidden */ export type RelationalOp = "<" | ">" | "<=" | ">="; /** * @hidden */ export type EqualityOp = "~=" | "^=" | "$=" | "==" | "!="; /** * @hidden */ export type BinaryOp = RelationalOp | EqualityOp; /** * @hidden */ export type Value = null | boolean | number | string | object; /** * @hidden */ export class Env { /** * Returns property in [[Env]] by name. * * @param name Name of property. */ lookup(_name: string): Value | undefined { return undefined; } /** * Return an object containing all properties of this environment. (Here: empty object). */ unmap(): ValueMap { return {}; } } /** * @hidden */ export interface ValueMap { [name: string]: Value; } /** * Adds access to map specific environment properties. */ export class MapEnv extends Env { constructor(readonly entries: ValueMap, private readonly parent?: Env) { super(); } /** * Returns property in [[Env]] by name. * * @param name Name of property. */ lookup(name: string): Value | undefined { if (this.entries.hasOwnProperty(name)) { const value = this.entries[name]; if (value !== undefined) { return value; } } return this.parent ? this.parent.lookup(name) : undefined; } /** * Return an object containing all properties of this environment, takes care of the parent * object. */ unmap(): ValueMap { const obj: any = this.parent ? this.parent.unmap() : {}; for (const key in this.entries) { if (this.entries.hasOwnProperty(key)) { obj[key] = this.entries[key]; } } return obj; } } /** * Var expression. * @hidden */ export class VarExpr extends Expr { constructor(readonly name: string) { super(); } accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result { return visitor.visitVarExpr(this, context); } } /** * Null literal expression. * @hidden */ export class NullLiteralExpr extends Expr { static instance = new NullLiteralExpr(); protected constructor() { super(); } accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result { return visitor.visitNullLiteralExpr(this, context); } } /** * Boolean literal expression. * @hidden */ export class BooleanLiteralExpr extends Expr { constructor(readonly value: boolean) { super(); } accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result { return visitor.visitBooleanLiteralExpr(this, context); } } /** * Number literal expression. * @hidden */ export class NumberLiteralExpr extends Expr { constructor(readonly value: number) { super(); } accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result { return visitor.visitNumberLiteralExpr(this, context); } } /** * String literal expression. * @hidden */ export class StringLiteralExpr extends Expr { constructor(readonly value: string) { super(); } accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result { return visitor.visitStringLiteralExpr(this, context); } } /** * Object literal expression. * @hidden */ export class ObjectLiteralExpr extends Expr { constructor(readonly value: object) { super(); } get isArrayLiteral() { return Array.isArray(this.value); } accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result { return visitor.visitObjectLiteralExpr(this, context); } } /** * A has expression with an attribute, for example `has(ref)`. * @hidden */ export class HasAttributeExpr extends Expr { constructor(readonly name: string) { super(); } accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result { return visitor.visitHasAttributeExpr(this, context); } } /** * A contains expression. * @hidden */ export class ContainsExpr extends Expr { constructor(readonly value: Expr, readonly elements: Value[]) { super(); } accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result { return visitor.visitContainsExpr(this, context); } } /** * @hidden */ export class CallExpr extends Expr { descriptor?: OperatorDescriptor; constructor(readonly op: string, readonly children: Expr[]) { super(); } accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result { return visitor.visitCallExpr(this, context); } } type MatchLabel = number | string | number[] | string[]; /** * @hidden */ export class MatchExpr extends Expr { constructor( readonly value: Expr, readonly branches: Array<[MatchLabel, Expr]>, readonly fallback: Expr ) { super(); } accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result { return visitor.visitMatchExpr(this, context); } } /** * @hidden */ export class CaseExpr extends Expr { constructor(readonly branches: Array<[Expr, Expr]>, readonly fallback: Expr) { super(); } accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result { return visitor.visitCaseExpr(this, context); } } /** * @hidden */ class ExprSerializer implements ExprVisitor<unknown, void> { serialize(expr: Expr): unknown { return expr.accept(this, undefined); } visitNullLiteralExpr(expr: NullLiteralExpr, context: void): unknown { return null; } visitBooleanLiteralExpr(expr: BooleanLiteralExpr, context: void): unknown { return expr.value; } visitNumberLiteralExpr(expr: NumberLiteralExpr, context: void): unknown { return expr.value; } visitStringLiteralExpr(expr: StringLiteralExpr, context: void): unknown { return expr.value; } visitObjectLiteralExpr(expr: ObjectLiteralExpr, context: void): unknown { return ["literal", expr.value]; } visitVarExpr(expr: VarExpr, context: void): unknown { return ["get", expr.name]; } visitHasAttributeExpr(expr: HasAttributeExpr, context: void): unknown { return ["has", expr.name]; } visitContainsExpr(expr: ContainsExpr, context: void): unknown { return ["in", this.serialize(expr.value), expr.elements]; } visitCallExpr(expr: CallExpr, context: void): unknown { return [expr.op, ...expr.children.map(childExpr => this.serialize(childExpr))]; } visitMatchExpr(expr: MatchExpr, context: void): unknown { const branches: unknown[] = []; for (const [label, body] of expr.branches) { branches.push(label, this.serialize(body)); } return ["match", this.serialize(expr.value), ...branches, this.serialize(expr.fallback)]; } visitCaseExpr(expr: CaseExpr, context: void): unknown { const branches: unknown[] = []; for (const [condition, body] of expr.branches) { branches.push(this.serialize(condition), this.serialize(body)); } return ["case", ...branches, this.serialize(expr.fallback)]; } }
42c3c28d4340a7a74f1936fafdbb23fb596d5f81
TypeScript
aidenwallis/modclient2
/src/core/storage.ts
3.09375
3
export class CoreStorage { private static cache = new Map<string, unknown>(); private static storage = window.localStorage; public static get<T>(key: string, defaultValue: T): T { if (this.cache.has(key)) { return this.cache.get(key) as T; } let serializedValue: string | null = null; try { serializedValue = this.storage.getItem(key); } catch (error) { console.warn("Failed to load value from store", key, error); } if (serializedValue === null || serializedValue === "undefined") { return defaultValue; } try { return JSON.parse(serializedValue) as T; } catch (error) { console.warn( "Failed to deserialize stored value.", { key, value: serializedValue }, error ); this.delete(key); return defaultValue; } } public static getOptional<T>(key: string): T | null { return this.get(key, null); } public static set(key: string, value: {}) { let serializedValue: string; try { serializedValue = JSON.stringify(value); } catch (error) { console.warn("Failed to serialize value to store", { key, value }, error); throw error; } this.cache.set(key, value); try { this.storage.setItem(key, serializedValue); } catch (error) { console.warn( "Failed to save value to storage", { key, value, serializedValue }, error ); } } public static delete(key: string) { this.cache.delete(key); try { this.storage.removeItem(key); } catch (error) { console.warn(`Failed to remove ${key} from storage`, error); } } public static clear() { this.cache.clear(); try { this.storage.clear(); } catch (error) { console.warn("Failed to clear storage", error); } } }
a40b746c472f1168e61557ae424441a422d5bb8e
TypeScript
isxam/shakely
/profiles-processor/src/lib/segment/service/ProfileManagement.ts
2.625
3
import { IDatabaseClient } from '../../db'; interface IProfile { id: string name: string } export default class ProfileManagement { private readonly client: IDatabaseClient; constructor(client: IDatabaseClient) { this.client = client; } async create(profile: IProfile): Promise<void> { const { db } = this.client; await db.insert(profile).into('profile'); } }
641df913d14752c422429cd959296db54e6fb1f2
TypeScript
sachila/react
/src/store/reducer.ts
2.921875
3
import { InitialState } from "./initialState"; import { AppActions, LOAD_CATEGORY, LOAD_CATEGORY_API, UPDATE_CATEGORY, } from "./types"; export const initialState: InitialState = { categories: [], categoriesApiData: [], }; const reducer = ( state: InitialState = initialState, action: AppActions ): InitialState => { switch (action.type) { case UPDATE_CATEGORY: { const categories = [...state.categories]; let category = categories.find((c) => c.id === action.item.id); if (!category) return state; const index = categories.indexOf(category); categories[index] = action.item; return { ...state, categories, }; } case LOAD_CATEGORY: { return { ...state, categories: [...action.items], }; } case LOAD_CATEGORY_API: { return { ...state, categoriesApiData: [...action.items], }; } default: return state; } }; export default reducer;
234c4983b62a34c2b235638810771fc17e95f9b1
TypeScript
bru02/neo-naplo
/src/helpers.ts
2.6875
3
import store from '@/store'; import linkifyHtml from 'linkifyjs/html'; import { getWeek } from './utils/evaluations'; const utc2date = (value: number | Date): Date => { return value instanceof Date ? value : new Date(value * 1000); }, day = (utc: number | Date): String => { return [ 'Vasárnap', 'Hétfő', 'Kedd', 'Szerda', 'Csütörtök', 'Péntek', 'Szombat', ][utc2date(utc).getDay()]; }, leadingZero = (n: number) => { return `0${n}`.slice(-2); }, formatDate = (value: number | Date, appendDay = true): String => { let date = utc2date(value); return `${ date.getFullYear() === new Date().getFullYear() ? '' : `${date.getFullYear()}. ` }${leadingZero(date.getMonth() + 1)}. ${leadingZero(date.getDate())}.${ appendDay ? `, ${day(value)}` : '' }`; }, formatTime = (utc: number): String => { const date = utc2date(utc); return `${leadingZero(date.getHours())}:${leadingZero(date.getMinutes())}`; }; export function isDark(bgColor: string) { const color = bgColor.charAt(0) === '#' ? bgColor.substring(1, 7) : bgColor, r = parseInt(color.substring(0, 2), 16), // hexToR g = parseInt(color.substring(2, 4), 16), // hexToG b = parseInt(color.substring(4, 6), 16), // hexToB uicolors = [r / 255, g / 255, b / 255], c = uicolors.map((col) => { if (col <= 0.03928) { return col / 12.92; } return Math.pow((col + 0.055) / 1.055, 2.4); }); const L = 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]; return L < 0.5; // 179 } export function formatText(text: string) { return linkifyHtml(text, { defaultProtocol: 'https', nl2br: true, }); } export function trimText(text: string) { return text.substr(0, 100) + (text.length > 100 ? '...' : ''); } export function getLessonUrl(date, numberOfLessons) { const getMonday = (utc) => { const d = new Date(utc); const day = d.getDay(), diff = d.getDate() - day + 1; return +new Date(d.setDate(diff)); }; return `/timetable/${Math.round( (getMonday(date * 1000) - getMonday(+new Date())) / 604800000 )}/${date}:${numberOfLessons}`; } export { formatDate, day, utc2date, formatTime }; export async function obtain( what: | 'general' | 'timetable' | 'events' | 'hirdetmenyek' | 'classAverages' | 'exams', w = 0 ) { let resource = store.state.api[what], arg: any; if (what === 'timetable') { arg = getWeek(w); // @ts-ignore resource = store.state.api.timetable[`${arg.from}-${arg.to}`]; } else if (what === 'hirdetmenyek') { arg = await obtain('general').then( (d) => d.osztalyCsoportok.find((o) => o.osztalyCsoportTipus === 'Osztaly').nev ); } if (resource && !resource.loading && resource.loaded) return resource.data; return store.dispatch( `api/pull${what.charAt(0).toUpperCase() + what.slice(1)}`, arg ); }
edbbeea6839017545fc66c745ec4aa9c7a097f78
TypeScript
Lite5h4dow/aleph.js
/framework/react/pageprops.ts
2.578125
3
import { ComponentType } from 'https://esm.sh/react@17.0.2' import { E400MissingComponent } from './components/ErrorBoundary.ts' import { isLikelyReactComponent } from './helper.ts' export type PageProps = { Page: ComponentType<any> | null pageProps: Record<string, any> | null } export function createPageProps(nestedComponents: { specifier: string, Component?: ComponentType<any>, props?: Record<string, any> }[]): PageProps { const pageProps: PageProps = { Page: null, pageProps: null } if (nestedComponents.length > 0) { Object.assign(pageProps, createPagePropsSegment(nestedComponents[0])) } if (nestedComponents.length > 1) { nestedComponents.slice(1).reduce((p, seg) => { const c = createPagePropsSegment(seg) p.pageProps = c return c }, pageProps) } return pageProps } function createPagePropsSegment(seg: { specifier: string, Component?: ComponentType<any>, props?: Record<string, any> }): PageProps { const pageProps: PageProps = { Page: null, pageProps: seg.props || null } if (seg.Component) { if (isLikelyReactComponent(seg.Component)) { pageProps.Page = seg.Component } else { pageProps.Page = E400MissingComponent pageProps.pageProps = { name: 'Page Component: ' + seg.specifier } } } return pageProps }
c801bc4b6c422c5366980af23c21f44420c33a83
TypeScript
nunof07/space-patrol
/src/weapons/pulse/PulseDynamicLevel.ts
2.96875
3
import { Position } from '@src/core/Position'; import { Bullet } from '@src/weapons/Bullet'; import { incWeaponLevel } from '@src/weapons/incWeaponLevel'; import { Pulse } from '@src/weapons/pulse/Pulse'; import { PulseLevel } from '@src/weapons/pulse/PulseLevel'; import { PulseLevel1 } from '@src/weapons/pulse/PulseLevel1'; import { PulseLevel2 } from '@src/weapons/pulse/PulseLevel2'; import { PulseLevel3 } from '@src/weapons/pulse/PulseLevel3'; import { PulseLevel4 } from '@src/weapons/pulse/PulseLevel4'; import { PulseLevel5 } from '@src/weapons/pulse/PulseLevel5'; import { PulseLevel6 } from '@src/weapons/pulse/PulseLevel6'; import { Weapon } from '@src/weapons/Weapon'; import { WeaponLevel } from '@src/weapons/WeaponLevel'; import { weaponNewLevel } from '@src/weapons/weaponNewLevel'; export class PulseDynamicLevel implements PulseLevel, WeaponLevel { private readonly levels: ReadonlyArray<PulseLevel>; private currentLevelImpl: number; constructor(level: number = 1) { this.levels = [ new PulseLevel1(), new PulseLevel2(), new PulseLevel3(), new PulseLevel4(), new PulseLevel5(), new PulseLevel6(), ]; this.currentLevelImpl = weaponNewLevel(level, 1, this.levels.length); } public position(index: number, weapon: Weapon): Position { return this.current().position(index, weapon); } public angle(index: number, weapon: Weapon): number { return this.current().angle(index, weapon); } public incLevel(): boolean { const incremented = this.currentLevelImpl < this.levels.length; this.currentLevelImpl = incWeaponLevel( this.currentLevelImpl, this.levels.length ); return incremented; } public createBullet( scene: Phaser.Scene, weapon: Weapon, index: number, sprite: Phaser.GameObjects.Sprite ): Bullet { const position = this.position(index, weapon); const angle = this.angle(index, weapon); return new Pulse(scene, sprite, position, angle); } public get count(): number { return this.current().count; } public get currentLevel(): number { return this.currentLevelImpl; } public get bulletsCount(): number { return this.count; } public restart(): void { this.currentLevelImpl = 1; } private current(): PulseLevel { return this.levels[this.currentLevelImpl - 1]; } }
b0da16531fe7c30e2659c7195a537fa8397895ca
TypeScript
nerjs/nlogs
/src/__tests__/logger.spec.ts
2.6875
3
import { PassThrough } from 'stream' import { TIME_END, TIME_LOG } from '../constants' import { testStandartLevels } from '../helpers/testHelpers' import { Logger } from '../logger' import { ConsoleOut } from '../utils/console.out' import { StringFormatter } from '../utils/string.formatter' import { AllowedList } from '../utils/allowed.list' describe('Main logger', () => { let logger: Logger let stdout: PassThrough beforeAll(() => { Logger.formatter = new StringFormatter() }) beforeEach(() => { stdout = new PassThrough({ encoding: 'utf-8' }) Logger.outLogs = new ConsoleOut(stdout, stdout) Logger.loggerOptions.debugAllowedList = '*' Logger.debugAllowedList = new AllowedList('*') logger = new Logger() }) it('BaseLogger constructor', () => { const category = 'test category' const logger = new Logger(category) expect(logger.meta.category).toEqual(category) }) testStandartLevels(Logger) describe('counters', () => { it('The count() method should return counter', () => { const label = 'label' const counter = logger.count(label) expect(counter).toEqual(expect.any(Function)) expect(counter.id).toEqual(expect.any(String)) expect(counter.label).toEqual(label) expect(counter.log).toEqual(expect.any(Function)) expect(counter.end).toEqual(expect.any(Function)) expect(counter.data).toBeDefined() }) it('A repeated call to count() should return the same counter', () => { const counter1 = logger.count('label') const counter2 = logger.count('label') expect(counter1).toEqual(counter2) }) it('A repeated call to count() should return different counters after the previous one is finished', () => { const counter1 = logger.count('label') counter1() const counter2 = logger.count('label') expect(counter1).not.toEqual(counter2) }) it('Calling count() again should return different counters if no label is set', () => { const counter1 = logger.count() const counter2 = logger.count() expect(counter1).not.toEqual(counter2) }) it('Data increment after multiple calls', () => { const label = 'label' logger.count(label) const counter = logger.count(label) counter.log() expect(counter.data).toEqual(3) }) }) describe('timers', () => { it('The time() method should return timer', () => { const label = 'label' const timer = logger.time(label) expect(timer).toEqual(expect.any(Function)) expect(timer.id).toEqual(expect.any(String)) expect(timer.label).toEqual(label) expect(timer.log).toEqual(expect.any(Function)) expect(timer.end).toEqual(expect.any(Function)) expect(timer.data).toBeDefined() }) it('Calling time() again should return different timers', () => { const timer1 = logger.time() const timer2 = logger.time() expect(timer1).not.toEqual(timer2) }) it('The timeLog method calls the timer log', () => { const label = 'label' logger.time(label) stdout.read() logger.timeLog(label) const str = stdout.read() expect(str).toMatch(label) expect(str).toMatch(TIME_LOG) }) it('The timeEnd method ends the timer', () => { const label = 'label' logger.time(label) stdout.read() logger.timeEnd(label) const str = stdout.read() expect(str).toMatch(label) expect(str).toMatch(TIME_END) }) }) })
07e02fb6dee326f7ef8feb6c8f70766c11a85599
TypeScript
seoj/seoj.github.io
/snake/src/direction.ts
2.84375
3
import { Point } from "./point"; export enum Direction { up = 1, down = 2, left = 3, right = 4, } export const offsets = { [Direction.up]: new Point(0, -1), [Direction.down]: new Point(0, 1), [Direction.left]: new Point(-1, 0), [Direction.right]: new Point(1, 0), }; export const opposites = { [Direction.up]: Direction.down, [Direction.down]: Direction.up, [Direction.left]: Direction.right, [Direction.right]: Direction.left, }
d6e9d8ae069f77be90425113abfe3907eb3901e5
TypeScript
IkarosKappler/ngdg
/src/esm/DildoMaterials.d.ts
2.96875
3
/** * A collection of materials and material making functions. * * @require THREE * * @author Ikaros Kappler * @date 2021-07-02 * @modified 2021-08-04 Ported to Typescript from vanilla JS. * @version 1.0.1 */ import * as THREE from "three"; export declare const DildoMaterials: { /** * Create a new mesh material from the given parameters. * * @param {boolean} useTextureImage - Load and use the given texture (at `textureImagePath`) if set to true. * @param {boolean} wireframe - Create a wireframe material if true. * @param {string} textureImagePath - The texture path to use (if useTextureImage is set to true). * @param {THREE.DoubleSide|THREE.FrontSide|THREE.Backside} doubleSingleSide - Wether to display one one or both face sides. * @returns */ createMainMaterial: (useTextureImage: boolean, wireframe: boolean, textureImagePath: string, doubleSingleSide: number) => THREE.Material; createSliceMaterial: (useTextureImage: boolean, wireframe: boolean, textureImagePath: string) => THREE.Material; /** * Load a texture or get it from the internal buffer if it was already loaded before. * * @param {string} path - The path (absolute or relative) to the texture image to load. * @returns {THREE.Texture} */ loadTextureImage: (path: string) => THREE.Texture; };
0e61357f6cabea46f5c932ae27e20f72be06752c
TypeScript
MihaiGaidau/dream-trip-ui
/src/app/core/models/pageable.model.ts
2.828125
3
export class Pageable { public pageNumber = 0; public pageSize = 20; public numberOfElements = 1; public totalElements = 20; public first = true; public last = true; constructor(pageNumber?: number, pageSize?: number, numberOfElements?: number, totalElements?: number, first?: boolean, last?: boolean) { this.pageNumber = pageNumber; this.pageSize = pageSize; this.numberOfElements = numberOfElements; this.totalElements = totalElements; this.first = first; this.last = last; } }
f108bc965f7145f7fc6df8a89d404fd60849a134
TypeScript
uxland/uxl-routing
/src/helpers/get-only-url.ts
2.59375
3
import {isPushStateAvailable} from "./is-push-state-available"; export const getOnlyUrl = (url: string, useHash: boolean = false, hash: string = '#') =>{ let onlyURL = url, split; let cleanGETParam = str => str.split(/\?(.*)?$/)[0]; if (typeof hash === 'undefined') { // To preserve BC hash = '#'; } if (isPushStateAvailable() && !useHash) { onlyURL = cleanGETParam(url).split(hash)[0]; } else { split = url.split(hash); onlyURL = split.length > 1 ? cleanGETParam(split[1]) : cleanGETParam(split[0]); } return onlyURL; };
5ebe8870cc4a4a434e9b1d668f55d4fb81bb564e
TypeScript
PauloHSOliveira/estudos-ts
/src/AULA10-type-unknown/AULA10.ts
2.703125
3
let x: unknown x = 2 x = 'teste' x = false x = 1000 const y = 10 if (typeof x === 'number') console.log(x + y)
f61807786f8f43399419ef7e0eb0c5973e464ebc
TypeScript
JamilsonMello/gobarber
/backend/src/shared/container/providers/EmailProvider/fakes/FakeEmailProvider.ts
2.53125
3
import IEmailProvider from '../models/IEmailProvider'; import ISendMailDTO from '../dtos/ISendMailDTO'; class FakeEmailProvider implements IEmailProvider { private emailReceived: ISendMailDTO[] = []; public async sendEmail(message: ISendMailDTO): Promise<void> { this.emailReceived.push(message); } } export default FakeEmailProvider;
f3191d251a5fc156f2277e349790a134e380fd07
TypeScript
DanielSLucas/RPBackend
/src/modules/users/services/DeleteUserService.spec.ts
2.53125
3
import AppError from '../../../shared/errors/AppError'; import { UsersRoles } from '../infra/typeorm/entities/User'; import FakeHashProvider from '../providers/hashProvider/fakes/FakeHashProvider'; import FakeUsersRepository from '../repositories/fakes/FakeUsersRepository'; import CreateUserService from './CreateUserService'; import DeleteUserService from './DeleteUserService'; import ListUsersService from './ListUsersService'; let fakeUsersRepository: FakeUsersRepository; let deleteUser: DeleteUserService; describe('DeleteUser', () => { beforeEach(() => { fakeUsersRepository = new FakeUsersRepository(); deleteUser = new DeleteUserService(fakeUsersRepository); }); it('should be able to delete a specified user', async () => { const fakeHashProvider = new FakeHashProvider(); const listUsers = new ListUsersService(fakeUsersRepository); const createUser = new CreateUserService( fakeUsersRepository, fakeHashProvider, ); const user1 = await createUser.execute({ name: 'Daniel Lucas', email: 'daniellucas-pms@hotmail.com', password: '123456', whatsapp: '12981025796', role: UsersRoles.ADM, }); const user2 = await createUser.execute({ name: 'Lucas', email: 'lucas-pms@hotmail.com', password: '123456', whatsapp: '12981025796', role: UsersRoles.ADM, }); await deleteUser.execute(user1.id); const users = await listUsers.execute(); expect(users).toEqual([user2]); }); it('should not be able to delete a nonexistent user', async () => { await expect(deleteUser.execute('a-nonexistent-user-id')).rejects.toEqual( new AppError('User not found', 404), ); }); });
65e630a000f0d6ef13a369aced474d0c2b09b0f1
TypeScript
jchai28/jchai28.github.io
/index.ts
2.859375
3
//////// HELPING FUNCTIONS function randomBusinessName(): string { var adjectives: Array<string> = ["Blue", "Red", "Green", "Purple", "Orange", "White", "Trusty", "Speedy", "Enigmatic", "Fly", "Golden", "Sturdy", "Graceful", "Rapid", "Robust", "American", "British", "Asian", "European", "Indian", "Italian", "Australian", "Chinese", "Russian", "Nordic", "Southern", "Northern", "Southwest", "Express", "Paper", "Malaysia", "Thai"] var nouns: Array<string> = ["Planes", "Airways", "Skies", "Air", "Airlines", "Flyers", "Jets", "Pilots", "Air Transport", "Helicopters", "Cargo"] var name: string = `${randomChoice(adjectives)} ${randomChoice(nouns)}` if (Math.random() < 0.3) { var name = randomChoice(adjectives) + ' ' + name } return name } function randomPlaneName(): string { var name = ["Boeing 737-800","Boeing 737-900","Boeing 737 Max 9","Boeing 747","Boeing 757","Boeing 767","Boeing 777","Boeing 777-200","Boeing 777X","Boeing 777-300","Boeing 787 Dreamliner","Airbus A320","Airbus A330","Airbus A350","Airbus A360"] return ` ${randomChoice(name)}` } function prettyCashString(cash: number): string { return "$" + cash.toLocaleString("en-gb", { maximumFractionDigits: 0, currency: "usd" }) } function randomChoice(things: Array<any>): any { return things[Math.floor(Math.random() * things.length)]; } function displayInfo(message: string): void { var div = <HTMLElement>document.getElementById("info") var span = document.createElement("span") span.classList.add("fade-in") span.innerHTML = message setTimeout(() => { span.classList.add("fade-out") setTimeout(() => { span.remove() }, 1000) }, 5000) div.appendChild(span) } function displayError(message: string): void { var div = <HTMLElement>document.getElementById("error") var span = document.createElement("span") span.classList.add("fade-in") span.innerHTML = message setTimeout(() => { span.classList.add("fade-out") setTimeout(() => { span.remove() }, 1000) }, 5000) div.appendChild(span) } function dataLabels(rows: Array<Array<string>>): HTMLDListElement { var elem = document.createElement("dl") rows.forEach(r => { var dt = document.createElement("dt") dt.innerHTML = r[0] var dd = document.createElement("dd") dd.innerHTML = r[1] elem.appendChild(dt) elem.appendChild(dd) }) return elem } function listLabels(rows: Array<Array<String>>): HTMLElement { var elem = document.createElement("ul") rows.forEach(r => { var li = document.createElement("li") li.innerHTML = `<strong>${r[0]}:</strong>${r[1]}` elem.appendChild(li) }) return elem } function createElement(elementType: string, elementId?: string, className?: string, innerText?: string) { var e = document.createElement(elementType) if (elementId) { e.setAttribute("id", elementId) } if (className) { e.setAttribute("class", className) } if (innerText) { e.innerText = innerText } return e } function createTitle(text: string, elementType: string = "h1"): HTMLElement { var h = document.createElement(elementType) h.innerHTML = text return h } function createParagraph(text: string): HTMLParagraphElement { var p = document.createElement("p") p.innerText = text return p } function hideElement(elem: HTMLElement): void { elem.style.display = 'none' } function getDistanceFromLatLonInKm(lat1: number, lon1: number, lat2: number, lon2: number): number { function deg2rad(deg: number): number { return deg * (Math.PI / 180) } var R = 6371; // Radius of the earth in km var dLat = deg2rad(lat2 - lat1); // deg2rad below var dLon = deg2rad(lon2 - lon1); var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2) ; var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; // Distance in km return d; } //////// OUR TYPES & CLASSES (THINGS) type AirportCode = string class Airport { code: AirportCode name: string country: string lat: number lon: number popularity: number constructor(code: AirportCode, name: string, country: string, lat: number, lon: number, popularity: number = 0) { this.code = code this.name = name this.country = country this.lat = lat this.lon = lon this.popularity = popularity } cardHtml(): HTMLElement { return dataLabels([ ["IATA code", this.code], ["Country", this.country], ["Popularity", String(this.popularity)], ]) } } class Route { identifier: string fromAirport: Airport toAirport: Airport popularity: number purchaseCost: number lastRunAt?: Date lastResultedAt?: Date nextAvailableAt?: Date plane?: Plane constructor(fromAirport: Airport, toAirport: Airport) { this.identifier = [fromAirport.code, toAirport.code].sort().join("-") this.fromAirport = fromAirport this.toAirport = toAirport this.popularity = 10 + Math.floor(Math.random() * 90) this.purchaseCost = 100 * this.popularity + Math.ceil(Math.random() * 1000) } distance(): number { return getDistanceFromLatLonInKm(this.fromAirport.lat, this.fromAirport.lon, this.toAirport.lat, this.toAirport.lon) } flightDuration(): number { return this.distance() / 20 } timeRemaining(): number { var now = new Date() if (this.lastRunAt) { var secondsSinceLastRun = (+now - +this.lastRunAt) / 1000 var runTimeSeconds = this.flightDuration() return Math.max(0, Math.floor((runTimeSeconds - secondsSinceLastRun))) } return 0 } canRun(): boolean { var plane = null gameEngine.airline?.planes.forEach(p => { if (!p.flying && p.maxDistance >= this.distance()) { plane = p console.log("picked plane",plane,this) } else { console.log("could not pick plane",p,p.flying,this) } }) if (plane) { if (this.timeRemaining() <= 0) { plane = <Plane>plane plane.flying = true this.plane = plane return true } else { return false } } displayError("No planes available to run route, go to the Fleet tab") return false } run(): boolean { if (!this.canRun()) { return false } console.log("running route", this.lastRunAt, this.timeRemaining()) this.lastRunAt = new Date() this.nextAvailableAt = new Date(new Date().getTime() + 60000 + 1000 * this.flightDuration()) var airline = <Airline>gameEngine.airline airline.updateStats() airline.getRoutesDisplay() return true } getResults() { this.lastResultedAt = new Date() var numPassengers = this.dailyPassengers() var income = 10 * numPassengers var cost = 500 + Math.ceil(Math.random() * 500) var profit = income - cost displayInfo(`Route running with ${numPassengers} passengers earning ${prettyCashString(profit)} profit`) var airline = <Airline>gameEngine.airline airline.cash += profit var eventCost = 0 var healthCost = 1 var popularityChange = 1 var incidentText, infoText = null if (Math.random() < 0.1) { eventCost = 2000 + Math.ceil(Math.random() * 2000) popularityChange = 5 incidentText = `Engine fire costing ${prettyCashString(eventCost)} and ${popularityChange} reputation` infoText = "There was an engine fire! See Accidents tab for details" healthCost = 80 } else if (Math.random() < 0.1) { eventCost = 100 + Math.ceil(Math.random() * 200) popularityChange = 1 incidentText = `Smoke in cabin ${prettyCashString(eventCost)} and ${popularityChange} reputation` infoText = "Smoke in cabin! See Accidents tab for details" healthCost = 80 } (<Plane>this.plane).health -= healthCost airline.cash -= eventCost; (<Plane>this.plane).flying = false this.plane = undefined airline.changePopularity( popularityChange) airline.updateStats() if (infoText) { displayInfo(infoText) } if (incidentText) { airline.incidents.push(`${new Date()} ${incidentText}`) } airline.getRoutesDisplay() } dailyPassengers(): number { return Math.ceil(this.popularity * (10 + Math.random() * 10)) } buttonHtml(): HTMLButtonElement { var btn = document.createElement("button") btn.setAttribute("style", "background-color:#ddcc44aa") btn.appendChild(this.cardHtml()) btn.addEventListener("click", () => { var airline = <Airline>gameEngine.airline if (airline.cash < this.purchaseCost) { displayError("You cannot afford this route!") } else { airline.routes.push(this) airline.cash -= this.purchaseCost airline.transactions.push(`${new Date()} $${airline.cash} Purchased route ${this.identifier} for ${prettyCashString(this.purchaseCost)}`) displayInfo("Route purchased!") gameEngine.displayRoutesTab() airline.updateStats() } }) return btn } purchasedCardHtml(): HTMLDivElement { var div = document.createElement("div") div.className = "bg-light border-box" div.appendChild(this.cardHtml()) var runbutton = document.createElement("button") var collectbutton = document.createElement("button") runbutton.innerHTML = "Run Route" runbutton.addEventListener("click", () => { if (this.run()) { runbutton.setAttribute("disabled", "") runbutton.innerHTML = `Current route running, ready in ${this.timeRemaining()} seconds ${this.plane?.name}` } }) collectbutton.addEventListener("click", () => { this.getResults() }) const updatebutton = () => { if (this.timeRemaining() === 0) { if (!this.lastRunAt || this.lastResultedAt && this.lastResultedAt > this.lastRunAt) { collectbutton.setAttribute("disabled", "") hideElement(collectbutton) if (this.nextAvailableAt && new Date() < this.nextAvailableAt) { runbutton.innerHTML = "Plane is Refueling, Cleaning, Unloading. Ready in 1 minute" } else { runbutton.innerHTML = "Run Route" runbutton.removeAttribute("disabled") } } else { collectbutton.style.display = "inherit" collectbutton.innerHTML = "Show Results" collectbutton.removeAttribute("disabled") } } else { runbutton.setAttribute("disabled", "") collectbutton.setAttribute("disabled", "") hideElement(collectbutton) runbutton.innerHTML = `Current route running, ready in ${this.timeRemaining()} seconds ${this.plane?.name}` } } setInterval(updatebutton, 1000) updatebutton() div.appendChild(runbutton) div.appendChild(collectbutton) return div } cardHtml(): HTMLElement { var dl = dataLabels([ ["Distance", `${this.distance().toLocaleString("en-gb", { maximumFractionDigits: 0 })}km`], ["Popularity", this.popularity.toLocaleString("en-gb")], ["Cost", `$${this.purchaseCost.toLocaleString("en-gb")}`], ]) var card = document.createElement("div") card.className = "flex flex-column justify-content-between" card.innerHTML = `<h3>${this.fromAirport.code} <-> ${this.toAirport.code}</h3>` card.appendChild(dl) var footer = document.createElement("div") var fromAirport = document.createElement("h5") fromAirport.innerHTML = this.fromAirport.name footer.appendChild(fromAirport) footer.appendChild(document.createElement("hr")) var toAirport = document.createElement("h5") toAirport.innerHTML = this.toAirport.name footer.appendChild(toAirport) card.appendChild(footer) return card } } class Plane { name: string id: number flying: boolean = false health: number = 100 maxDistance: number = Math.floor(500 + Math.random() * 15000) cost: number = 100000 + this.maxDistance constructor(name: string, id: number) { this.name = name this.id = id } purchasedCardHtml(): HTMLElement { var div = document.createElement("div") div.className = "bg-light border-box" var dl = dataLabels([ ["Name", `${this.name}`], ["Flying", `${this.flying}`], ["Maxdistance", `${this.maxDistance}`], ["health", this.health.toLocaleString("en-gb")], ]) var card = document.createElement("div") card.innerHTML = `<h3>${this.name} </h3>` card.appendChild(dl) div.appendChild(card) var status if (!this.flying && this.health >= 30) { status = "Available" } else if (this.flying) { status = "inflight" } else { status = "maintenance" card.appendChild(this.maintenanceHtml()) } card.className = `flex flex-column justify-content-between ${status}` card.appendChild(createParagraph(status)) return div } displayHtml(): HTMLElement { var div = document.createElement("div") div.className = "flex" div.appendChild(dataLabels([ ["id", String(this.id)], ["name", this.name], ["health", String(this.health)], ["maxDistance", String(this.maxDistance)], ])) return div } maintenanceHtml(): HTMLElement { var div = this.displayHtml() var btn = document.createElement("button") btn.innerText = "Fix for $100,000" div.appendChild(btn) btn.addEventListener("click", () => { var airline = <Airline>gameEngine.airline if (airline.cash < 100000) { displayError("You cannot afford this fix!") return } airline.cash -= 100000 this.health = 100 airline.transactions.push(`${new Date()} $100,000 Fixed plane ${this.id}`) displayInfo("Plane fixed!") gameEngine.displayFleetTab() airline.updateStats() }) var btn = document.createElement("button") btn.innerText = "Sell to Mojave scrapyard for $10,000" div.appendChild(btn) btn.addEventListener("click", () => { var airline = <Airline>gameEngine.airline airline.cash += 10000 airline.transactions.push(`${new Date()} +$10,000 Sold plane ${this.id} to scrapyard`) displayInfo("Plane sold!") airline.planes = airline.planes.filter(p => p.id !== this.id) gameEngine.displayFleetTab() airline.updateStats() }) return div } } function newPlane(existingPlanes: number): Plane { return new Plane(randomPlaneName(), existingPlanes + 1) } class Airline { name: string hub: Airport joined: Date cash: number = 1000000 planes: Array<Plane> = [] routes: Array<Route> = [] popularity: number = 50 transactions: Array<string> = [] incidents: Array<string> = [] constructor(name: string, hub: Airport) { this.name = name this.hub = hub this.joined = new Date() } changePopularity(amount: number): void { this.popularity += amount if (this.popularity <= 0) { gameEngine.gameOver() } } updateTitle(): void { var div = <HTMLElement>document.getElementById("airlineTitle") div.appendChild(this.titleHtml()) } updateStats(): void { const placeholder = <HTMLElement>document.getElementById("airlineStats") placeholder.innerHTML = "" placeholder.appendChild(this.statsHtml()) } sparePlanes(): number { return this.planes.length - this.routes.length } titleHtml(): HTMLElement { return createTitle( `${this.name}<strong>Hub: ${this.hub.code}</strong> <strong> Joined: ${this.joined.toLocaleDateString()} </strong>`, "h2", ) } statsHtml(): HTMLElement { var dl = dataLabels([ ["Cash", prettyCashString(this.cash)], ["Planes", String(this.planes.length)], ["Routes", String(this.routes.length)], ["Popularity", String(this.popularity)], ]) return dl } getFleetDisplay(): HTMLElement { var div = document.createElement("div") div.appendChild(createTitle("Your Fleet")) var planesContainer = document.createElement("div") this.planes.forEach(plane => { planesContainer.appendChild(plane.purchasedCardHtml()) }) div.appendChild(planesContainer) div.appendChild(createParagraph(`You have ${this.planes.length} planes in your fleet`)) var button = document.createElement("button") button.setAttribute("style", "margin: 0.5rem") var plane = newPlane(this.planes.length) const airplaneCost = plane.cost div.appendChild(createParagraph(`You can buy another plane for ${prettyCashString(airplaneCost)}`)) button.innerHTML = `Buy plane for ${prettyCashString(airplaneCost).toLocaleString()}` button.addEventListener("click", () => { if (this.cash >= airplaneCost) { this.cash -= airplaneCost this.transactions.push(`${new Date()} ${prettyCashString(this.cash)} Purchased plane for ${prettyCashString(airplaneCost)}`) this.planes.push(plane) this.updateStats() gameEngine.displayFleetTab() } else { displayError("You don't have enough cash to afford that plane!") } }) div.appendChild( button) return div } getRoutesDisplay(): HTMLElement { var div = document.createElement("div") div.appendChild(createTitle("Your Routes")) var routesContainer = document.createElement("div") this.routes.forEach(route => { routesContainer.appendChild(route.purchasedCardHtml()) }) div.appendChild(routesContainer) return div } getReputationDisplay(): HTMLElement { var div = document.createElement("div") var heading = document.createElement("h2") heading.innerHTML = "Reputation and Reviews" div.appendChild(heading) var p = document.createElement("p") var numStars = 0 if (this.popularity > 79) { p.innerText = `Customers favorite airline in ${this.hub.country}!` numStars = 5 } else if (this.popularity > 49) { p.innerText = `Customers secound favorite choice` numStars = 3 } else { p.innerText = `Customers least favorite choice` numStars = 1 } for (var i = 0; i < 5; i++) { var span = document.createElement("span") span.className = "fa fa-star" if (i < numStars) { span.classList.add("checked") } div.appendChild(span) } div.appendChild(p) return div } getFinanceDisplay(): HTMLElement { var div = document.createElement("div") var heading = document.createElement("h3") heading.innerHTML = "Finances" div.appendChild(heading) this.transactions.forEach(t => { div.appendChild(createParagraph(t)) }) return div } getAccidentsDisplay(): HTMLElement { var div = document.createElement("div") var heading = document.createElement("h2") heading.innerHTML = "Accidents" div.appendChild(heading) this.incidents.forEach(t => { div.appendChild(createParagraph(t)) }) return div } } function getAirports(): Array<Airport> { return [ // Europe new Airport("LHR", "London Heathrow", "United Kingdom", 51.4775, -0.461388, 80.1), new Airport("CDG", "Charles de Gaulle Airport", "France", 49.009722, 2.547778, 69.5), new Airport("FRA", "Frankfurt International Airport", "Germany", 50.0379, 8.5622, 71.0), // North America new Airport("JFK", "John F. Kennedy Airport", "USA", 40.6413, 73.7781, 71.9), new Airport("IAD", "Washington Dulles International Airport", "USA", 38.9531, 77.4565, 51.9), // South America // Asia new Airport("KUL", "Kuala Lumpur International Airport", "Malaysia", 2.743333, 101.698056, 60.0), new Airport("HKG", "Hong Kong International Airport", "Hong Kong", 22.308889, 113.914444, 71.4), new Airport("BKK", "Suvarnabhumi International Airport", "Thailand", 13.6900, 100.7501, 65.4), new Airport("SIN", "Changi International Airport", "Singapore", 1.3644, 103.9915, 91.0), // Africa new Airport("CPT", "Cape Town International Airport", "South Africa", 33.9715, 18.6021, 56.5), // Middle East new Airport("DXB", "Dubai International Airport", "UAE", 25.2532, 55.3657, 91.2), ] } function createAirline(businessName: string, hub: Airport): Airline { var airline = new Airline(businessName, hub) displayInfo(businessName + " joins the aviation industry!") return airline } class GameEngine { airline?: Airline airports: Array<Airport> = [] routes: Array<Route> = [] days: number = 0 today: Date = new Date() constructor() { this.loadAirports() this.loadRoutes() } registerAirline(airline: Airline): void { this.airline = airline displayInfo("Please Choose your new route.") this.displayRoutesTab() } progressDay(): void { this.days += 1 this.today.setDate(this.today.getDate() + 1); } loadAirports(): Array<Airport> { if (this.airports.length === 0) { this.airports = getAirports() } return this.airports } loadRoutes(): Array<Route> { if (this.routes.length === 0) { var routes: Array<Route> = [] this.airports.forEach(a => { this.airports.forEach(b => { if (a.code < b.code) { routes.push(new Route(a, b)) } }) }) this.routes = routes } return this.routes } displaySummaryTab(): void { const main = <HTMLElement>document.getElementById("main") main.innerHTML = "" var airline = <Airline>this.airline var heading = createTitle(airline.name) main.appendChild(heading) main.appendChild(airline.getReputationDisplay()) main.appendChild(airline.getAccidentsDisplay()) } displayFleetTab(): void { const main = <HTMLElement>document.getElementById("main") main.innerHTML = "" var airline = <Airline>this.airline main.appendChild(airline.getFleetDisplay()) } displayRoutesTab(): void { const main = <HTMLElement>document.getElementById("main") main.innerHTML = "" var airline = <Airline>this.airline main.appendChild(airline.getRoutesDisplay()) main.appendChild(createTitle("Routes Available For Purchase")) var div = document.createElement("div") var unpurchasedRoutes = this.routes.filter(r => !this.airline?.routes.some(airlineRoute => airlineRoute.identifier === r.identifier)) var routesForHub = unpurchasedRoutes.filter(r => r.fromAirport === this.airline?.hub || r.toAirport === this.airline?.hub) var routesToDisplay = routesForHub.sort((a, b) => a.distance() - b.distance()).slice(0,3) routesToDisplay.forEach(r => div.appendChild(r.buttonHtml())) main.appendChild(div) } displayReputationTab(): void { const main = <HTMLElement>document.getElementById("main") main.innerHTML = "" var airline = <Airline>this.airline main.appendChild(airline.getReputationDisplay()) } displayFinanceTab(): void { const main = <HTMLElement>document.getElementById("main") main.innerHTML = "" var airline = <Airline>this.airline main.appendChild(airline.getFinanceDisplay()) } displayAccidentsTab(): void { const main = <HTMLElement>document.getElementById("main") main.innerHTML = "" var airline = <Airline>this.airline main.appendChild(airline.getAccidentsDisplay()) } getAirport(code: string): Airport | void { var airport; this.airports.forEach(a => { if (a.code === code) { airport = a } }) return airport } showAirports(): void { const main = <HTMLElement>document.getElementById("main") this.airports.forEach((a) => { main.appendChild(a.cardHtml()) }) } showRoutes(): void { const main = <HTMLElement>document.getElementById("main") this.routes.forEach(r => { main.appendChild(r.cardHtml()) }) } gameOver(): void { const main = <HTMLElement>document.getElementById("main") main.innerHTML = "<h1 style='color:red;'>GAMEOVER</h1>" } createSideMenu(): void { var sideMenu = <HTMLElement>document.getElementById("sidemenu") var companyBtn = createElement("button", "viewCompany", "flex-grow", `Overview of ${(<Airline>this.airline).name}`) var fleetBtn = createElement("button", "viewFleet", "flex-grow", `Overview of Fleet`) var routesBtn = createElement("button", "viewRoutes", "flex-grow", `Overview of Routes`) var reputationBtn = createElement("button", "viewReputation", "flex-grow", `Overview of Reputation`) var financeBtn = createElement("button", "viewFinance", "flex-grow", `Overview of Finance`) var accidentsBtn = createElement("button", "viewAccidents", "flex-grow", `Overview of Accidents`) const main = <HTMLElement>document.getElementById("main") companyBtn.addEventListener("click", () => gameEngine.displaySummaryTab()) fleetBtn.addEventListener("click", () => gameEngine.displayFleetTab()) routesBtn.addEventListener("click", () => gameEngine.displayRoutesTab()) reputationBtn.addEventListener("click", () => gameEngine.displayReputationTab()) financeBtn.addEventListener("click", () => gameEngine.displayFinanceTab()) accidentsBtn.addEventListener("click", () => gameEngine.displayAccidentsTab()) sideMenu.appendChild(companyBtn) sideMenu.appendChild(fleetBtn) sideMenu.appendChild(routesBtn) sideMenu.appendChild(reputationBtn) sideMenu.appendChild(financeBtn) sideMenu.appendChild(accidentsBtn) } } //////// SETUP var gameEngine: GameEngine = new GameEngine() window.onload = () => { // Creating form to enter business name and to choose hub const form = <HTMLFormElement>document.getElementById("playForm") var nameRow = document.createElement("div") var nameLabel = document.createElement("label") nameLabel.setAttribute("for", "businessName") nameLabel.textContent = "What is your airline called?" var nameInput: HTMLInputElement = document.createElement("input") nameInput.setAttribute("type", "text") nameInput.setAttribute("name", "businessName") nameInput.setAttribute("required", "") nameRow.appendChild(nameLabel) nameRow.appendChild(nameInput) // choose hub var hubRow = document.createElement("div") var hubLabel = document.createElement("label") hubLabel.setAttribute("for", "hub") hubLabel.textContent = "Choose your hub" var hubSelect = <HTMLSelectElement>document.createElement("select") hubSelect.setAttribute("name", "hub") gameEngine.airports.map((airport) => { var opt = document.createElement("option") opt.setAttribute("value", airport.code) opt.textContent = `${airport.name} (${airport.code})` hubSelect.appendChild(opt) return opt }) hubRow.appendChild(hubLabel) hubRow.appendChild(hubSelect) var playBtn = document.createElement("button") playBtn.setAttribute("type", "submit") playBtn.textContent = "Play Now" playBtn.className = "primary" form.innerHTML = "" form.appendChild(nameRow) form.appendChild(hubRow) form.appendChild(playBtn) nameInput.setAttribute("value", randomBusinessName()) form.addEventListener("submit", (e) => { e.preventDefault() hideElement(form) var hub = <Airport>gameEngine.getAirport(hubSelect.value) var airline = createAirline(nameInput.value, hub) gameEngine.registerAirline(airline) const header = document.getElementsByTagName("header")[0] header?.classList.remove("justify-content-center") header?.classList.remove("flex-column") header?.classList.add("justify-content-between") gameEngine.createSideMenu() airline.updateTitle() airline.updateStats() }) }