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
|
|---|---|---|---|---|---|---|
d48825b212d8b1215538e4cb81f05ead0c314ec7
|
TypeScript
|
lakexyde/tabris-js
|
/examples/typescript-weather-app/src/forecastOverview.ts
| 2.65625
| 3
|
import {Composite, CompositeProperties, TextView} from 'tabris';
import {omit} from './util';
import {WeatherData, WeatherDatum} from './weatherService';
const TEXT_COLOR = 'rgb(255, 255, 255)';
const MIN_TEMP_COLOR = 'rgb(245, 245, 255)';
const INFO_BOX_COLOR = 'rgba(0, 0, 0, 0.2)';
const MARGIN = 5;
const INNER_MARGIN = 6;
const DAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const SMALL_FONT = 'thin 19px sans-serif';
const BIG_FONT = 'thin 28px sans-serif';
const SMALL_FONT_ITALIC = 'italic thin 22px sans-serif';
interface ForecastOverviewProperties extends CompositeProperties {
weatherData: WeatherData;
}
export default class ForecastOverview extends Composite {
private days: WeatherDatum[][];
constructor(properties: ForecastOverviewProperties) {
super(omit(properties, 'data'));
this.days = properties.weatherData.days;
for (let index = 0; index < this.days.length; index++) {
this.createDayInformationBox(index).appendTo(this);
}
}
private createDayInformationBox(dayIndex: number) {
let dayForecasts = this.days[dayIndex];
let container = new Composite({
top: this.children().length === 0 ? 0 : 'prev()',
left: MARGIN,
right: MARGIN,
});
let infoBox = new Composite({
top: MARGIN,
left: MARGIN,
right: MARGIN,
background: INFO_BOX_COLOR,
highlightOnTouch: true
}).on({
tap: () => this.trigger('daySelect', {dayIndex})
}).appendTo(container);
let minTemp = Math.min(...dayForecasts.map((forecast) => forecast.temperature));
let maxTemp = Math.max(...dayForecasts.map((forecast) => forecast.temperature));
this.createDayText(dayForecasts[0]).appendTo(infoBox);
this.createWeatherText(WeatherData.getAverageWeatherDescription(dayForecasts)).appendTo(infoBox);
this.createTemperatureRangeText(maxTemp, minTemp).appendTo(infoBox);
return container;
}
private createDayText(forecast: WeatherDatum) {
return new TextView({
top: INNER_MARGIN,
bottom: INNER_MARGIN,
left: INNER_MARGIN,
text: DAY_NAMES[forecast.date.getDay()],
textColor: TEXT_COLOR,
font: BIG_FONT
});
}
private createTemperatureRangeText(maxTemp: number, minTemp: number) {
let container = new Composite({right: MARGIN, centerY: 0});
let maxTempText = new TextView({
text: Math.round(maxTemp) + '°C /',
textColor: TEXT_COLOR,
font: BIG_FONT
}).appendTo(container);
new TextView({
left: 'prev()',
text: Math.round(minTemp) + '°C',
textColor: MIN_TEMP_COLOR,
baseline: maxTempText,
font: SMALL_FONT
}).appendTo(container);
return container;
}
private createWeatherText(text: string) {
return new TextView({
left: 'prev() 8', centerY: 0,
text,
textColor: TEXT_COLOR,
font: SMALL_FONT_ITALIC
});
}
}
|
3e498cfbfe148872670d99ba2832afa1e2837961
|
TypeScript
|
alejandrade/ScrumPointer
|
/src/app/model/story.ts
| 2.640625
| 3
|
export class Story {
public score: number;
public storyName: string;
public id: string;
public consensus: boolean;
constructor(id: string) {
this.score = 0;
this.storyName = '';
this.id = id;
this.consensus = false;
}
}
|
9e0742a51fc0f619b95ff683b66c6ca3b3aeb830
|
TypeScript
|
citelao/hit_list_api
|
/src/util/WebArchive.ts
| 2.703125
| 3
|
import plist from "simple-plist";
interface IWebArchive {
WebMainResource: {
WebResourceData: Array<number>;
WebResourceFrameName: string;
WebResourceMIMEType: string;
WebResourceTextEncodingName: string;
WebResourceURL: string;
}
}
function parseWebArchiveEncoding(encoding: string): BufferEncoding {
if (encoding === "UTF-8") {
return "utf-8";
}
throw new Error(`Unknown encoding '${encoding}'`);
}
export default class WebArchive {
private readonly data: IWebArchive;
private readonly buffer: Buffer;
constructor(blob: Buffer) {
this.data = plist.parse(blob) as IWebArchive;
// console.log(JSON.stringify(this.data));
this.buffer = Buffer.from(this.data.WebMainResource.WebResourceData);
}
public get html(): string {
console.log(this.buffer.toString(parseWebArchiveEncoding(this.data.WebMainResource.WebResourceTextEncodingName)));
return this.buffer.toString(parseWebArchiveEncoding(this.data.WebMainResource.WebResourceTextEncodingName));
}
}
|
cbdabb5bb5a9031b946a783298d1e8d41d85ff3b
|
TypeScript
|
wydra98/Flight-booking-frontend
|
/src/app/user/search-flight/Type.ts
| 3.15625
| 3
|
export class Type {
text: string;
allowed: boolean;
constructor(text: string, allowed: boolean) {
this.text = text;
this.allowed = allowed;
}
}
|
645f8aaad2c3e5f279a313d549dabdea9cb90aac
|
TypeScript
|
AbhishekLondhe/swabhavrepo3
|
/angular7/welcome-app/src/app/student/student.component.ts
| 2.59375
| 3
|
import { Component } from "@angular/core";
import { IStudents } from "./IStudents";
import{ICourse} from "./ICourse"
@Component({
selector: 'aurionpro-student',
templateUrl: 'student.component.html'
})
export class StudentComponent {
student: IStudents;
imgHeight:String="400px";
imgWidth:String="400px";
courses:ICourse[];
constructor() {
this.student = {
name: "abhishek",
cgpa: 9.54,
location: "borivali",
profilePic: '../../assets/download.jpg'
}
}
convertCgpaToColor() {
if(this.student.cgpa<5){
return "red";
}
else if(this.student.cgpa>=5 && this.student.cgpa<8){
return "yellow";
}
else{
return "green";
}
}
loadCourse(){
this.courses=[{courseId:1,courseName:"java"},{courseId:2,courseName:"angular"},{courseId:3,courseName:"jquery"}];
}
nameChange(newVal:String){
console.log(newVal);
this.student.name=newVal;
}
}
|
21f2019f3c3cb1e154e01ad165d3268591760989
|
TypeScript
|
zeromq/zeromq.js
|
/test/unit/context-construction-test.ts
| 2.625
| 3
|
import * as zmq from "../../src"
import {assert} from "chai"
describe("context construction", function () {
afterEach(function () {
global.gc?.()
})
it("should throw if called as function", function () {
assert.throws(
() => (zmq.Context as any)(),
TypeError,
"Class constructors cannot be invoked without 'new'",
)
})
it("should throw with wrong options argument", function () {
assert.throws(
() => new (zmq.Context as any)(1),
TypeError,
"Options must be an object",
)
})
it("should throw with too many arguments", function () {
assert.throws(
() => new (zmq.Context as any)({}, 2),
TypeError,
"Expected 1 argument",
)
})
it("should set option", function () {
const context = new zmq.Context({ioThreads: 5})
assert.equal(context.ioThreads, 5)
})
it("should throw with invalid option value", function () {
assert.throws(
() => new (zmq.Context as any)({ioThreads: "hello"}),
TypeError,
"Option value must be a number",
)
})
it("should throw with readonly option", function () {
assert.throws(
() => new (zmq.Context as any)({maxSocketsLimit: 1}),
TypeError,
"Cannot set property maxSocketsLimit of #<Context> which has only a getter",
)
})
it("should throw with unknown option", function () {
assert.throws(
() => new (zmq.Context as any)({doesNotExist: 1}),
TypeError,
"Cannot add property doesNotExist, object is not extensible",
)
})
})
|
ee1102a33ec0da85853fb91ed279ab8660f8e227
|
TypeScript
|
mznx/git-graph
|
/dev/ts/model.ts
| 2.609375
| 3
|
import { View } from './view';
import { Commit, Tag, CommitsObject, CommitQueue, Coords } from './mytypes';
export class Model {
view: View;
commit_queue: CommitQueue;
json_check: boolean;
constructor(view: View) {
this.view = view;
this.json_check = false;
}
parseJSON(text: string) {
let json: CommitsObject;
let error_msg: string;
try {
json = JSON.parse(text);
if (!this.checkJSONContent(json)) throw {name: 'ContentError'};
this.json_check = true;
} catch (event) {
error_msg = 'JSON: ' + event.name;
this.json_check = false;
}
if (this.json_check){
this.generateCommitQueue(json);
this.view.render(this.commit_queue);
} else {
this.view.renderFail(error_msg);
}
}
// добавить проверку времени
checkJSONContent(json: CommitsObject): boolean {
let hashs: string[] = [];
let error: boolean = false;
// проверяем наличие обязательных массивов
if (!json.hasOwnProperty('commits'))
return false;
if (!json.hasOwnProperty('tags'))
return false;
// проверяем коммиты на наличие обязательных полей и совпадения хэшей
for (let i = 0; i < json.commits.length; i++) {
if (!json.commits[i].hasOwnProperty('hash') || !json.commits[i].hasOwnProperty('text') || !json.commits[i].hasOwnProperty('time') || !json.commits[i].hasOwnProperty('previous')) {
error = true;
break;
}
if (hashs.indexOf(json.commits[i].hash) !== -1) {
error = true;
break;
}
hashs.push(json.commits[i].hash);
}
if (error)
return false;
// проверяем наличие всех родителей коммитов как самостоятельных коммитов
for (let i = 0; i < json.commits.length; i++) {
for (let j = 0; j < json.commits[i].previous.length; j++) {
if (hashs.indexOf(json.commits[i].previous[j]) == -1) {
error = true;
break;
}
}
if (error) break;
}
if (error)
return false;
// проверяем тэги на наличие обязательных полей и корректность хэша
for (let i = 0; i < json.tags.length; i++) {
if (!json.tags[i].hasOwnProperty('commit') || !json.tags[i].hasOwnProperty('tag')) {
error = true;
break;
}
if (hashs.indexOf(json.tags[i].commit) == -1) {
error = true;
break;
}
}
if (error)
return false;
return true;
}
// генерирует объект отсортированных по времени коммитов с добавлением в них ветки и тэга
generateCommitQueue(json: CommitsObject) {
let branchs: string[] = [];
let tags: Tag[] = json.tags;
this.commit_queue = json.commits;
// сортируем по времени
this.commit_queue.sort(function(a, b) {
return Date.parse(a.time) - Date.parse(b.time);
});
// добавляем ветки и теги
for (let i = 0; i < this.commit_queue.length; i++) { // проходим по коммитам
let branchExist: boolean = false;
for (let j = 0; j < this.commit_queue[i].previous.length; j++) { // проходим по предкам
for (let k = 0; k < branchs.length; k++) { // проходим по веткам
if (this.commit_queue[i].previous[j] == branchs[k]) { // нашли ветку к которой относится
branchs[k] = this.commit_queue[i].hash;
this.commit_queue[i].branch = k;
branchExist = true;
break;
}
}
if (branchExist) break;
}
// создаем новую ветку, если коммит не является продолжением текущей
if (!branchExist) {
branchs.push(this.commit_queue[i].hash);
this.commit_queue[i].branch = branchs.length - 1;
}
// добавляем тэг к коммиту, если есть
for (let j = 0; j < tags.length; j++) {
if (this.commit_queue[i].hash == tags[j].commit)
this.commit_queue[i].tag = tags[j].tag;
}
}
}
graphMove(shift: Coords) {
if (this.json_check) {
this.view.move(shift);
this.view.render(this.commit_queue);
}
}
checkClick(coords: Coords, mouse: Coords) {
if (this.json_check) {
this.view.onClick(this.commit_queue, coords, mouse);
}
}
}
|
4a424b20dded2549be04aa598d5ca9acca330967
|
TypeScript
|
organizer2012/TypeScript
|
/Seminar ECMA6/seminar_Original/typescript/types.ts
| 3.34375
| 3
|
// Value Types??
// das ist einer!
let zweiundvierzig: 42;
zweiundvierzig = 42;
// zweiundvierzig = 17;
let numBool: number|boolean|null;
type numBoolNull = number|boolean|null;
let numBool2: numBoolNull;
type ampel = 'rot'|'gelb'|'grün';
type zahlangabe = 'nix'|'nada'|number|null;
let color:ampel;
color = 'rot'; // ok!
|
8f11392cdd2add86db8bb563fe7216bae855d612
|
TypeScript
|
boromisp/jsonapi-tools
|
/packages/jsonapi-tools/src/handlers/handle-errors.ts
| 2.875
| 3
|
'use strict';
import * as JSONAPI from 'jsonapi-types';
import { IExtendedError, IErrorResponseObject } from '../types/utils';
export interface IErrorLogger {
error: (message: any, ...optionalArgs: any[]) => void;
}
function transformError(error: IExtendedError): JSONAPI.IErrorObject {
const val: JSONAPI.IErrorObject = {
status: error.status,
detail: error.message
};
if (error.source) {
val.source = error.source;
}
if (error.code) {
val.code = error.code;
}
if (error.title) {
val.title = error.title;
}
if (error.meta) {
val.meta = error.meta;
}
if (error.id) {
val.id = error.id;
}
if (error.links) {
val.links = error.links;
}
return val;
}
export default function handleErrors(
errorOrErrors: IExtendedError | IExtendedError[] | undefined,
errorLogger: IErrorLogger
): IErrorResponseObject {
let errors: JSONAPI.IErrorObject[];
if (Array.isArray(errorOrErrors)) {
if (errorOrErrors.length && errorOrErrors[0].status) {
errors = errorOrErrors.map(transformError);
} else if (!errorOrErrors.length) {
errors = [{ detail: 'Unknown internal error: []' }];
} else {
errorLogger.error(errorOrErrors[0].message, errorOrErrors[0].stack);
errors = [{ detail: `Unknown internal error: ${errorOrErrors[0].message}` }];
}
} else if (errorOrErrors && errorOrErrors.status) {
errors = [transformError(errorOrErrors)];
} else {
if (errorOrErrors && errorOrErrors.message && errorOrErrors.stack) {
errorLogger.error(errorOrErrors.message, errorOrErrors.stack);
}
errors = [{ detail: `Unknown internal error: ${errorOrErrors ? errorOrErrors.message : '<unknown>'}` }];
}
throw errors;
// return { status: errors[0].status || 500, body: { errors } };
}
|
ca18920782d0cbb94e2f0a81d1ccfd605d12705d
|
TypeScript
|
iMicknl/communication-ui-library
|
/packages/storybook/.storybook/telemetry.ts
| 2.796875
| 3
|
import { ApplicationInsights } from '@microsoft/applicationinsights-web';
/**
* Check if we have the necessary cookie consent to allow the app insights library to make use of cookies
*/
export const analyticsCookieConsentObtained = (): boolean => {
return (
!!(window as any).siteConsent && // has telemetry library been initialized
(!(window as any).siteConsent.isConsentRequired || // check if we need collect consent in this region
(window as any).siteConsent.getConsent().Analytics)
); // check if we have consent to collect analytics telemetry
};
/**
* Start telemetry collection and watch for cookie consent changes.
*/
export const initTelemetry = () => {
const appInsightsInstance = startTelemetry(analyticsCookieConsentObtained());
if (appInsightsInstance) {
createCookieChangedCallback(appInsightsInstance);
}
};
/**
* Setup the window.cookieConsentChanged that is called when the cookie banner's onConsentChanged is called.
* @param applicationInsightsInstance application instance that enables or disables appInsight's cookie manager
*/
const createCookieChangedCallback = (applicationInsightsInstance: ApplicationInsights) => {
(window as any).cookieConsentChanged = () => {
const analyticsCookieConsent = analyticsCookieConsentObtained();
applicationInsightsInstance.getCookieMgr().setEnabled(analyticsCookieConsent);
};
};
/**
* Start app insights tracking telemetry
* @param cookieConsent do we have consent to collect cookies for analytics purposes
* @returns the created instance of the application insights library
*/
const startTelemetry = (cookieConsent: boolean): ApplicationInsights | undefined => {
const instrumentationKey = process.env.TELEMETRY_INSTRUMENTATION_KEY;
if (!instrumentationKey) {
console.warn('No telemetry instrumentationKey provided. Telemetry collection is disabled.');
return;
}
// Initialize and start collecting telemetry
const appInsights = new ApplicationInsights({
config: {
disableCookiesUsage: !cookieConsent,
instrumentationKey,
enableAutoRouteTracking: true
}
});
appInsights.loadAppInsights();
return appInsights;
};
|
0fcf9be9c36035d8951540ece15eb0b56969ba20
|
TypeScript
|
khanka0511/discord-contest-bot
|
/src/notify.ts
| 2.78125
| 3
|
import { subscribedChannels } from '@/cli';
import {
EventSource,
UpcomingEvent,
notifyIntervals,
formatUpcomingEvent,
} from './event';
const eventSources: Map<string, EventSource> = new Map();
export function addEventSource(eventSource: EventSource, id: string) {
if (eventSources.has(id)) {
throw Error(`Event source with ID ${id} is already added!`);
}
eventSources.set(id, eventSource);
}
const upcomingEvents: Map<string, UpcomingEvent> = new Map();
// handleNewContest add new contest to upcomingEvents map and creates notifiers
function handleNewContest(contest: UpcomingEvent) {
// Insert contest to upcomingEvents map
if (upcomingEvents.has(contest.id)) {
return;
}
upcomingEvents.set(contest.id, contest);
// For each interval in notifyIntervals create timeout sending notification to subscribedChannels
const currentTime = Date.now() / 1000;
notifyIntervals.forEach(async interval => {
const timeDist = contest.startTime - interval.remainingTime;
await new Promise(resolve =>
setTimeout(() => resolve, (timeDist - currentTime) * 1000),
);
subscribedChannels.forEach(channel => {
channel.send(`Contest will start in ${interval.message}!!`);
channel.send(formatUpcomingEvent(contest));
});
});
}
export async function getUpcomingEvents(): Promise<UpcomingEvent[]> {
const upcoming = [];
await Promise.all(
Array.from(eventSources.values()).map(async source => {
const events = await source.poll();
upcoming.push(...events);
}),
);
return upcoming;
}
// checkForNewContests fetches list of upcoming events and add new contests if found
export async function checkForNewContests() {
(await getUpcomingEvents())
.filter(event => !upcomingEvents.has(event.id))
.forEach(handleNewContest);
}
|
adba965f0bde6ec4d05cb05e459c53e4f4d3680b
|
TypeScript
|
corbane/g3
|
/worker/io/ressource.ts
| 3.03125
| 3
|
"use strict"
const IS_RESOURCE = Symbol.for ("GS_RESOURCE")
interface IResource <T = any>
{
readonly isLoaded: boolean
readonly data : T|null
}
declare function loadImage <T> (url: string, callback?: (rsc: ImageBitmap) => T): IResource<T>
declare function loadText <T> (url: string, callback?: (rsc: string) => T) : IResource<T>
declare function loadJson <T> (url: string, callback?: (rsc: object) => T) : IResource<T>
declare namespace Internal
{
type Resource <T = any> = { -readonly [K in keyof IResource<T>]: IResource<T>[K] } & { [IS_RESOURCE]: true }
function isLoading (): boolean
function setBaseUri (uri: string): void
function getResourcePath (path: string): string
}
;{ // Resources Manager
let m_baseuri = ""
let m_loading_count = 0
const setBaseUri = function (uri: string)
{
if(uri[uri.length - 1] != '/')
m_baseuri = uri + '/'
else
m_baseuri = uri
}
const getResourcePath = function (path: string)
{
return m_baseuri + ( path[0] == '/' ? path.substring (1) : path )
}
const isLoading = function () { return m_loading_count != 0 }
const fetchArrayBuffer = function <R> (url: string, callback?: (rsc: ArrayBuffer) => R)
{
m_loading_count++
const rsc: Partial <Internal.Resource <R>> = {
[IS_RESOURCE] : true,
isLoaded : false,
data : null
}
fetch (url)
.then (ret => ret.arrayBuffer ())
.then (arrbuf =>
{
rsc.isLoaded = true
if (callback)
rsc.data = callback (arrbuf)
_finallyLoad ()
})
.catch (err =>
{
Internal.addAndEmitError (err)
_finallyLoad ()
})
return rsc as IResource <R>
}
const loadImage = function <R> (url: string, callback?: (rsc: ImageBitmap) => R)
{
m_loading_count++
const rsc: Partial <Internal.Resource <R>> = {
[IS_RESOURCE] : true,
isLoaded: false,
data: null
}
fetch (getResourcePath (url))
.then (ret => ret.blob ())
.then (blob => createImageBitmap (blob))
.then (img =>
{
rsc.isLoaded = true
if (callback)
rsc.data = callback (img)
_finallyLoad ()
})
.catch (err =>
{
Internal.addAndEmitError (err)
_finallyLoad ()
})
return rsc as IResource <R>
}
const loadText = function <R> (url: string, callback?: (text: string) => R)
{
m_loading_count++
const rsc: Partial <Internal.Resource <R>> = {
[IS_RESOURCE] : true,
isLoaded: false,
data: null
}
fetch (getResourcePath (url))
.then (ret => ret.text())
.then (text =>
{
rsc.isLoaded = true
if (callback)
rsc.data = callback (text)
_finallyLoad ()
})
.catch (err =>
{
Internal.addAndEmitError (err)
_finallyLoad ()
})
return rsc as IResource <R>
}
const loadJson = function <R> (url: string, callback?: (json: object) => R)
{
m_loading_count++
const rsc: Partial <Internal.Resource <R>> = {
[IS_RESOURCE] : true,
isLoaded: false,
data: null
}
fetch (getResourcePath (url))
.then (ret => ret.json())
.then (json =>
{
rsc.isLoaded = true
if(callback)
rsc.data = callback(json)
_finallyLoad()
})
.catch (err =>
{
Internal.addAndEmitError (err)
_finallyLoad()
})
return rsc as IResource <R>
}
const _finallyLoad = function ()
{
m_loading_count--
if (m_loading_count != 0)
return
//if (m_on_loaded)
// m_on_loaded ()
Internal.dispatch ("resource-loaded")
}
Internal.definePublicMethods ({
loadImage,
loadText,
loadJson
})
Internal.defineInternalMethods ({
isLoading,
setBaseUri,
getResourcePath
})
}
|
6e8dd42b4c1c142e895cb556feda6c70540ef1aa
|
TypeScript
|
isdenmois/beta-hd
|
/src/app/pipes/sort-table.pipe.ts
| 2.578125
| 3
|
import {Pipe, PipeTransform} from "angular2/core";
/**
* Filter task list with selected.
*/
@Pipe({name: 'tasksort'})
export class TaskListSorterPipe implements PipeTransform {
transform(collection, args) {
const [column, direction] = args;
if (column == '') {
return collection;
}
collection.sort((t1, t2) => {
if (t1[column] > t2[column]) {
return direction;
}
if (t1[column] < t2[column]) {
return -1 * direction;
}
return 0;
});
return collection;
}
}
|
bda1d4f34051bdaa07bbe3af33e5228f1f7f61e5
|
TypeScript
|
Hspharwinder/CompleteNodeAngular8Project
|
/CrudMeanAngular8ReactiveForm/src/app/Service/authentication.service.ts
| 2.515625
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { BaseURL, Api } from '../path.config/Api';
import { ToastrService } from 'ngx-toastr';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
constructor(private http: HttpClient,
private toastr: ToastrService,
private router: Router, ) { }
login(username: string, password: string) {
return this.http.post<any>(BaseURL + `/auth/login`, { username, password })
.pipe(map(user => {
// login successful if there's a jwt token in the response
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
// this.currentUserSubject.next(user);
}
return user;
}));
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
this.router.navigateByUrl('/login');
// this.currentUserSubject.next(null);
}
getToken(){
const getUser = JSON.parse(localStorage.getItem('currentUser'));
if(getUser)
return getUser.token;
}
loggedIn():boolean{
return !! this.getToken(); // !! uses for returning boolean value if get token return true else false
}
tokenExpire(){
this.toastr.error("Token Expire");
this.logout();
}
}
|
3c63e039363ade6be95518826cbba997f0714ee3
|
TypeScript
|
bergur/pg-parameterize
|
/src/index.ts
| 3.078125
| 3
|
export function toOrdinal (sqlString: string): string {
let index = 1
let ordinalString = sqlString
while (ordinalString.indexOf('?') !== -1) {
ordinalString = ordinalString.replace('?','$' + index)
index++
}
return ordinalString
}
export function flatten (arr: any[]): string {
return arr.reduce((flattened,item) => {
item.forEach(value => {
flattened.push(value)
})
return flattened
},[])
}
export function toTuple (arr: any[], makeOrdinal?: boolean): string {
const tuple = arr.map(item => {
return '(' + item.map(_ => '?').join(',') + ')'
}).join(',')
if (!makeOrdinal) {
return tuple
} else {
return toOrdinal(tuple)
}
}
export default { toOrdinal, flatten, toTuple }
|
862f8b7fcb982230940206a780678d311b5fcee2
|
TypeScript
|
sreenuyedavalli/angular
|
/modules/angular2/src/facade/intl.ts
| 3.09375
| 3
|
// Modified version of internal Typescript intl.d.ts.
// TODO(piloopin): remove when https://github.com/Microsoft/TypeScript/issues/3521 is shipped.
declare module Intl {
interface NumberFormatOptions {
localeMatcher?: string;
style?: string;
currency?: string;
currencyDisplay?: string;
useGrouping?: boolean;
minimumIntegerDigits?: number;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
}
interface NumberFormat {
format(value: number): string;
}
var NumberFormat: {new (locale?: string, options?: NumberFormatOptions): NumberFormat};
interface DateTimeFormatOptions {
localeMatcher?: string;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
formatMatcher?: string;
hour12?: boolean;
}
interface DateTimeFormat {
format(date?: Date | number): string;
}
var DateTimeFormat: {new (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat};
}
export enum NumberFormatStyle {
DECIMAL,
PERCENT,
CURRENCY
}
export class NumberFormatter {
static format(number: number, locale: string, style: NumberFormatStyle,
{minimumIntegerDigits = 1, minimumFractionDigits = 0, maximumFractionDigits = 3,
currency, currencyAsSymbol = false}: {
minimumIntegerDigits?: int,
minimumFractionDigits?: int,
maximumFractionDigits?: int,
currency?: string,
currencyAsSymbol?: boolean
} = {}): string {
var intlOptions: Intl.NumberFormatOptions = {
minimumIntegerDigits: minimumIntegerDigits,
minimumFractionDigits: minimumFractionDigits,
maximumFractionDigits: maximumFractionDigits
};
intlOptions.style = NumberFormatStyle[style].toLowerCase();
if (style == NumberFormatStyle.CURRENCY) {
intlOptions.currency = currency;
intlOptions.currencyDisplay = currencyAsSymbol ? 'symbol' : 'code';
}
return new Intl.NumberFormat(locale, intlOptions).format(number);
}
}
function digitCondition(len: int): string {
return len == 2 ? '2-digit' : 'numeric';
}
function nameCondition(len: int): string {
return len < 4 ? 'short' : 'long';
}
function extractComponents(pattern: string): Intl.DateTimeFormatOptions {
var ret: Intl.DateTimeFormatOptions = {};
var i = 0, j;
while (i < pattern.length) {
j = i;
while (j < pattern.length && pattern[j] == pattern[i]) j++;
let len = j - i;
switch (pattern[i]) {
case 'G':
ret.era = nameCondition(len);
break;
case 'y':
ret.year = digitCondition(len);
break;
case 'M':
if (len >= 3)
ret.month = nameCondition(len);
else
ret.month = digitCondition(len);
break;
case 'd':
ret.day = digitCondition(len);
break;
case 'E':
ret.weekday = nameCondition(len);
break;
case 'j':
ret.hour = digitCondition(len);
break;
case 'h':
ret.hour = digitCondition(len);
ret.hour12 = true;
break;
case 'H':
ret.hour = digitCondition(len);
ret.hour12 = false;
break;
case 'm':
ret.minute = digitCondition(len);
break;
case 's':
ret.second = digitCondition(len);
break;
case 'z':
ret.timeZoneName = 'long';
break;
case 'Z':
ret.timeZoneName = 'short';
break;
}
i = j;
}
return ret;
}
var dateFormatterCache: Map<string, Intl.DateTimeFormat> = new Map<string, Intl.DateTimeFormat>();
export class DateFormatter {
static format(date: Date, locale: string, pattern: string): string {
var key = locale + pattern;
if (dateFormatterCache.has(key)) {
return dateFormatterCache.get(key).format(date);
}
var formatter = new Intl.DateTimeFormat(locale, extractComponents(pattern));
dateFormatterCache.set(key, formatter);
return formatter.format(date);
}
}
|
c6617b5447b4a1f1e54440cb6c762439b69a6078
|
TypeScript
|
Ragomez33/tasky-server
|
/src/triggers/trigger/handler.ts
| 2.78125
| 3
|
/**
* This file was generated using 8base CLI.
*
* To learn more about writing custom trigger functions, visit
* the 8base documentation at:
*
* https://docs.8base.com/8base-console/custom-functions/triggers
*
* To update this functions invocation settings, update its configuration block
* in the projects 8base.yml file:
* functions:
* trigger:
* ...
*
* Data that is sent to the function can be accessed on the event argument at:
* event.data[KEY_NAME]
*
* There are two ways to invoke this function locally:
*
* (1) Explicit file mock file path using '-p' flag:
* 8base invoke-local trigger -p src/resolvers/trigger/mocks/request.json
*
* (2) Default mock file location using -m flag:
* 8base invoke-local trigger -m request
*
* Add new mocks to this function to test different input arguments. Mocks can easily be generated
* the following generator command:
* 8base generate mock trigger -m [MOCK_FILE_NAME]
*/
import { FunctionContext, FunctionEvent, FunctionResult } from '8base-cli-types';
type TriggerResult = FunctionResult<{
firstName: string,
},
{},
{},
Array<object>
>;
export default async (
event: FunctionEvent,
ctx: FunctionContext,
): TriggerResult => {
return {
data: {
...event.data,
firstName: 'Override firstName',
},
/**
* Triggers allow for errors to be specified in the response
* as an array of user defined objects.
*
* Example:
*
* [{
* message: "Error message",
* code: "error_code"
* }, ...]
*/
errors: [],
};
};
|
122d64456d58c635b46bb2d71fd54ba745def301
|
TypeScript
|
AverzaAldo/merkdoo-test
|
/src/app/app.component.ts
| 2.59375
| 3
|
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
errorText = '';
productName ='';
productDesc = '';
productSku = '';
products: string[][] = [];
addProduct(){
if (this.productName == '' || this.productDesc == '' || this.productSku == '') //valida que todos los datos estén llenos
{
this.errorText = 'Por favor llenar todos los campos';
setTimeout (() => {
this.errorText = '';
}, 2000); //muestra el mensaje por dos segundos
}
else
{
this.products.push([this.productName, this.productDesc, this.productSku]);
this.productName ='';
this.productDesc = '';
this.productSku = '';
}//introduce productos al array y limpia los campos
}
deleteRow(index) {
this.products.splice(index, 1);//borra la fila seleccionada
}
}
|
b68637d2f595fdb3fa44d95fa698aa7af067f6e1
|
TypeScript
|
brayanesteves/mipsss-selasky-nodejs-angular
|
/backend/src/controller/UserController.ts
| 2.6875
| 3
|
import {getRepository} from "typeorm";
import {NextFunction, Request, Response} from "express";
import { User } from "../entity/User";
import { validate } from 'class-validator';
import * as moment from 'moment';
export class UserController {
//
static getAll = async (req: Request, res: Response) => {
const userRepository = getRepository(User);
let users;
try {
users = await userRepository.find();
} catch(e){
res.status(404).json({ message: 'Something goes wrong!' });
}
if (users.length > 0) {
res.send(users);
} else {
res.status(404).json({ message: 'Not result' });
}
};
static getById = async (req: Request, res: Response) => {
const { id } = req.params;
const userRepository = getRepository(User);
try {
const user = await userRepository.findOneOrFail(id);
res.send(user);
} catch(e) {
res.status(404).json({ message: 'Not result' });
}
};
static newUser = async (req: Request, res: Response) => {
const { Usrnm, Psswrd, Rfrnc_Prsn, UsrTyp_Rfrnc } = req.body;
const user = new User();
user.Usrnm = Usrnm;
user.Psswrd = Psswrd;
user.Rfrnc_Prsn = Rfrnc_Prsn;
user.UsrTyp_Rfrnc = UsrTyp_Rfrnc;
user.Cndtn = 1;
user.Rmvd = 0;
user.Lckd = 0;
user.DtAdmssn = new Date();
user.ChckTm = moment(new Date()).format('HH:mm:ss');
// Validate
const validationOpt = { validationError: { target: false, value: false } };
const errors = await validate(user, validationOpt);
if(errors.length > 0) {
return res.status(400).json(errors);
}
// TODO: Hash Password
const userRepository = getRepository(User);
try {
user.hashPassword();
await userRepository.save(user);
} catch(e) {
return res.status(409).json({ message: 'Username already exist' + res});
}
// All ok
res.send('User created');
};
static editUser = async (req: Request, res: Response) => {
let user;
const { Rfrnc } = req.params;
const { Usrnm, Psswrd, Rfrnc_Prsn, UsrTyp_Rfrnc } = req.body;
const userRepository = getRepository(User);
// Try get user
try {
user = await userRepository.findOneOrFail(Rfrnc);
} catch(e) {
return res.status(404).json({ message: 'User not found' });
}
user.Usrnm = Usrnm;
user.Psswrd = Psswrd;
user.Rfrnc_Prsn = Rfrnc_Prsn;
user.UsrTyp_Rfrnc = UsrTyp_Rfrnc;
user.Cndtn = 1;
user.Rmvd = 0;
user.Lckd = 0;
const validationOpt = { validationError: { target: false, value: false } };
const errors = await validate(user, validationOpt);
if(errors.length > 0) {
return res.status(400).json(errors);
}
// Try to save user
try {
await userRepository.save(user);
} catch (e) {
return res.status(409).json({ message: 'Username already in user' });
}
res.status(201).json({ message: 'User update' });
};
static deleteUser = async (req: Request, res: Response) => {
const { Rfrnc } = req.params;
const userRepository = getRepository(User);
let user: User;
try {
user = await userRepository.findOneOrFail(Rfrnc);
} catch(e) {
return res.status(404).json({ message: 'User not found' });
}
// Remove user
userRepository.delete(Rfrnc);
res.status(201).json({ message: 'User deleted' });
};
}
export default UserController;
|
b81d306c257acb457591ba56486b1a3ee1334fa7
|
TypeScript
|
BlokDenis/EVM
|
/packages/client/lib/net/peerpool.ts
| 2.96875
| 3
|
import { EventEmitter } from 'events'
import { Config } from '../config'
import { Peer } from './peer/peer'
import { RlpxServer } from './server'
export interface PeerPoolOptions {
/* Config */
config: Config
}
/**
* @module net
*/
/**
* Pool of connected peers
* @memberof module:net
* @emits connected
* @emits disconnected
* @emits banned
* @emits added
* @emits removed
* @emits message
* @emits message:{protocol}
* @emits error
*/
export class PeerPool extends EventEmitter {
public config: Config
private pool: Map<string, Peer>
private noPeerPeriods: number
private opened: boolean
// eslint-disable-next-line no-undef
private _statusCheckInterval: NodeJS.Timeout | null
/**
* Create new peer pool
* @param {Object} options constructor parameters
*/
constructor(options: PeerPoolOptions) {
super()
this.config = options.config
this.pool = new Map<string, Peer>()
this.noPeerPeriods = 0
this.opened = false
this._statusCheckInterval = null
this.init()
}
init() {
this.opened = false
}
/**
* Open pool
* @return {Promise}
*/
async open(): Promise<boolean | void> {
if (this.opened) {
return false
}
this.config.servers.map((s) => {
s.on('connected', (peer: Peer) => {
this.connected(peer)
})
s.on('disconnected', (peer: Peer) => {
this.disconnected(peer)
})
})
this.opened = true
// eslint-disable-next-line @typescript-eslint/await-thenable
this._statusCheckInterval = setInterval(await this._statusCheck.bind(this), 20000)
}
/**
* Close pool
* @return {Promise}
*/
async close() {
this.pool.clear()
this.opened = false
// eslint-disable-next-line no-undef
clearInterval(this._statusCheckInterval as NodeJS.Timeout)
}
/**
* Connected peers
*/
get peers(): Peer[] {
const connectedPeers: Peer[] = Array.from(this.pool.values())
return connectedPeers
}
/**
* Number of peers in pool
* @type {number}
*/
get size(): number {
return this.peers.length
}
/**
* Return true if pool contains the specified peer
* @param peer object or peer id
*/
contains(peer: Peer | string): boolean {
if (typeof peer !== 'string') {
peer = peer.id
}
return !!this.pool.get(peer)
}
/**
* Returns a random idle peer from the pool
* @param [filterFn] filter function to apply before finding idle peers
* @return {Peer}
*/
idle(filterFn = (_peer: Peer) => true): Peer {
const idle = this.peers.filter((p) => p.idle && filterFn(p))
const index = Math.floor(Math.random() * idle.length)
return idle[index]
}
/**
* Handler for peer connections
* @private
* @param {Peer} peer
*/
connected(peer: Peer) {
if (this.size >= this.config.maxPeers) return
peer.on('message', (message: any, protocol: string) => {
if (this.pool.get(peer.id)) {
this.emit('message', message, protocol, peer)
this.emit(`message:${protocol}`, message, peer)
}
})
peer.on('error', (error: Error) => {
if (this.pool.get(peer.id)) {
this.config.logger.warn(`Peer error: ${error} ${peer}`)
this.ban(peer)
}
})
this.add(peer)
peer.handleMessageQueue()
}
/**
* Handler for peer disconnections
* @private
* @param {Peer} peer
*/
disconnected(peer: Peer) {
this.remove(peer)
}
/**
* Ban peer from being added to the pool for a period of time
* @param {Peer} peer
* @param maxAge ban period in milliseconds
* @emits banned
*/
ban(peer: Peer, maxAge: number = 60000) {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (!peer.server) {
return
}
peer.server.ban(peer.id, maxAge)
this.remove(peer)
this.emit('banned', peer)
}
/**
* Add peer to pool
* @param {Peer} peer
* @emits added
* @emits message
* @emits message:{protocol}
*/
add(peer?: Peer) {
if (peer && peer.id && !this.pool.get(peer.id)) {
this.pool.set(peer.id, peer)
peer.pooled = true
this.emit('added', peer)
}
}
/**
* Remove peer from pool
* @param {Peer} peer
* @emits removed
*/
remove(peer?: Peer) {
if (peer && peer.id) {
if (this.pool.delete(peer.id)) {
peer.pooled = false
this.emit('removed', peer)
}
}
}
/**
* Peer pool status check on a repeated interval
*/
async _statusCheck() {
if (this.size === 0) {
this.noPeerPeriods += 1
if (this.noPeerPeriods >= 3) {
const promises = this.config.servers.map(async (server) => {
if (server instanceof RlpxServer && server.discovery) {
this.config.logger.info('Restarting RLPx server: bootstrap')
await server.stop()
await server.start()
}
})
await Promise.all(promises)
this.noPeerPeriods = 0
} else {
let tablesize: number | undefined = 0
this.config.servers.forEach((server) => {
if (server instanceof RlpxServer && server.discovery) {
tablesize = server.dpt?.getPeers().length
this.config.logger.info(`Looking for suited peers: peertablesize=${tablesize}`)
}
})
}
} else {
this.noPeerPeriods = 0
}
}
}
|
27d400e6716ed334d219d61449163c244bcd3f27
|
TypeScript
|
jeremy-coleman/gulpy
|
/packages/async-done/index.ts
| 2.84375
| 3
|
import * as domain from "domain"
import eos from "@local/end-of-stream"
import { once, isFunction } from "lodash"
import exhaust from "stream-exhaust"
import type { ChildProcess } from "child_process"
import type { EventEmitter } from "events"
import type { Stream } from "stream"
/**
* Represents a callback function used to signal the completion of a
* task without any result value.
*/
export type VoidCallback = (err: Error | null) => void
/**
* Represents a callback function used to signal the completion of a
* task with a single result value.
*/
export interface Callback<T> {
(err: null, result: T): void
// Use `result?: T` or `result: undefined` to require the consumer to assert the existence of the result
// (even in case of success). See comment at the top of the file.
(err: Error, result?: any): void
}
/**
* Minimal `Observable` interface compatible with `async-done`.
*
* @see https://github.com/ReactiveX/rxjs/blob/c3c56867eaf93f302ac7cd588034c7d8712f2834/src/internal/Observable.ts#L77
*/
interface Observable<T = any> {
subscribe(
next?: (value: T) => void,
error?: (error: any) => void,
complete?: () => void
): any
}
/**
* Represents an async operation.
*/
export type AsyncTask<R = any> =
| ((done: VoidCallback) => void)
| ((done: Callback<R>) => void)
| (() => ChildProcess | EventEmitter | Observable<R> | PromiseLike<R> | Stream)
const eosConfig = {
error: false,
}
/**
* Takes a function to execute (`fn`) and a function to call on completion (`callback`).
*
* @param fn Function to execute.
* @param callback Function to call on completion.
*/
export function asyncDone<R = any>(fn: AsyncTask<R>, cb: Callback<R>): void {
cb = once(cb)
const d = domain.create()
d.once("error", onError)
const domainBoundFn = d.bind(fn)
function done(...rest) {
d.removeListener("error", onError)
d.exit()
try {
return cb(...rest)
} catch (e) {
process.nextTick(() => {
throw e
})
}
}
function onSuccess(result) {
done(null, result)
}
function onError(error = Error("Promise rejected without Error")) {
done(error)
}
function asyncRunner() {
const result = domainBoundFn(done) as any
function onNext(state) {
onNext.state = state
}
onNext.state = null
function onCompleted() {
onSuccess(onNext.state)
}
if (result && isFunction(result.on)) {
// Assume node stream
d.add(result)
eos(exhaust(result), eosConfig, done)
return
}
if (result && isFunction(result.subscribe)) {
// Assume RxJS observable
result.subscribe(onNext, onError, onCompleted)
return
}
if (result && isFunction(result.then)) {
// Assume promise
result.then(onSuccess, onError)
return
}
}
process.nextTick(asyncRunner)
}
|
71c634359f276c8f14129c5b9fb718e67c539df5
|
TypeScript
|
cloudfoundry/stratos
|
/src/frontend/packages/core/src/core/utils.service.ts
| 2.65625
| 3
|
import { Injectable } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';
export function getIdFromRoute(activatedRoute: ActivatedRoute, id: string) {
if (activatedRoute.snapshot.params[id]) {
return activatedRoute.snapshot.params[id];
} else if (activatedRoute.parent) {
return getIdFromRoute(activatedRoute.parent, id);
}
return null;
}
export const urlValidationExpression =
'^' +
// protocol identifier
'http(s)?://' +
// user:pass authentication
'(?:\\S+(?::\\S*)?@)?' +
'(?:' +
// IP address exclusion
// private & local networks
'(?!(?:10|127)(?:\\.\\d{1,3}){3})' +
'(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})' +
'(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})' +
// IP address dotted notation octets
// excludes loopback network 0.0.0.0
// excludes reserved space >= 224.0.0.0
// excludes network & broadcast addresses
// (first & last IP address of each class)
'(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])' +
'(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}' +
'(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))' +
'|' +
// host name
'(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)' +
// domain name
'(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*' +
// TLD identifier
'(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))' +
// TLD may end with dot
'\\.?' +
')' +
// port number
'(?::\\d{2,5})?' +
// resource path
'(?:[/?#]\\S*)?' +
'$'
;
@Injectable()
export class UtilsService {
private units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'];
/*
* Expression used to validate URLs in the Endpoint registration form.
* Expression explanation available from https://gist.github.com/dperini/729294
* Passes the following criteria: https://mathiasbynens.be/demo/url-regex
*
*/
public urlValidationExpression = urlValidationExpression;
constructor() { }
precisionIfUseful(size: number, precision: number = 1) {
const floored = Math.floor(size);
const fixed = Number(size.toFixed(precision));
if (floored === fixed) {
return floored;
}
return fixed;
}
mbToHumanSize(mb: number): string {
if (mb == null) {
return '';
}
if (mb === -1) {
return '∞';
}
if (mb >= 1048576) {
return this.precisionIfUseful(mb / 1048576) + ' TB';
}
if (mb >= 1024) {
return this.precisionIfUseful(mb / 1024) + ' GB';
}
return this.precisionIfUseful(mb) + ' MB';
}
bytesToHumanSize(value: string): string {
const bytes = parseInt(value, 10);
let retBytes = '';
if (!bytes && bytes !== 0) {
return '';
}
if (bytes === -1) {
retBytes = '∞';
}
if (bytes >= 1099511627776) {
retBytes = this.precisionIfUseful(bytes / 1099511627776) + ' TB';
} else if (bytes >= 1073741824) {
retBytes = this.precisionIfUseful(bytes / 1073741824) + ' GB';
} else if (bytes >= 1048576) {
retBytes = this.precisionIfUseful(bytes / 1048576) + ' MB';
} else if (bytes >= 1024) {
retBytes = this.precisionIfUseful(bytes / 1024) + ' kB';
} else if (bytes >= 0) {
retBytes = this.precisionIfUseful(bytes) + ' B';
}
return retBytes;
}
usageBytes(usage, usedPrecision?, totalPrecision?): string {
const used = usage[0];
const total = usage[1];
if (isNaN(parseFloat(used)) || !isFinite(used) ||
isNaN(parseFloat(total)) || !isFinite(total) ||
total === 0) {
return '-';
}
// Precision
usedPrecision = this.getDefaultPrecision(usedPrecision);
totalPrecision = this.getDefaultPrecision(totalPrecision);
// Units
const value = this.getNumber(total);
let usedNumber = null;
// Values to display
const totalDisplay = this.getReducedValue(total, value).toFixed(totalPrecision);
const usedValue = this.getReducedValue(used, value);
let usedDisplay = usedValue.toFixed(totalPrecision);
// Is the used value too small to be accurate (for instance 20M consumed of 1GB would show as 0 of 1GB)?
if (used !== 0 && usedPrecision === 0 && usedValue < 1) {
// Use the units relative to the used value instead of total (20MB of 1GB instead of 0 of 1GB)
usedNumber = this.getNumber(used);
usedDisplay = this.getReducedValue(used, usedNumber).toFixed(totalPrecision);
}
return usedDisplay + (usedNumber ? ' ' + this.units[usedNumber] : '') + ' / ' + totalDisplay + ' ' + this.units[value];
}
/**
* @description format an uptime in seconds into a days, hours, minutes, seconds string
* @param uptime in seconds
* @returns formatted uptime string
*/
formatUptime(uptime): string {
if (uptime === undefined || uptime === null || isNaN(uptime)) {
return '-';
}
if (uptime === 0) {
return this.getFormattedTime(false, '0', 's');
}
const days = Math.floor(uptime / 86400);
uptime = uptime % 86400;
const hours = Math.floor(uptime / 3600);
uptime = uptime % 3600;
const minutes = Math.floor(uptime / 60);
const seconds = uptime % 60;
return (
this.formatPart(days, 'd', 'd') +
this.formatPart(hours, 'h', 'h') +
this.formatPart(minutes, 'm', 'm') +
this.formatPart(seconds, 's', 's')
).trim();
}
percent(value: number, decimals: number = 2): string {
if (!value && value !== 0) {
return '';
}
const val = (value * 100).toFixed(decimals);
return val + '%';
}
private getReducedValue(value: number, multiplier: number): number {
return (value / Math.pow(1024, Math.floor(multiplier)));
}
private getDefaultPrecision(precision: number): number {
if (precision === undefined || precision === null) {
precision = 0;
}
return precision;
}
private getNumber(value: number): number {
return Math.floor(Math.log(value) / Math.log(1024));
}
private getFormattedTime(isPlural, value, unit): string {
// i18n
// const formatString = isPlural ? 'dateTime.plural.format' : 'dateTime.singular.format';
// return $translate.instant(formatString, { value: value, unit: unit });
return value + unit;
}
private formatPart(count, single, plural): string {
if (count === 0) {
return '';
} else if (count === 1) {
return this.getFormattedTime(false, count, single) + ' ';
} else {
return this.getFormattedTime(true, count, plural) + ' ';
}
}
}
/**
* Return the value in the object for the given dot separated param path
*/
export function pathGet(path: string, object: any): any {
const params = path.split('.');
let index = 0;
const length = params.length;
while (object !== null && object !== undefined && index < length) {
object = object[params[index++]];
}
return (index && index === length) ? object : undefined;
}
export function pathSet(path: string, object: any, value: any) {
const params = path.split('.');
let index = 0;
const length = params.length - 1;
while (object !== null && object !== undefined && index < length) {
object = object[params[index++]];
}
if ((index && index === length)) {
object[params[index++]] = value;
}
}
export function safeStringToObj<T = object>(value: string): T {
try {
if (value) {
const jsonObj = JSON.parse(value);
// Check if jsonObj is actually an obj
if (jsonObj.constructor !== {}.constructor) {
throw new Error('not an object');
}
return jsonObj;
}
} catch (e) {
return null;
}
return null;
}
export const safeUnsubscribe = (...subs: Subscription[]) => {
subs.forEach(sub => {
if (sub) {
sub.unsubscribe();
}
});
};
export const truthyIncludingZero = (obj: any): boolean => !!obj || obj === 0;
export const truthyIncludingZeroString = (obj: any): string => truthyIncludingZero(obj) ? obj.toString() : null;
/**
* Real basic, shallow check
*/
export const arraysEqual = (a: any[], b: any[]): boolean => {
// Both falsy
if (!a && !b) {
return true;
}
// Both truthy
if (a && b) {
if (a.length !== b.length) {
return false;
}
for (const vA of a) {
if (!b.includes(vA)) {
return false;
}
}
return true;
}
// Falsy/Truthy
return false;
};
/* tslint:disable:no-bitwise */
export const createGuid = (): string => {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = Math.random() * 16 | 0;
const v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
};
/* tslint:enable */
|
a3a4fb9abd85ef40b0b8c4b79ef66e72c5ec942c
|
TypeScript
|
corinm/advent-of-code-2019
|
/IntComputer/operations/index.ts
| 3.390625
| 3
|
import { getParameter, getParameters, setOutput } from "./helpers";
export const add = (opcode: number[], pointer: number): number[] => {
const { parameter1, parameter2 } = getParameters(opcode, pointer);
const output = parameter1 + parameter2;
const newOpcode = setOutput(opcode, pointer, output);
return newOpcode;
};
export const multiply = (opcode: number[], pointer: number): number[] => {
const { parameter1, parameter2 } = getParameters(opcode, pointer);
const output = parameter1 * parameter2;
const newOpcode = setOutput(opcode, pointer, output);
return newOpcode;
};
export const saveToPosition = (
opcode: number[],
pointer: number,
input: number
): number[] => {
const newOpcode = [...opcode];
const outputAddress = opcode[pointer + 1];
newOpcode[outputAddress] = input;
return newOpcode;
};
export const outputParameter = (opcode: number[], pointer: number) => {
return getParameter(opcode, pointer, 1);
};
/**
* Opcode 5 is jump-if-true: if the first parameter is non-zero, it sets the
* instruction pointer to the value from the second parameter.
* Otherwise, it does nothing
*/
export const jumpIfTrue = (opcode: number[], pointer: number) => {
const { parameter1, parameter2 } = getParameters(opcode, pointer);
return parameter1 !== 0 ? parameter2 : pointer + 3;
};
export const jumpIfFalse = (opcode: number[], pointer: number) => {
const { parameter1, parameter2 } = getParameters(opcode, pointer);
return parameter1 !== 0 ? pointer + 3 : parameter2;
};
export const lessThan = (opcode: number[], pointer: number) => {
const { parameter1, parameter2 } = getParameters(opcode, pointer);
const output = parameter1 < parameter2 ? 1 : 0;
const newOpcode = setOutput(opcode, pointer, output);
return newOpcode;
};
export const equals = (opcode: number[], pointer: number) => {
const { parameter1, parameter2 } = getParameters(opcode, pointer);
const output = parameter1 === parameter2 ? 1 : 0;
const newOpcode = setOutput(opcode, pointer, output);
return newOpcode;
};
|
33f69d980f5e716f29584311aa49737c6a2b8058
|
TypeScript
|
rogermedico/activities-app
|
/src/app/shared/store/user/user.reducer.ts
| 2.515625
| 3
|
import { UserState } from './user.state';
import * as UserActions from './user.action';
import { Action, createReducer, on } from '@ngrx/store';
/* the auth state starts with no one logged in */
const defaultUserState: UserState = {
user: null,
loading: false,
loaded: true,
edited: false,
saved: false,
profileEdit: false,
educationCreate: false,
educationEdit: false,
educationDelete: false,
languageCreate: false,
languageEdit: false,
languageDelete: false,
error: null
};
const _userReducer = createReducer(defaultUserState,
/* signin */
on(UserActions.UserSignin, state => {
return {
...state,
loading: true, loaded: false,
error: null
}
}),
/* signin success */
on(UserActions.UserSigninSuccess, (state, { user }) => {
return {
...state,
user: user,
loading: false,
loaded: true,
error: null
}
}),
/* signin error */
on(UserActions.UserSigninError, (state, { err }) => {
return {
...state,
loading: false,
loaded: true,
error: err
}
}),
/* signout */
on(UserActions.UserSignout, state => {
return {
...state,
loading: true,
loaded: false,
error: null
}
}),
/* signout success */
on(UserActions.UserSignoutSuccess, state => {
return {
...state,
user: null,
loading: false,
loaded: true,
error: null
}
}),
/* signout error */
on(UserActions.UserSignoutError, (state, { err }) => {
return {
...state,
loading: false,
loaded: true,
error: err
}
}),
/* modify profile */
on(UserActions.UserModifyPersonalData, state => {
return {
...state,
loading: true,
loaded: false,
profileEdit: false,
educationCreate: false,
educationEdit: false,
educationDelete: false,
languageCreate: false,
languageEdit: false,
languageDelete: false,
error: null
}
}),
/* modify profile success */
on(UserActions.UserModifyPersonalDataSuccess, state => {
return {
...state,
loading: false,
loaded: true,
edited: true,
saved: false,
error: null
}
}),
/* modify profile error */
on(UserActions.UserModifyPersonalDataError, (state, { err }) => {
return {
...state,
loading: false,
loaded: true,
error: err
}
}),
/* discard profile changes */
on(UserActions.UserDiscardPersonalDataChanges, state => {
return {
...state,
loading: true,
loaded: false,
profileEdit: false,
educationCreate: false,
educationEdit: false,
educationDelete: false,
languageCreate: false,
languageEdit: false,
languageDelete: false,
error: null
}
}),
/* discard profile changes success */
on(UserActions.UserDiscardPersonalDataChangesSuccess, state => {
return {
...state,
loading: false,
loaded: true,
edited: false,
saved: true,
error: null
}
}),
/* discard profile changes error */
on(UserActions.UserDiscardPersonalDataChangesError, (state, { err }) => {
return {
...state,
loading: false,
loaded: true,
error: err
}
}),
/* update profile */
on(UserActions.UserUpdatePersonalData, state => {
return {
...state,
loading: true,
loaded: false,
profileEdit: false,
educationCreate: false,
educationEdit: false,
educationDelete: false,
languageCreate: false,
languageEdit: false,
languageDelete: false,
error: null
}
}),
/* update profile success */
on(UserActions.UserUpdatePersonalDataSuccess, (state, { user }) => {
return {
...state,
user: user,
loading: false,
loaded: true,
edited: false,
saved: true,
profileEdit: true,
educationCreate: false,
educationEdit: false,
educationDelete: false,
languageCreate: false,
languageEdit: false,
languageDelete: false,
error: null
}
}),
/* update profile error */
on(UserActions.UserUpdatePersonalDataError, (state, { err }) => {
return {
...state,
loading: false,
loaded: true,
error: err
}
}),
/* create language */
on(UserActions.UserCreateLanguage, state => {
return {
...state,
loading: true,
loaded: false,
profileEdit: false,
educationCreate: false,
educationEdit: false,
educationDelete: false,
languageCreate: false,
languageEdit: false,
languageDelete: false,
error: null
}
}),
/* create language success */
on(UserActions.UserCreateLanguageSuccess, (state, { user }) => {
return {
...state,
user: user,
loading: false,
loaded: true,
profileEdit: false,
educationCreate: false,
educationEdit: false,
educationDelete: false,
languageCreate: true,
languageEdit: false,
languageDelete: false,
error: null
}
}),
/* create language error */
on(UserActions.UserCreateLanguageError, (state, { err }) => {
return {
...state,
loading: false,
loaded: true,
error: err
}
}),
/* update language */
on(UserActions.UserUpdateLanguage, state => {
return {
...state,
loading: true,
loaded: false,
profileEdit: false,
educationCreate: false,
educationEdit: false,
educationDelete: false,
languageCreate: false,
languageEdit: false,
languageDelete: false,
error: null
}
}),
/* update language success */
on(UserActions.UserUpdateLanguageSuccess, (state, { user }) => {
return {
...state,
user: user,
loading: false,
loaded: true,
profileEdit: false,
educationCreate: false,
educationEdit: false,
educationDelete: false,
languageCreate: false,
languageEdit: true,
languageDelete: false,
error: null
}
}),
/* update language error */
on(UserActions.UserUpdateLanguageError, (state, { err }) => {
return {
...state,
loading: false,
loaded: true,
error: err
}
}),
/* delete language */
on(UserActions.UserDeleteLanguage, state => {
return {
...state,
loading: true,
loaded: false,
profileEdit: false,
educationCreate: false,
educationEdit: false,
educationDelete: false,
languageCreate: false,
languageEdit: false,
languageDelete: false,
error: null
}
}),
/* delete language success */
on(UserActions.UserDeleteLanguageSuccess, (state, { user }) => {
return {
...state,
user: user,
loading: false,
loaded: true,
profileEdit: false,
educationCreate: false,
educationEdit: false,
educationDelete: false,
languageCreate: false,
languageEdit: false,
languageDelete: true,
error: null
}
}),
/* delete language error */
on(UserActions.UserDeleteLanguageError, (state, { err }) => {
return {
...state,
loading: false,
loaded: true,
error: err
}
}),
/* create education */
on(UserActions.UserCreateEducation, state => {
return {
...state,
loading: true,
loaded: false,
profileEdit: false,
educationCreate: false,
educationEdit: false,
educationDelete: false,
languageCreate: false,
languageEdit: false,
languageDelete: false,
error: null
}
}),
/* create education success */
on(UserActions.UserCreateEducationSuccess, (state, { user }) => {
return {
...state,
user: user,
loading: false,
loaded: true,
profileEdit: false,
educationCreate: true,
educationEdit: false,
educationDelete: false,
languageCreate: false,
languageEdit: false,
languageDelete: false,
error: null
}
}),
/* create education error */
on(UserActions.UserCreateEducationError, (state, { err }) => {
return {
...state,
loading: false,
loaded: true,
error: err
}
}),
/* update education */
on(UserActions.UserUpdateEducation, state => {
return {
...state,
loading: true,
loaded: false,
profileEdit: false,
educationCreate: false,
educationEdit: false,
educationDelete: false,
languageCreate: false,
languageEdit: false,
languageDelete: false,
error: null
}
}),
/* update education success */
on(UserActions.UserUpdateEducationSuccess, (state, { user }) => {
return {
...state,
user: user,
loading: false,
loaded: true,
profileEdit: false,
educationCreate: false,
educationEdit: true,
educationDelete: false,
languageCreate: false,
languageEdit: false,
languageDelete: false,
error: null
}
}),
/* update education error */
on(UserActions.UserUpdateEducationError, (state, { err }) => {
return {
...state,
loading: false,
loaded: true,
error: err
}
}),
/* delete education */
on(UserActions.UserDeleteEducation, state => {
return {
...state,
loading: true,
loaded: false,
profileEdit: false,
educationCreate: false,
educationEdit: false,
educationDelete: false,
languageCreate: false,
languageEdit: false,
languageDelete: false,
error: null
}
}),
/* delete education success */
on(UserActions.UserDeleteEducationSuccess, (state, { user }) => {
return {
...state,
user: user,
loading: false,
loaded: true,
profileEdit: false,
educationCreate: false,
educationEdit: false,
educationDelete: true,
languageCreate: false,
languageEdit: false,
languageDelete: false,
error: null
}
}),
/* delete education error */
on(UserActions.UserDeleteEducationError, (state, { err }) => {
return {
...state,
loading: false,
loaded: true,
error: err
}
}),
/* load favorite activities */
on(UserActions.UserLoadFavoriteActivities, state => {
return {
...state,
loading: true,
loaded: false,
error: null
}
}),
/* load favorite activities success */
on(UserActions.UserLoadFavoriteActivitiesSuccess, (state, { favoriteActivities }) => {
return {
...state,
user: {
...state.user,
favoriteActivities: favoriteActivities
},
loading: false,
loaded: true,
error: null
}
}),
/* load favorite activities error */
on(UserActions.UserLoadFavoriteActivitiesError, (state, { err }) => {
return {
...state,
loading: false,
loaded: true,
error: err
}
}),
/* toggle favorite activity */
on(UserActions.UserToggleFavoriteActivity, state => {
return {
...state,
loading: true,
loaded: false,
error: null
}
}),
/* toggle favorite activity success */
on(UserActions.UserToggleFavoriteActivitySuccess, (state, { favoriteActivities }) => {
return {
...state,
user: {
...state.user,
favoriteActivities: favoriteActivities
},
loading: false,
loaded: true,
error: null
}
}),
/* toggle favorite activity error */
on(UserActions.UserToggleFavoriteActivityError, (state, { err }) => {
return {
...state,
loading: false,
loaded: true,
error: err
}
}),
/* reset flags */
on(UserActions.UserResetFlags, (state) => {
return {
...state,
profileEdit: false,
educationCreate: false,
educationEdit: false,
educationDelete: false,
languageCreate: false,
languageEdit: false,
languageDelete: false
}
})
);
export function userReducer(state: UserState | undefined, action: Action) {
return _userReducer(state, action);
}
|
9086412873c99b66740b4ae246c23088608b1e00
|
TypeScript
|
TamuzGroup/node-express-typescript-boilerplate
|
/src/models/token.model.ts
| 2.71875
| 3
|
import { model, Document, Schema, Types, Model } from 'mongoose';
import toJSON from './plugins/toJSON.plugin';
import TokenTypes from '../config/tokens';
export interface IToken {
token: string;
user: Types.ObjectId;
type: string;
expires: string;
blacklisted: boolean;
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface ITokenModel extends Model<IToken, Record<string, never>, Record<string, never>> {}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type ITokenDoc = IToken & Document<Record<string, any>, Record<string, never>, IToken>;
const tokenSchema = new Schema<IToken, ITokenModel>(
{
token: {
type: String,
required: true,
index: true,
},
user: {
type: Types.ObjectId,
ref: 'User',
required: true,
},
type: {
type: String,
enum: [TokenTypes.REFRESH, TokenTypes.RESET_PASSWORD, TokenTypes.VERIFY_EMAIL],
required: true,
},
expires: {
type: Date,
required: true,
},
blacklisted: {
type: Boolean,
default: false,
},
},
{
timestamps: true,
}
);
// add plugin that converts mongoose to json
tokenSchema.plugin(toJSON);
/**
* @typedef Token
*/
const TokenModel: ITokenModel = model<IToken>('Token', tokenSchema);
export default TokenModel;
|
68327735ed3d9b9b0c78aec7527b86c1e61d3d38
|
TypeScript
|
capricorn86/happy-dom
|
/packages/happy-dom/test/nodes/node/Node.test.ts
| 2.984375
| 3
|
import Window from '../../../src/window/Window.js';
import IWindow from '../../../src/window/IWindow.js';
import IDocument from '../../../src/nodes/document/IDocument.js';
import Node from '../../../src/nodes/node/Node.js';
import HTMLElement from '../../../src/nodes/html-element/HTMLElement.js';
import HTMLTemplateElement from '../../../src/nodes/html-template-element/HTMLTemplateElement.js';
import Event from '../../../src/event/Event.js';
import DOMException from '../../../src/exception/DOMException.js';
import DOMExceptionNameEnum from '../../../src/exception/DOMExceptionNameEnum.js';
import Text from '../../../src/nodes/text/Text.js';
import EventPhaseEnum from '../../../src/event/EventPhaseEnum.js';
import { beforeEach, describe, it, expect } from 'vitest';
/**
*
*/
class CustomCounterElement extends HTMLElement {
public static output: string[] = [];
/**
* Constructor.
*/
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
/**
* Connected.
*/
public connectedCallback(): void {
this.shadowRoot.innerHTML = '<div><span>Test</span></div>';
(<typeof CustomCounterElement>this.constructor).output.push('Counter:connected');
}
/**
* Disconnected.
*/
public disconnectedCallback(): void {
(<typeof CustomCounterElement>this.constructor).output.push('Counter:disconnected');
}
}
/**
*
*/
class CustomButtonElement extends HTMLElement {
public static output: string[] = [];
/**
* Connected.
*/
public connectedCallback(): void {
(<typeof CustomButtonElement>this.constructor).output.push('Button:connected');
}
/**
* Disconnected.
*/
public disconnectedCallback(): void {
(<typeof CustomButtonElement>this.constructor).output.push('Button:disconnected');
}
}
describe('Node', () => {
let window: IWindow;
let document: IDocument;
let customElementOutput;
beforeEach(() => {
window = new Window();
document = window.document;
customElementOutput = [];
CustomCounterElement.output = customElementOutput;
CustomButtonElement.output = customElementOutput;
window.customElements.define('custom-counter', CustomCounterElement);
window.customElements.define('custom-button', CustomButtonElement);
});
describe('get isConnected()', () => {
it('Returns "true" if the node is connected to the document.', () => {
const div = document.createElement('div');
const span = document.createElement('span');
const text = document.createTextNode('text');
div.appendChild(span);
span.appendChild(text);
expect(div.isConnected).toBe(false);
expect(span.isConnected).toBe(false);
expect(text.isConnected).toBe(false);
document.body.appendChild(div);
expect(div.isConnected).toBe(true);
expect(span.isConnected).toBe(true);
expect(text.isConnected).toBe(true);
});
});
describe('get childNodes()', () => {
it('Returns child nodes.', () => {
const div = document.createElement('div');
const span = document.createElement('span');
const text = document.createTextNode('text');
const comment = document.createComment('comment');
div.appendChild(span);
div.appendChild(text);
div.appendChild(comment);
expect(div.childNodes.length).toBe(3);
expect(div.childNodes[0] === span).toBe(true);
expect(div.childNodes[1] === text).toBe(true);
expect(div.childNodes[2] === comment).toBe(true);
});
it('Is a getter.', () => {
expect(typeof Object.getOwnPropertyDescriptor(Node.prototype, 'childNodes')?.get).toBe(
'function'
);
});
});
describe('get nodeValue()', () => {
it('Returns null.', () => {
expect(new Node().nodeValue).toBe(null);
});
});
describe('get nodeName()', () => {
it('Returns emptry string.', () => {
expect(new Node().nodeName).toBe('');
});
});
describe('get previousSibling()', () => {
it('Returns previous sibling.', () => {
const div = document.createElement('div');
const span1 = document.createElement('span');
const span2 = document.createElement('span');
const text = document.createTextNode('text');
div.appendChild(span1);
div.appendChild(text);
div.appendChild(span2);
expect(span2.previousSibling).toBe(text);
});
});
describe('get nextSibling()', () => {
it('Returns next sibling.', () => {
const div = document.createElement('div');
const span1 = document.createElement('span');
const span2 = document.createElement('span');
const text = document.createTextNode('text');
div.appendChild(span1);
div.appendChild(text);
div.appendChild(span2);
expect(text.nextSibling).toBe(span2);
});
});
describe('get firstChild()', () => {
it('Returns the first child node.', () => {
const div = document.createElement('div');
const span1 = document.createElement('span');
const span2 = document.createElement('span');
const text = document.createTextNode('text');
div.appendChild(span1);
div.appendChild(text);
div.appendChild(span2);
expect(div.firstChild).toBe(span1);
});
});
describe('get lastChild()', () => {
it('Returns the last child node.', () => {
const div = document.createElement('div');
const span1 = document.createElement('span');
const span2 = document.createElement('span');
const text = document.createTextNode('text');
div.appendChild(span1);
div.appendChild(text);
div.appendChild(span2);
expect(div.lastChild).toBe(span2);
});
});
describe('get parentElement()', () => {
it('Returns parent element.', () => {
const div = document.createElement('div');
const span1 = document.createElement('span');
const text = document.createTextNode('text');
span1.appendChild(text);
div.appendChild(span1);
expect(text.parentElement).toBe(span1);
});
it('Returns document element.', () => {
const text1 = document.createTextNode('text1');
const text2 = document.createTextNode('text2');
const text3 = document.createTextNode('text3');
text1.appendChild(text2);
text2.appendChild(text3);
document.documentElement.appendChild(text1);
expect(text3.parentElement).toBe(document.documentElement);
});
it('Returns null if there is no parent node.', () => {
const text = document.createTextNode('text');
expect(text.parentElement).toBe(null);
});
it('Returns null if parent node is not an element.', () => {
const htmlElement = document.createElement('html');
document.appendChild(htmlElement);
expect(htmlElement.parentNode).toBe(document);
expect(htmlElement.parentElement).toBe(null);
});
});
describe('get baseURI()', () => {
it('Returns location.href.', () => {
document.location.href = 'https://localhost:8080/base/path/to/script/?key=value=1#test';
const div = document.createElement('div');
expect(div.baseURI).toBe('https://localhost:8080/base/path/to/script/?key=value=1#test');
});
it('Returns the "href" attribute set on a <base> element.', () => {
document.location.href = 'https://localhost:8080/base/path/to/script/?key=value=1#test';
const base = document.createElement('base');
base.setAttribute('href', 'https://www.test.test/base/path/to/script/?key=value=1#test');
document.documentElement.appendChild(base);
const div = document.createElement('div');
expect(div.baseURI).toBe('https://www.test.test/base/path/to/script/?key=value=1#test');
});
});
describe('connectedCallback()', () => {
it('Calls connected callback when a custom element is connected to DOM.', () => {
document.body.innerHTML = '<custom-counter><custom-button></custom-button></custom-counter>';
document.body.innerHTML = '';
expect(customElementOutput).toEqual([
'Counter:connected',
'Button:connected',
'Counter:disconnected',
'Button:disconnected'
]);
});
});
describe('disconnectedCallback()', () => {
it('Calls disconnected callback when a custom element is connected to DOM.', () => {
const customElement = document.createElement('custom-counter');
let isConnected = false;
let isDisconnected = false;
customElement.connectedCallback = () => {
isConnected = true;
};
customElement.disconnectedCallback = () => {
isDisconnected = true;
};
document.body.appendChild(customElement);
expect(isConnected).toBe(true);
expect(isDisconnected).toBe(false);
document.body.removeChild(customElement);
expect(isDisconnected).toBe(true);
});
});
describe('hasChildNodes()', () => {
it('Returns "true" if the Node has child nodes.', () => {
const parent = document.createElement('div');
const child = document.createElement('span');
expect(parent.hasChildNodes()).toBe(false);
parent.appendChild(child);
expect(parent.hasChildNodes()).toBe(true);
});
});
describe('contains()', () => {
it('Returns "true" if a node contains another node.', () => {
const div = document.createElement('div');
const span1 = document.createElement('span');
const span2 = document.createElement('span');
const text = document.createTextNode('text');
div.appendChild(span1);
div.appendChild(span2);
expect(div.contains(text)).toBe(false);
span2.appendChild(text);
expect(div.contains(text)).toBe(true);
});
it('Returns "false" if match node is null.', () => {
const div = document.createElement('div');
expect(div.contains(null)).toBe(false);
});
});
describe('getRootNode()', () => {
it('Returns ShadowRoot when used on a node inside a ShadowRoot.', () => {
const customElement = document.createElement('custom-counter');
document.body.appendChild(customElement);
const rootNode = customElement.shadowRoot.querySelector('span').getRootNode();
expect(rootNode === customElement.shadowRoot).toBe(true);
});
it('Returns Document when used on a node inside a ShadowRoot and the option "composed" is set to "true".', () => {
const customElement = document.createElement('custom-counter');
document.body.appendChild(customElement);
const rootNode = customElement.shadowRoot
.querySelector('span')
.getRootNode({ composed: true });
expect(rootNode === document).toBe(true);
});
it('Returns Document when the node is not inside a ShadowRoot.', () => {
const divElement = document.createElement('div');
const spanElement = document.createElement('span');
divElement.appendChild(spanElement);
document.body.appendChild(divElement);
const rootNode = spanElement.getRootNode();
expect(rootNode === document).toBe(true);
});
it('Returns Document when called on Document', () => {
expect(document.getRootNode() === document).toBe(true);
});
});
describe('cloneNode()', () => {
it('Makes a shallow clone of a node (default behavior).', () => {
const div = document.createElement('div');
const span = document.createElement('span');
const text = document.createTextNode('text');
const comment = document.createComment('comment');
div.appendChild(span);
span.appendChild(text);
span.appendChild(comment);
document.body.appendChild(div);
const clone = div.cloneNode();
document.body.removeChild(div);
div.removeChild(span);
expect(div).toEqual(clone);
expect(div !== clone).toBe(true);
});
it('Makes a deep clone of a node.', () => {
const div = document.createElement('div');
const span = document.createElement('span');
const text = document.createTextNode('text');
const comment = document.createComment('comment');
div.appendChild(span);
span.appendChild(text);
span.appendChild(comment);
document.body.appendChild(div);
const clone = div.cloneNode(true);
document.body.removeChild(div);
expect(div).toEqual(clone);
expect(div !== clone).toBe(true);
expect(Array.from(clone.children)).toEqual(
Array.from(clone.childNodes.filter((node) => node.nodeType === Node.ELEMENT_NODE))
);
});
});
describe('appendChild()', () => {
it('Appends an Node to another Node.', () => {
const child = document.createElement('span');
const parent1 = document.createElement('div');
const parent2 = document.createElement('div');
parent1.appendChild(child);
expect(child.parentNode).toBe(parent1);
expect(Array.from(parent1.childNodes)).toEqual([child]);
parent2.appendChild(child);
expect(child.parentNode).toBe(parent2);
expect(Array.from(parent1.childNodes)).toEqual([]);
expect(Array.from(parent2.childNodes)).toEqual([child]);
expect(child.isConnected).toBe(false);
document.body.appendChild(parent2);
expect(child.isConnected).toBe(true);
});
// See: https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment
it('Append the child nodes instead of the actual node if the type is DocumentFragment.', () => {
const template = <HTMLTemplateElement>document.createElement('template');
template.innerHTML = '<div>Div</div><span>Span</span>';
const div = document.createElement('div');
const clone = template.content.cloneNode(true);
div.appendChild(clone);
expect(Array.from(clone.childNodes)).toEqual([]);
expect(div.innerHTML).toBe('<div>Div</div><span>Span</span>');
});
it('Throws an error if the node to append is the parent of the current node.', () => {
const parent = document.createElement('div');
const child1 = document.createElement('div');
const child2 = document.createElement('div');
child1.appendChild(child2);
parent.appendChild(child1);
try {
child2.appendChild(parent);
} catch (error) {
expect(error).toEqual(
new DOMException(
"Failed to execute 'appendChild' on 'Node': The new node is a parent of the node to insert to.",
DOMExceptionNameEnum.domException
)
);
}
});
});
describe('removeChild()', () => {
it('Removes a child Node from its parent and returns a reference to a removed node.', () => {
const child = document.createElement('span');
const parent = document.createElement('div');
parent.appendChild(child);
expect(child.parentNode).toBe(parent);
expect(Array.from(parent.childNodes)).toEqual([child]);
expect(child.isConnected).toBe(false);
document.body.appendChild(parent);
expect(child.isConnected).toBe(true);
const removed = parent.removeChild(child);
expect(child.parentNode).toBe(null);
expect(Array.from(parent.childNodes)).toEqual([]);
expect(child.isConnected).toBe(false);
expect(removed).toEqual(child);
});
});
describe('insertBefore()', () => {
it('Inserts a Node before another reference Node.', () => {
const child1 = document.createElement('span');
const child2 = document.createElement('span');
const newNode = document.createElement('span');
const parent = document.createElement('div');
parent.appendChild(child1);
parent.appendChild(child2);
parent.insertBefore(newNode, child2);
expect(newNode.parentNode).toBe(parent);
expect(Array.from(parent.childNodes)).toEqual([child1, newNode, child2]);
expect(newNode.isConnected).toBe(false);
document.body.appendChild(parent);
expect(newNode.isConnected).toBe(true);
});
// See: https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment
it('Insert the child nodes instead of the actual node before another reference Node if the type is DocumentFragment.', () => {
const child1 = document.createElement('span');
const child2 = document.createElement('span');
const template = <HTMLTemplateElement>document.createElement('template');
const parent = document.createElement('div');
template.innerHTML = '<div>Template DIV 1</div><span>Template SPAN 1</span>';
const clone = template.content.cloneNode(true);
parent.appendChild(child1);
parent.appendChild(child2);
parent.insertBefore(clone, child2);
expect(parent.innerHTML).toEqual(
'<span></span><div>Template DIV 1</div><span>Template SPAN 1</span><span></span>'
);
});
it('Inserts a Node after all children if reference node is "null".', () => {
const child1 = document.createElement('span');
const child2 = document.createElement('span');
const newNode = document.createElement('span');
const parent = document.createElement('div');
parent.appendChild(child1);
parent.appendChild(child2);
parent.insertBefore(newNode, null);
expect(parent.childNodes[0]).toBe(child1);
expect(parent.childNodes[1]).toBe(child2);
expect(parent.childNodes[2]).toBe(newNode);
expect(newNode.isConnected).toBe(false);
document.body.appendChild(parent);
expect(newNode.isConnected).toBe(true);
});
it('Throws an exception if reference node is node sent.', () => {
const child1 = document.createElement('span');
const child2 = document.createElement('span');
const newNode = document.createElement('span');
const parent = document.createElement('div');
parent.appendChild(child1);
parent.appendChild(child2);
expect(() => parent.insertBefore(newNode)).toThrow(
"Failed to execute 'insertBefore' on 'Node': 2 arguments required, but only 1 present."
);
});
it('If reference node is null or undefined, the newNode should be inserted at the end of the peer node.', () => {
const child1 = document.createElement('span');
const child2 = document.createElement('span');
const newNode = document.createElement('span');
const newNode1 = document.createElement('span');
const parent = document.createElement('div');
parent.appendChild(child1);
parent.appendChild(child2);
parent.insertBefore(newNode, null);
parent.insertBefore(newNode1, undefined);
expect(parent.childNodes[0]).toBe(child1);
expect(parent.childNodes[1]).toBe(child2);
expect(parent.childNodes[2]).toBe(newNode);
expect(parent.childNodes[3]).toBe(newNode1);
});
it('Throws an exception if reference node is not child of parent node.', () => {
const referenceNode = document.createElement('span');
const newNode = document.createElement('span');
const parent = document.createElement('div');
expect(() => parent.insertBefore(newNode, referenceNode)).toThrow(
"Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node."
);
});
it('Throws an error if the node to insert is the parent of the current node.', () => {
const parent = document.createElement('div');
const child1 = document.createElement('div');
const child2 = document.createElement('div');
child1.appendChild(child2);
parent.appendChild(child1);
try {
child2.insertBefore(parent, null);
} catch (error) {
expect(error).toEqual(
new DOMException(
"Failed to execute 'insertBefore' on 'Node': The new node is a parent of the node to insert to.",
DOMExceptionNameEnum.domException
)
);
}
});
});
describe('replaceChild()', () => {
it('Inserts a Node before another reference Node.', () => {
const child1 = document.createElement('span');
const child2 = document.createElement('span');
const newNode = document.createElement('span');
const parent = document.createElement('div');
parent.appendChild(child1);
parent.appendChild(child2);
parent.replaceChild(newNode, child2);
expect(newNode.parentNode).toBe(parent);
expect(Array.from(parent.childNodes)).toEqual([child1, newNode]);
expect(newNode.isConnected).toBe(false);
document.body.appendChild(parent);
expect(newNode.isConnected).toBe(true);
});
});
describe('dispatchEvent()', () => {
it('Dispatches an event that is set to not bubble.', () => {
const child = document.createElement('span');
const parent = document.createElement('div');
const event = new Event('click', { bubbles: false });
let childEvent: Event | null = null;
let parentEvent: Event | null = null;
parent.appendChild(child);
child.addEventListener('click', (event) => (childEvent = event));
parent.addEventListener('click', (event) => (parentEvent = event));
expect(child.dispatchEvent(event)).toBe(true);
expect(childEvent).toBe(event);
expect((<Event>(<unknown>childEvent)).target).toBe(child);
expect((<Event>(<unknown>childEvent)).currentTarget).toBe(child);
expect(parentEvent).toBe(null);
});
it('Dispatches an event that is set to bubble.', () => {
const child = document.createElement('span');
const parent = document.createElement('div');
const event = new Event('click', { bubbles: true });
let childEvent: Event | null = null;
let parentEvent: Event | null = null;
parent.appendChild(child);
child.addEventListener('click', (event) => (childEvent = event));
parent.addEventListener('click', (event) => (parentEvent = event));
expect(child.dispatchEvent(event)).toBe(true);
expect(childEvent).toBe(event);
expect(parentEvent).toBe(event);
expect((<Event>(<unknown>parentEvent)).target).toBe(child);
expect((<Event>(<unknown>parentEvent)).currentTarget).toBe(parent);
});
it('Does not bubble to parent if propagation is stopped.', () => {
const child = document.createElement('span');
const parent = document.createElement('div');
const event = new Event('click', { bubbles: false });
let childEvent: Event | null = null;
let parentEvent: Event | null = null;
parent.appendChild(child);
child.addEventListener('click', (event) => {
event.stopPropagation();
childEvent = event;
});
parent.addEventListener('click', (event) => (parentEvent = event));
expect(child.dispatchEvent(event)).toBe(true);
expect(childEvent).toBe(event);
expect(parentEvent).toBe(null);
});
it('Returns false if preventDefault() is called and the event is cancelable.', () => {
const child = document.createElement('span');
const parent = document.createElement('div');
const event = new Event('click', { bubbles: true, cancelable: true });
let childEvent: Event | null = null;
let parentEvent: Event | null = null;
parent.appendChild(child);
child.addEventListener('click', (event) => {
event.preventDefault();
childEvent = event;
});
parent.addEventListener('click', (event) => (parentEvent = event));
expect(child.dispatchEvent(event)).toBe(false);
expect(childEvent).toBe(event);
expect(parentEvent).toBe(event);
});
it('Supports capture events that are not bubbles.', () => {
const parent = document.createElement('div');
const child1 = document.createElement('span');
const child2 = document.createElement('span');
child1.appendChild(child2);
parent.appendChild(child1);
const event = new Event('blur', { bubbles: false, cancelable: true });
const parentEvents: Event[] = [];
const child1Events: Event[] = [];
const child2Events: Event[] = [];
parent.addEventListener(
'blur',
(event) => {
expect(event.eventPhase).toBe(EventPhaseEnum.capturing);
parentEvents.push(event);
},
true
);
child1.addEventListener('blur', (event) => {
expect(event.eventPhase).toBe(EventPhaseEnum.bubbling);
child1Events.push(event);
});
child2.addEventListener('blur', (event) => {
expect(event.eventPhase).toBe(EventPhaseEnum.atTarget);
child2Events.push(event);
});
child2.dispatchEvent(event);
expect(child1Events.length).toBe(0);
expect(child2Events.length).toBe(1);
expect(child2Events[0] === event).toBe(true);
expect(parentEvents.length).toBe(1);
expect(parentEvents[0] === event).toBe(true);
});
it('Supports capture events that bubbles.', () => {
const parent = document.createElement('div');
const child1 = document.createElement('span');
const child2 = document.createElement('span');
child1.appendChild(child2);
parent.appendChild(child1);
const event = new Event('blur', { bubbles: true, cancelable: true });
const parentEvents: Event[] = [];
const child1Events: Event[] = [];
const child2Events: Event[] = [];
parent.addEventListener(
'blur',
(event) => {
expect(event.eventPhase).toBe(EventPhaseEnum.capturing);
parentEvents.push(event);
},
true
);
child1.addEventListener('blur', (event) => {
expect(event.eventPhase).toBe(EventPhaseEnum.bubbling);
child1Events.push(event);
});
child2.addEventListener('blur', (event) => {
expect(event.eventPhase).toBe(EventPhaseEnum.atTarget);
child2Events.push(event);
});
child2.dispatchEvent(event);
expect(child1Events.length).toBe(1);
expect(child1Events[0] === event).toBe(true);
expect(child2Events.length).toBe(1);
expect(child2Events[0] === event).toBe(true);
expect(parentEvents.length).toBe(1);
expect(parentEvents[0] === event).toBe(true);
});
it('Supports capture events on document simulating what Test Library is doing when listenening to "blur" and "focus".', () => {
const child1 = document.createElement('span');
const child2 = document.createElement('span');
child1.appendChild(child2);
document.body.appendChild(child1);
const event = new Event('blur', { bubbles: false, composed: true });
const documentEvents: Event[] = [];
const child1Events: Event[] = [];
const child2Events: Event[] = [];
document.addEventListener(
'blur',
(event) => {
expect(event.eventPhase).toBe(EventPhaseEnum.capturing);
documentEvents.push(event);
},
{
capture: true,
passive: true
}
);
child1.addEventListener('blur', (event) => {
expect(event.eventPhase).toBe(EventPhaseEnum.bubbling);
child1Events.push(event);
});
child2.addEventListener('blur', (event) => {
expect(event.eventPhase).toBe(EventPhaseEnum.atTarget);
child2Events.push(event);
});
child2.dispatchEvent(event);
expect(child1Events.length).toBe(0);
expect(child2Events.length).toBe(1);
expect(child2Events[0] === event).toBe(true);
expect(documentEvents.length).toBe(1);
expect(documentEvents[0] === event).toBe(true);
});
});
describe('compareDocumentPosition()', () => {
it('Returns 0 if b is a', () => {
const div = document.createElement('div');
div.id = 'element';
document.body.appendChild(div);
expect(
document
.getElementById('element')
.compareDocumentPosition(document.getElementById('element'))
).toEqual(0);
});
it('Returns 4 if b is following a', () => {
const div = document.createElement('div');
const span1 = document.createElement('span');
span1.id = 'span1';
const span2 = document.createElement('span');
span2.id = 'span2';
div.appendChild(span1);
div.appendChild(span2);
document.body.appendChild(div);
expect(
document.getElementById('span1').compareDocumentPosition(document.getElementById('span2'))
).toEqual(4);
});
it('Returns 2 if b is preceding a', () => {
const div = document.createElement('div');
const span1 = document.createElement('span');
span1.id = 'span1';
const span2 = document.createElement('span');
span2.id = 'span2';
div.appendChild(span1);
div.appendChild(span2);
document.body.appendChild(div);
expect(
document.getElementById('span2').compareDocumentPosition(document.getElementById('span1'))
).toEqual(2);
});
it('Returns 20 if b is contained by a', () => {
const div = document.createElement('div');
div.id = 'parent';
const span = document.createElement('span');
span.id = 'child';
div.appendChild(span);
document.body.appendChild(div);
const position = document
.getElementById('parent')
.compareDocumentPosition(document.getElementById('child'));
expect(position).toEqual(20);
});
it('Returns 10 if b contains a', () => {
const div = document.createElement('div');
div.id = 'parent';
const span = document.createElement('span');
span.id = 'child';
div.appendChild(span);
document.body.appendChild(div);
const position = document
.getElementById('child')
.compareDocumentPosition(document.getElementById('parent'));
expect(position).toEqual(10);
});
});
describe('normalize()', () => {
it('Normalizes an element.', () => {
const txt = document.createTextNode.bind(document);
const div = document.createElement('div');
const span = document.createElement('span');
span.append(txt('sp'), txt('an'));
const b = document.createElement('b');
b.append(txt(''), txt(''), txt(''));
div.append(txt(''), txt('d'), txt(''), txt('i'), txt('v'), span, txt(''), b, txt(''));
expect(div.childNodes).toHaveLength(9);
div.normalize();
expect(div.childNodes).toHaveLength(3);
expect(div.childNodes[0]).toBeInstanceOf(Text);
expect(div.childNodes[0].nodeValue).toBe('div');
expect(div.childNodes[1]).toBe(span);
expect(div.childNodes[2]).toBe(b);
expect(span.childNodes).toHaveLength(1);
expect(span.childNodes[0]).toBeInstanceOf(Text);
expect(span.childNodes[0].nodeValue).toBe('span');
expect(b.childNodes).toHaveLength(0);
});
it('Normalizes a document fragment.', () => {
const txt = document.createTextNode.bind(document);
const fragment = document.createDocumentFragment();
const span = document.createElement('span');
span.append(txt('sp'), txt('an'));
const b = document.createElement('b');
b.append(txt(''), txt(''), txt(''));
fragment.append(txt(''), txt('d'), txt(''), txt('i'), txt('v'), span, txt(''), b, txt(''));
expect(fragment.childNodes).toHaveLength(9);
fragment.normalize();
expect(fragment.childNodes).toHaveLength(3);
expect(fragment.childNodes[0]).toBeInstanceOf(Text);
expect(fragment.childNodes[0].nodeValue).toBe('div');
expect(fragment.childNodes[1]).toBe(span);
expect(fragment.childNodes[2]).toBe(b);
expect(span.childNodes).toHaveLength(1);
expect(span.childNodes[0]).toBeInstanceOf(Text);
expect(span.childNodes[0].nodeValue).toBe('span');
expect(b.childNodes).toHaveLength(0);
});
it('Normalizes the document.', () => {
const count = document.childNodes.length;
document.append(document.createTextNode(''));
expect(document.childNodes).toHaveLength(count + 1);
document.normalize();
expect(document.childNodes).toHaveLength(count);
});
it('Does nothing on a text node.', () => {
const div = document.createElement('div');
const node = div.appendChild(document.createTextNode(''));
node.normalize();
expect(div.childNodes).toHaveLength(1);
expect(div.childNodes[0]).toBe(node);
});
});
describe('isSameNode()', () => {
it('Returns true if the nodes are the same.', () => {
const div = document.createElement('div');
expect(div.isSameNode(div)).toBe(true);
});
it('Returns false if the nodes are not the same.', () => {
const div1 = document.createElement('div');
const div2 = document.createElement('div');
expect(div1.isSameNode(div2)).toBe(false);
});
});
});
|
315a851e771f131523487c6ee4fc6f81859ccfca
|
TypeScript
|
albertozaranza/alurabank
|
/ts/models/Negotiation.ts
| 2.78125
| 3
|
export class Negotiation {
private _date: Date;
private _amount: number;
private _value: number;
constructor(date: Date, amount: number, value: number) {
this._date = date;
this._amount = amount;
this._value = value;
}
get date() {
return this._date;
}
get amount() {
return this._amount;
}
get value() {
return this._value;
}
get volume() {
return this._value * this._amount;
}
}
|
30acc2a548ce9582c877ac3ee9f9800c5909b867
|
TypeScript
|
AndrewSChapman/pandapoker
|
/frontend/src/domains/room/store/roomStoreProvider.ts
| 2.65625
| 3
|
import { getBlankRoom, RoomItem } from '@/domains/room/interfaces/RoomItem';
import { Store } from 'vuex';
import { RoomVoteOptionItem } from '@/domains/room/interfaces/RoomVoteOptionItem';
import { CreateRoomActionParams } from '@/domains/room/interfaces/CreateRoomActionParams';
import { DeleteUserFromRoomActionParams } from '@/domains/room/interfaces/DeleteUserFromRoomActionParams';
export class RoomStoreProvider {
private store: Store<any>;
private roomStore: any;
constructor(store: Store<any>, roomStore: any) {
this.store = store;
this.roomStore = roomStore;
}
get errorMessage(): string {
if (this.hasError) {
return this.roomStore.error.message;
}
return '';
}
get hasError(): boolean {
return ((this.roomStore.error !== null) && (this.roomStore.error.hasOwnProperty('message'))
&& (this.roomStore.error.message.length > 0));
}
public get rooms(): RoomItem[] {
return this.roomStore.rooms;
}
public get roomVoteOptions(): RoomVoteOptionItem[] {
return this.roomStore.roomVoteOptions;
}
public get currentRoom(): RoomItem {
let room = this.roomStore.currentRoom;
if (room === null) {
room = getBlankRoom();
}
return room;
}
public async setCurrentRoom(room: RoomItem): Promise<void> {
await this.store.commit('setCurrentRoom', room);
}
public async setRoomOptionSelected(roomVoteOption: RoomVoteOptionItem): Promise<void> {
await this.store.commit('setRoomVoteOption', roomVoteOption);
}
public async setRoomVoteOptions(roomVoteOptions: RoomVoteOptionItem[]): Promise<void> {
await this.store.commit('setRoomVoteOptions', roomVoteOptions);
}
public async createRoom(roomName: string, roomVoteOptions: RoomVoteOptionItem[]): Promise<boolean> {
const params: CreateRoomActionParams = {
roomName,
roomVoteOptions,
};
await this.store.dispatch('createRoom', params);
if (this.hasError) {
return false;
}
await this.enterRoom(this.currentRoom.id);
return !this.hasError;
}
public async deleteUserFromRoom(roomId: string, userId: string): Promise<boolean> {
const params: DeleteUserFromRoomActionParams = {
roomId,
userId,
};
await this.store.dispatch('deleteUserFromRoom', params);
return !this.hasError;
}
public async exitCurrentRoom(userId: string): Promise<boolean> {
if (!this.currentRoom) {
return false;
}
const params: DeleteUserFromRoomActionParams = {
roomId: this.currentRoom.id,
userId,
};
await this.store.dispatch('deleteUserFromRoom', params);
return !this.hasError;
}
public async loadRooms(): Promise<void> {
await this.store.dispatch('loadRooms');
}
public getRoomById(roomId: string): RoomItem|null {
for (const room of this.rooms) {
if (room.id === roomId) {
return room;
}
}
return null;
}
public async enterRoom(roomId: string): Promise<boolean> {
await this.store.dispatch('enterRoom', roomId);
return !this.hasError;
}
public async openVoting(roomId: string): Promise<boolean> {
await this.store.dispatch('openVoting', roomId);
return !this.hasError;
}
public async closeVoting(roomId: string): Promise<boolean> {
await this.store.dispatch('closeVoting', roomId);
return !this.hasError;
}
public async resetVotes(roomId: string): Promise<boolean> {
await this.store.dispatch('resetVotes', roomId);
return !this.hasError;
}
public async vote(roomId: string, vote: number): Promise<boolean> {
await this.store.dispatch('vote', {
roomId,
vote,
});
return !this.hasError;
}
public async resetCurrentRoom(loggedInUserId: string): Promise<void> {
if (this.currentRoom && this.currentRoom.id.length > 1) {
await this.exitCurrentRoom(loggedInUserId);
}
const clearedRoomVoteOptions = this.roomVoteOptions.map((roomVoteOption) => {
roomVoteOption.selected = false;
return roomVoteOption;
});
this.setRoomVoteOptions(clearedRoomVoteOptions);
await this.store.commit('setCurrentRoom', null);
}
public async createRoomFromSocketEvent(roomItem: RoomItem): Promise<void> {
// The updateRoom mutation will add the room if it doesn't exist.
await this.store.commit('updateRoom', roomItem);
}
public async updateRoomFromSocketEvent(roomItem: RoomItem): Promise<void> {
await this.store.commit('updateRoom', roomItem);
if (this.currentRoom.id === roomItem.id) {
await this.setCurrentRoom(roomItem);
}
}
public async changeRoomOwnership(roomId: string): Promise<boolean> {
await this.store.dispatch('changeRoomOwnership', roomId);
return !this.hasError;
}
public async deleteCurrentRoom(): Promise<boolean> {
await this.store.dispatch('deleteCurrentRoom');
return !this.hasError;
}
public async handleRoomDeleted(roomId: string, loggedInUserId: string): Promise<void> {
await this.store.commit('deleteRoom', roomId);
await this.store.commit('setCurrentRoom', null);
}
}
|
2586b11cca9db1a1f0e25a4edf13d14e7be921c4
|
TypeScript
|
CVPhelan/commander-spellbook-api-wrapper
|
/test/unit/models/card.test.ts
| 2.90625
| 3
|
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import scryfall from "scryfall-client";
import Card from "../../../src/models/card";
describe("Card", () => {
it("has a name attribute", () => {
const card = new Card("Sydri, Galvanic Genius");
expect(card.name).toEqual("Sydri, Galvanic Genius");
});
describe("matchesName", () => {
it("returns true when the input is the name", () => {
const card = new Card("Sydri, Galvanic Genius");
expect(card.matchesName("Sydri, Galvanic Genius")).toBe(true);
expect(card.matchesName("Arjun, the Shifting Flame")).toBe(false);
});
it("returns true for partial matches", () => {
const card = new Card("Sydri, Galvanic Genius");
expect(card.matchesName("Sydri")).toBe(true);
expect(card.matchesName("alv")).toBe(true);
expect(card.matchesName("nius")).toBe(true);
});
it("disregards punctuation and casing", () => {
const card = new Card("Sydri, Galvanic Genius");
expect(card.matchesName("sYd~Ri G!alva??nIc GENIUS")).toBe(true);
});
});
describe("matchesNameExactly", () => {
it("returns true when the input is the name", () => {
const card = new Card("Sydri, Galvanic Genius");
expect(card.matchesNameExactly("Sydri, Galvanic Genius")).toBe(true);
expect(card.matchesNameExactly("Arjun, the Shifting Flame")).toBe(false);
});
it("returns false for partial matches", () => {
const card = new Card("Sydri, Galvanic Genius");
expect(card.matchesNameExactly("Sydri")).toBe(false);
});
it("disregards punctuation and casing", () => {
const card = new Card("Sydri, Galvanic Genius");
expect(card.matchesNameExactly("sYd~Ri G!alva??nIc GENIUS")).toBe(true);
});
});
describe("toString", () => {
it("returns the raw name", () => {
const card = new Card("Sydri, Galvanic Genius");
expect(card.toString()).toEqual("Sydri, Galvanic Genius");
expect(`text ${card} text`).toEqual("text Sydri, Galvanic Genius text");
});
});
describe("getScryfallData", () => {
it("calls out to scryfall.getCard", async () => {
const payload = {};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
jest.spyOn(scryfall, "getCard").mockResolvedValue(payload as any);
const card = new Card("Sydri, Galvanic Genius");
const scryfallResult = await card.getScryfallData();
expect(scryfallResult).toBe(payload);
expect(scryfall.getCard).toBeCalledTimes(1);
expect(scryfall.getCard).toBeCalledWith(
"Sydri, Galvanic Genius",
"exactName"
);
});
});
describe("getScryfallImageUrl", () => {
it("returns a url for the card image", () => {
const card = new Card("Sydri, Galvanic Genius");
expect(card.getScryfallImageUrl()).toBe(
"https://api.scryfall.com/cards/named?format=image&exact=Sydri%2C%20Galvanic%20Genius"
);
});
it("can pass a version string", () => {
const card = new Card("Sydri, Galvanic Genius");
expect(card.getScryfallImageUrl("art_crop")).toBe(
"https://api.scryfall.com/cards/named?format=image&exact=Sydri%2C%20Galvanic%20Genius&version=art_crop"
);
});
});
describe("toString", () => {
it("returns the raw name", () => {
const card = new Card("Sydri, Galvanic Genius");
expect(card.toString()).toEqual("Sydri, Galvanic Genius");
expect(`text ${card} text`).toEqual("text Sydri, Galvanic Genius text");
});
});
});
|
e15da1b633f59bd04ce58df33da8d3b7e8150db2
|
TypeScript
|
YIZHUANG/react-multi-carousel
|
/src/utils/next.ts
| 3.125
| 3
|
import { CarouselInternalState, CarouselProps } from "../types";
import { getSlidesToSlide } from "./common";
/*
two cases:
1. We are not over-sliding.
2. We are sliding over to what we have, that means nextslides > this.props.children.length. (does not apply to the inifnite mode)
*/
function populateNextSlides(
state: CarouselInternalState,
props: CarouselProps,
slidesHavePassed = 0
): {
nextSlides: number | undefined;
nextPosition: number | undefined;
} {
const { slidesToShow, currentSlide, itemWidth, totalItems } = state;
const slidesToSlide = getSlidesToSlide(state, props);
let nextSlides;
let nextPosition;
// possibile next number of slides that don't go over what we have, this doesn't apply to the infinite mode.
// because for inifnite mode this will never happen.
const nextMaximumSlides =
currentSlide +
1 +
slidesHavePassed +
slidesToShow +
(slidesHavePassed > 0 ? 0 : slidesToSlide!);
if (nextMaximumSlides <= totalItems) {
// It means if we have next slides go back to on the right-hand side.
nextSlides =
currentSlide +
slidesHavePassed +
(slidesHavePassed > 0 ? 0 : slidesToSlide!);
nextPosition = -(itemWidth * nextSlides);
} else if (
nextMaximumSlides > totalItems &&
currentSlide !== totalItems - slidesToShow
) {
// This is to prevent oversliding
// This is not for inifinite mode as for inifinite mode is never over-sliding.
nextSlides = totalItems - slidesToShow;
nextPosition = -(itemWidth * nextSlides);
} else {
nextSlides = undefined;
nextPosition = undefined;
}
return {
nextSlides,
nextPosition
};
}
export { populateNextSlides };
|
94a8a8158f8fdbd030fb39283a1771caa8376d92
|
TypeScript
|
SystemDevelopTraining/oic-sns
|
/server/src/domain/course/course.service.ts
| 2.515625
| 3
|
import { Course } from "../entities/course.entity";
import { Injectable, BadRequestException } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { CourseDto } from "../../../front/src/domain/course/CourseDto";
@Injectable()
export class CourseService {
constructor(
@InjectRepository(Course)
private readonly courseRepository: Repository<Course>,
) { }
//全ての専攻を取得する
async getCourses(): Promise<CourseDto[]> {
try {
const courses = await this.courseRepository.find();
return courses.map(x => ({ id: { id: x.id }, name: x.name }));
}
catch (e) {
throw new BadRequestException("専攻一覧取得に失敗しました");
}
}
}
|
666a4a7ad930ab3fe474e57e5b68fa8412af295c
|
TypeScript
|
kortkamp/ouvidoria-api
|
/src/__test__/unit/users/AuthenticateUserService.test.ts
| 2.6875
| 3
|
import CreateUserService from '@modules/users/services/CreateUserService';
import AuthenticateUserService from '@modules/users/services/AuthenticateUserService';
import FakeUsersRepository from '@modules/users/repositories/fakes/FakeUsersRepository';
let fakeUsersRepository:FakeUsersRepository;
let createUserService:CreateUserService;
let authenticateUserService:AuthenticateUserService;
const CreateUserRequest = {
name: 'user',
email: 'user@user.com',
password: '123456',
};
describe('AuthenticateUserService', () => {
beforeEach(async () => {
fakeUsersRepository = new FakeUsersRepository();
createUserService = new CreateUserService(fakeUsersRepository);
authenticateUserService = new AuthenticateUserService(fakeUsersRepository);
await createUserService.execute(CreateUserRequest);
});
it('Should be able to authenticate an user', async () => {
const { email, password } = CreateUserRequest;
const token = await authenticateUserService.execute({ email, password });
expect(token).toBeTruthy();
});
it('Should not be able to authenticate with wrong password', async () => {
await expect(
authenticateUserService.execute({ email: CreateUserRequest.email, password: 'wrong' }),
).rejects.toMatchObject({ statusCode: 401 });
});
it('Should not be able to authenticate with non existent user', async () => {
await expect(
authenticateUserService.execute({ email: 'not@exists.com', password: CreateUserRequest.password }),
).rejects.toMatchObject({ statusCode: 401 });
});
});
|
cb6ccd6fc121f8534bcdba8393815b58b5ca52bb
|
TypeScript
|
Karan-Munjani/graphique
|
/packages/graphique/src/util/directlyStyleNodes.ts
| 2.78125
| 3
|
import { CSSProperties } from 'react'
interface FocusProps {
nodes: HTMLCollectionOf<SVGElement>
focusedIndex: number | number[]
focusedStyles: CSSProperties
unfocusedStyles: CSSProperties
}
interface UnfocusProps {
nodes: HTMLCollectionOf<SVGElement>
baseStyles: CSSProperties
}
export const focusNodes = ({
nodes,
focusedIndex,
focusedStyles,
unfocusedStyles,
}: FocusProps) => {
const styleNodes = nodes
const focusedIndices = [focusedIndex].flat()
const toUnfocus = Array.from(nodes).filter(
(_, ind) => !focusedIndices.includes(ind)
)
toUnfocus.forEach((node) => {
const styleNode = node
Object.entries(unfocusedStyles).forEach(([key, val]) => {
styleNode.style[key as any] = val as string
})
})
Object.entries(focusedStyles).forEach(([key, val]) => {
focusedIndices.forEach((ind) => {
styleNodes[ind].style[key as any] = val as string
})
})
}
export const unfocusNodes = ({ nodes, baseStyles }: UnfocusProps) => {
Array.from(nodes).forEach((node) => {
const styleNode = node
Object.entries(baseStyles).forEach(([key, val]) => {
styleNode.style[key as any] = val as string
})
})
}
|
5a68911852471fe8e8c7c5c97b24f1e60dabaac9
|
TypeScript
|
sandeep12407/volte1
|
/lib/util.ts
| 2.765625
| 3
|
export const unwrap = <X>(x?: X | null, msg?: string): X => {
if (x === null || x === undefined) {
throw new Error(msg);
}
return x;
};
|
acdde2996f3234f2b226a84890b4441fcc6ea796
|
TypeScript
|
diego-rangel/ngx-ui-hero
|
/projects/ngx-ui-hero/src/lib/input-forms/directives/currency/input.manager.ts
| 2.8125
| 3
|
export class InputManager {
private _storedRawValue: string;
constructor(private htmlInputElement: any) {
}
setCursorAt(position: number): void {
if (this.htmlInputElement.setSelectionRange) {
this.htmlInputElement.focus();
this.htmlInputElement.setSelectionRange(position, position);
} else if (this.htmlInputElement.createTextRange) {
let textRange = this.htmlInputElement.createTextRange();
textRange.collapse(true);
textRange.moveEnd("character", position);
textRange.moveStart("character", position);
textRange.select();
}
}
updateValueAndCursor(newRawValue: string, oldLength: number, selectionStart: number): void {
this.rawValue = newRawValue;
let newLength = newRawValue.length;
selectionStart = selectionStart - (oldLength - newLength);
this.setCursorAt(selectionStart);
}
get canInputMoreNumbers(): boolean {
let haventReachedMaxLength = !(this.rawValue.length >= this.htmlInputElement.maxLength && this.htmlInputElement.maxLength >= 0);
let selectionStart = this.inputSelection.selectionStart;
let selectionEnd = this.inputSelection.selectionEnd;
let haveNumberSelected = (selectionStart != selectionEnd && this.htmlInputElement.value.substring(selectionStart, selectionEnd).match(/\d/)) ? true : false;
let startWithZero = (this.htmlInputElement.value.substring(0, 1) == "0");
return haventReachedMaxLength || haveNumberSelected || startWithZero;
}
get inputSelection(): any {
let selectionStart = 0;
let selectionEnd = 0;
if (typeof this.htmlInputElement.selectionStart == "number" && typeof this.htmlInputElement.selectionEnd == "number") {
selectionStart = this.htmlInputElement.selectionStart;
selectionEnd = this.htmlInputElement.selectionEnd;
} else {
let range = document.getSelection().anchorNode;
if (range && range.firstChild == this.htmlInputElement) {
let lenght = this.htmlInputElement.value.length;
let normalizedValue = this.htmlInputElement.value.replace(/\r\n/g, "\n");
let startRange = this.htmlInputElement.createTextRange();
let endRange = this.htmlInputElement.createTextRange();
endRange.collapse(false);
if (startRange.compareEndPoints("StartToEnd", endRange) > -1) {
selectionStart = selectionEnd = lenght;
} else {
selectionStart = -startRange.moveStart("character", -lenght);
selectionStart += normalizedValue.slice(0, selectionStart).split("\n").length - 1;
if (startRange.compareEndPoints("EndToEnd", endRange) > -1) {
selectionEnd = lenght;
} else {
selectionEnd = -startRange.moveEnd("character", -lenght);
selectionEnd += normalizedValue.slice(0, selectionEnd).split("\n").length - 1;
}
}
}
}
return {
selectionStart: selectionStart,
selectionEnd: selectionEnd
};
}
get rawValue(): string {
return this.htmlInputElement && this.htmlInputElement.value;
}
set rawValue(value: string) {
this._storedRawValue = value;
if (this.htmlInputElement) {
this.htmlInputElement.value = value;
}
}
get storedRawValue(): string {
return this._storedRawValue;
}
}
|
a48b3f6fe6d8e374bacd07ec3d62608d7dbafedb
|
TypeScript
|
nguoianphu/phaser3-flappybird
|
/src/ts/prefabs/bird.ts
| 2.828125
| 3
|
import { Physics } from 'phaser'
import { config } from '../config'
export default class Bird extends Physics.Arcade.Sprite implements FlappyBird {
// 不能使用game属性哦
private flySound: Phaser.Sound.BaseSound
private tween: Phaser.Tweens.Tween
constructor(scene, x, y, textureKey) {
super(scene, x, y, textureKey)
// TODO: 为什么不太容易动态修改setOrigin??
// 添加小鸟飞翔的声音
this.flySound = scene.sound.add('fly_sound')
this.setDepth(1)
}
// 注意: 并不是内置的方法
updateBird(scene) {
// 撞到柱子
if (this.active === false) return
// TODO:
if (this.y > 200 && this.angle < 20) {
this.angle += 1
}
// this.y < 0 || this.y > 490
if (this.y < 0) {
scene.hitPipe()
}
}
jump() {
let { birdFlapPower } = config
// 向上飞
let flapPower = 0 - birdFlapPower
this.setVelocityY(flapPower)
// 旋转
if (this.angle > -20) {
this.stopTween()
this.tween = this.scene.tweens.add({
targets: this,
angle: '-= 20',
duration: 100
})
}
// 播放声音
this.flySound.play()
}
headDroop() {
this.stopTween()
this.tween = this.scene.tweens.add({
targets: this,
duration: 500,
angle: 70
})
}
stopTween() {
if (this.tween) {
this.tween.stop()
this.tween = null
}
}
setG() {
let { birdGravity } = config
this.body.setGravityY(birdGravity)
}
}
|
ee5ba8a252617cbbd04cca6b4bd2d1daa3b32f5f
|
TypeScript
|
DivineCross/DesignPattern
|
/ts/src/mediator/client.ts
| 2.875
| 3
|
import { CutePetTrader } from './cute-pet-trader.js';
import { Pet } from './pet.js';
import { PetMediator } from './pet-mediator.js';
import { StrongPetTrader } from './strong-pet-trader.js';
const petMediator = new PetMediator;
const cuteLucas = new CutePetTrader(petMediator, 'CuteLucas');
const cuteEhtan = new CutePetTrader(petMediator, 'CuteEthan');
const strongOwen = new StrongPetTrader(petMediator, 'StrongOwen');
const strongEzra = new StrongPetTrader(petMediator, 'StrongEzra');
const traders = [
cuteLucas,
cuteEhtan,
strongOwen,
strongEzra,
];
const cuteTiger = new Pet('CuteTiger', true, false);
const cuteLucky = new Pet('CuteLucky', true, false);
const strongAri = new Pet('StrongAri', false, true);
const strongLev = new Pet('StrongLev', false, true);
const cuteStrongLeo = new Pet('CuteStrongLeo', true, true);
// Pet: [Tiger]
cuteLucas.put(cuteTiger);
// Pet: [], Trader: [], Ethan gets Tiger
cuteEhtan.call();
// Pet: [], Trader: [Lucas]
cuteLucas.call();
// Pet: [Ari], Trader: [Lucas]
strongOwen.put(strongAri);
// Pet: [Ari], Trader: [], Lucas gets Leo
strongEzra.put(cuteStrongLeo);
// Pet: [Ari, Lucky], Trader: []
cuteLucas.put(cuteLucky);
// Pet: [Ari, Lucky, Lev], Trader: []
strongEzra.put(strongLev);
// Pet: [Ari, Lev], Trader: [], Lucas gets Lucky
cuteLucas.call();
// Pet: [Lev], Trader: [], Ezra gets Ari
strongEzra.call();
console.group(petMediator.constructor.name);
console.log(petMediator);
console.groupEnd();
console.log();
traders.forEach(t => {
console.group(t.name);
console.log(t.receivedPets);
console.groupEnd();
console.log();
});
|
0e9ad7a8fbc759f1237281374fdd0861fe15a2c3
|
TypeScript
|
bave8672/leetcode
|
/src/scramble-string/scramble-string.ts
| 4.03125
| 4
|
/**
* https://leetcode.com/problems/scramble-string/
*
* We can scramble a string s to get a string t using the following algorithm:
*
* If the length of the string is 1, stop.
* If the length of the string is > 1, do the following:
* Split the string into two non-empty substrings at a random index, i.e., if the string is s, divide it to x and y where s = x + y.
* Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step, s may become s = x + y or s = y + x.
* Apply step 1 recursively on each of the two substrings x and y.
*
* Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
*
*
*
* Example 1:
*
* Input: s1 = "great", s2 = "rgeat"
* Output: true
* Explanation: One possible scenario applied on s1 is:
* "great" --> "gr/eat" // divide at random index.
* "gr/eat" --> "gr/eat" // random decision is not to swap the two substrings and keep them in order.
* "gr/eat" --> "g/r / e/at" // apply the same algorithm recursively on both substrings. divide at ranom index each of them.
* "g/r / e/at" --> "r/g / e/at" // random decision was to swap the first substring and to keep the second substring in the same order.
* "r/g / e/at" --> "r/g / e/ a/t" // again apply the algorithm recursively, divide "at" to "a/t".
* "r/g / e/ a/t" --> "r/g / e/ a/t" // random decision is to keep both substrings in the same order.
* The algorithm stops now and the result string is "rgeat" which is s2.
* As there is one possible scenario that led s1 to be scrambled to s2, we return true.
*
* Example 2:
*
* Input: s1 = "abcde", s2 = "caebd"
* Output: false
*
* Example 3:
*
* Input: s1 = "a", s2 = "a"
* Output: true
*
*
*
* Constraints:
*
* s1.length == s2.length
* 1 <= s1.length <= 30
* s1 and s2 consist of lower-case English letters.
*
*
*/
const BASE = 32;
export function isScramble(
s1: string,
s2: string,
s1startIndex = 0,
s1endIndex = s1.length - 1,
s2startIndex = 0,
s2endIndex = s2.length - 1,
): boolean {
// Using a scrolling divider,
// Hash chars in left & right sections of s2 and check if they match lef of s1
// if they do, check hashes recursively
// Time O(n * log(n)) space O(log(n)) (inclusive of stack)
if (s1startIndex === s1endIndex) {
return s1[s1startIndex] === s2[s2startIndex];
}
let s1Left = BigInt(0);
let s2Left = BigInt(0);
let s2Right = BigInt(0);
for (let i = 0; i < s1endIndex - s1startIndex; i++) {
s1Left += BigInt(
Math.pow(BASE, s1.charCodeAt(s1startIndex + i) % BASE),
);
s2Left += BigInt(
Math.pow(BASE, s2.charCodeAt(s2startIndex + i) % BASE),
);
if (
s1Left === s2Left &&
isScramble(
s1,
s2,
s1startIndex,
s1startIndex + i,
s2startIndex,
s2startIndex + i,
) &&
isScramble(
s1,
s2,
s1startIndex + i + 1,
s1endIndex,
s2startIndex + i + 1,
s2endIndex,
)
) {
return true;
}
s2Right += BigInt(Math.pow(BASE, s2.charCodeAt(s2endIndex - i) % BASE));
if (
s1Left === s2Right &&
isScramble(
s1,
s2,
s1startIndex,
s1startIndex + i,
s2endIndex - i,
s2endIndex,
) &&
isScramble(
s1,
s2,
s1startIndex + i + 1,
s1endIndex,
s2startIndex,
s2endIndex - i - 1,
)
) {
return true;
}
}
return false;
}
|
f62a7d6b9bb39fb879c7239e9db131ec46363e1e
|
TypeScript
|
carlosdumar/uicore
|
/src/hooks/useTween.ts
| 3.140625
| 3
|
import { useRef, useState } from 'react'
type TimingFunction = (time: number) => number
function makeEaseInOut(timing: TimingFunction): TimingFunction {
return function (time: number) {
if (time < 0.5) return timing(2 * time) / 2
else return (2 - timing(2 * (1 - time))) / 2
}
}
export const Easing = {
linear: (time: number) => time,
easeInOutQuad: makeEaseInOut(time => time ** 2),
easeInOutCubic: makeEaseInOut(time => time ** 2),
easeInOutQuart: makeEaseInOut(time => time ** 2)
}
export function useTween(
initial: number,
{ easing: timing = Easing.easeInOutQuad, duration = 250, onEnd = () => void 0 } = {}
): [number, (to: number) => void] {
const raf = useRef<number | null>(null)
const [state, setState] = useState(initial)
return [
state,
(to: number) => {
if (raf.current) cancelAnimationFrame(raf.current)
let start: number
function animate(time: number) {
start = start || time
const delta = (time - start) / duration,
progress = delta > 1 ? 1 : delta
setState(state + (to - state) * timing(progress))
if (progress < 1) raf.current = requestAnimationFrame(animate)
else {
raf.current = null
onEnd()
}
}
if (to !== state) raf.current = requestAnimationFrame(animate)
}
]
}
|
99a8589fc8a4a03aa8f3d188aa45cf32a5052aa5
|
TypeScript
|
AlmazKo/cosmos
|
/web/src/ext/promiser/types.d.ts
| 3.03125
| 3
|
declare type NP<T> = Exclude<T, Promise<any>>;
interface PromiseConstructor {
of<T>(value: NP<TO>): Promise<T>;
// zip<T1, T2, R>(v1: Promise<T1>, v2: Promise<T2>, accum: (p1: T1, p: T2) => R): Promise<R>;
//
// zip<T1, T2, T3, R>(v1: Promise<T1>, v2: Promise<T2>, v3: Promise<T3>, accum: (p1: T1, p2: T2, p3: T3) => R): Promise<R>;
timer(ms: number): Promise<void>;
error<T>(error: any): Promise<T>;
never(): Promise<void>;
}
interface Promise<T extends NP<T>> {
map<FROM = T, TO>(transformer: (f: FROM) => NP<TO>): Promise<TO>;
do<FROM = T>(consumer: (f: FROM) => void): Promise<T>;
doOnError<FROM = T>(consumer: (error: any) => void): Promise<T>;
onErrorResume<FROM = T>(consumer: (error: any) => Promise<T>): Promise<T>;
delay<TO = T>(ms: number): Promise<TO>;
ignore(): Promise<void>;
timeout<TO = T>(ms: number): Promise<TO>;
flatMap<TO>(mapper: (v: T) => Promise<TO>): Promise<TO>;
}
|
3b5c18ec30bfaee20ad9c1a421e383f702afa819
|
TypeScript
|
ludanin/groupxs
|
/src/order.spec.ts
| 3.515625
| 4
|
import "mocha";
import { expect } from "chai";
import Order from "./order";
describe("test Order constructor", () => {
it("returns a valid Order when built with an object", () => {
const order = new Order({ book1: 3, book2: 2, book3: -1, book4: undefined });
expect(order.book1).to.be.equal(3);
expect(order.book2).to.be.equal(2);
expect(order.book3).to.be.equal(0);
expect(order.book4).to.be.equal(0);
expect(order.book5).to.be.equal(0);
});
it("returns a valid Order when built with an array", () => {
const order = new Order({}, ["book1", "book1", "book2", "book3"]);
expect(order.book1).to.be.equal(2);
expect(order.book2).to.be.equal(1);
expect(order.book3).to.be.equal(1);
expect(order.book4).to.be.equal(0);
expect(order.book5).to.be.equal(0);
});
});
describe("test Order.array", () => {
it("returns a valid array", () => {
const order = new Order({ book1: 2, book2: 1 });
const { array } = order;
expect(array.length).to.be.equal(3);
expect(array[0]).to.be.equal("book1");
expect(array[1]).to.be.equal("book1");
expect(array[2]).to.be.equal("book2");
});
});
describe("test Order.arrangements", () => {
// What are the possible blocks to make with the following books?
// books = [book1, book2, book3]
//
// Ignoring order of books, the answer is 7:
// [book1, book2, book3] is by itself a block
// [book1, book2]
// [book1, book3]
// [book2, book3]
// [book1]
// [book2]
// [book3]
it("returns all possible blocks (1 distinct books)", () => {
const order = new Order({ book1: 1 });
expect(order.arrangements.length).to.be.equal(1);
});
it("returns all possible blocks (2 distinct books)", () => {
const order = new Order({ book1: 1, book2: 2 });
expect(order.arrangements.length).to.be.equal(3);
});
it("returns all possible blocks (3 distinct books)", () => {
const order = new Order({ book1: 1, book2: 2, book3: 3 });
expect(order.arrangements.length).to.be.equal(7);
});
it("returns all possible blocks (4 distinct books)", () => {
const order = new Order({ book1: 1, book2: 2, book3: 3, book4: 4 });
expect(order.arrangements.length).to.be.equal(15);
});
it("returns all possible blocks (5 distinct books)", () => {
const order = new Order({
book1: 1, book2: 2, book3: 3, book4: 4, book5: 5
});
expect(order.arrangements.length).to.be.equal(31);
});
});
describe("test Order solutions", () => {
it("returns all possible solutions (2 distinct books)", () => {
const order = new Order({ book1: 1, book2: 1 });
// [[book1, book2]]
// [[book1], [book2]]
expect(order.solutions.length).to.be.equal(2);
});
it("returns all possible solutions (3 distinct books)", () => {
const order = new Order({ book1: 1, book2: 1, book3: 1 });
// [[book1, book2, book3]]
// [[book1], [book2], [book3]]
// ... and so on
// We discard equal arrangements in different orders, e.g.
// [[book1], [book2, book3]] is treated equally as [[book2, book3], [book1]]
expect(order.solutions.length).to.be.equal(5);
});
it("returns all possible solutions (4 distinct books)", () => {
const order = new Order({}, ["book1", "book2", "book3", "book4"]);
expect(order.solutions.length).to.be.equal(15);
});
it("returns all possible solutions (5 distinct books)", () => {
const order = new Order({}, ["book1", "book2", "book3", "book4", "book5"]);
expect(order.solutions.length).to.be.equal(52);
});
it("returns the best solution (2 distinct books)", () => {
const order = new Order({ book1: 1, book2: 1 });
const { bestSolution } = order;
expect(bestSolution.price).to.be.equal(15.2);
});
it("returns the best solution (3 distinct books)", () => {
const order = new Order({ book1: 1, book2: 1, book3: 1 });
const { bestSolution } = order;
expect(bestSolution.price).to.be.equal(21.6);
});
it("returns the best solution (4 distinct books)", () => {
const order = new Order({}, ["book1", "book2", "book3", "book4"]);
const { bestSolution } = order;
expect(bestSolution.price).to.be.equal(25.6);
});
it("returns the best solution (5 distinct books)", () => {
const order = new Order({}, ["book1", "book2", "book3", "book4", "book5"]);
const { bestSolution } = order;
expect(bestSolution.price).to.be.equal(30);
});
});
|
e8d8b2f1449a5afaadf99b11956b1398e53c5950
|
TypeScript
|
kincjf/kidskids-appclient-backup1
|
/apps/ecom9/src/app/store/product/reducers/variant.reducer.ts
| 2.640625
| 3
|
import { createEntityAdapter, EntityState, EntityAdapter } from '@ngrx/entity';
import { VariantActions, VariantActionTypes } from '../actions/variant.actions';
import { ProductVariant } from '@ecom9/models';
export interface State extends EntityState<ProductVariant> {
isLoading: boolean;
error: any;
}
export const adapter: EntityAdapter<ProductVariant> = createEntityAdapter({
selectId: (product: ProductVariant) => product.id,
});
export const initialState: State = adapter.getInitialState({
isLoading: true,
error: null,
selectedId: null,
});
export function reducer(state = initialState, action: VariantActions): State {
switch (action.type) {
case VariantActionTypes.LoadVariants: {
return {
...state,
isLoading: true,
error: null,
};
}
case VariantActionTypes.LoadVariantsSuccess: {
return adapter.addMany(action.payload.items, {
...state,
isLoading: false,
isLoadingMore: false,
error: null,
});
}
case VariantActionTypes.LoadVariantsError: {
return {
...state,
isLoading: false,
error: action.payload.error,
};
}
default:
return state;
}
}
export const getIsLoading = (state: State) => state.isLoading;
export const getError = (state: State) => state.error;
|
b1c3680115e9410ed08e455e4315c9ac55ed99b3
|
TypeScript
|
jaburns/tsynth
|
/src/newNodes/adsr.ts
| 2.734375
| 3
|
import { NodeDef, UpdateFunc } from "newNodes";
const JUMP_LERP_TIME = 0.003; // Seconds.
// TODO Assert bufferLength > JUMP_LERP_TIME * sampleRate
export const ADSRDef : NodeDef = {
descriptor: ({
inputSignals: ['sync', 'input'],
outputSignals: ['output'],
knobs: [
{ label: 'attack', lower: 0, upper: 1, logarithmic: false, default: 0.03 },
{ label: 'decay', lower: 0, upper: 1, logarithmic: false, default: 0.2 },
{ label: 'sustain', lower: 0, upper: 1, logarithmic: false, default: 0.5 },
{ label: 'release', lower: 0, upper: 1, logarithmic: false, default: 0.2 }
]
}),
construct: (sampleRate: number, knobValues: number[]): UpdateFunc => {
const attack = knobValues[0];
const decay = knobValues[1];
const sustain = knobValues[2];
const release = knobValues[3];
let t: number = 0;
let on: boolean = false;
let releasing: boolean = false;
let lastAmp: number = 0;
return (xs: Float32Array[], ys: Float32Array[]) => {
const clk = xs[0];
const x = xs[1];
const y = ys[0];
let lerpStartAmp = 0;
if (!on && clk[0] > .5) {
lerpStartAmp = lastAmp;
on = true;
t = 0;
}
if (on && clk[0] < .5) {
lerpStartAmp = lastAmp;
on = false;
releasing = true;
t = 0;
}
let amp = 0;
if (on) {
for (let i = 0; i < y.length; ++i) {
const t1 = t++ / sampleRate;
amp = sustain;
if (t1 < attack) {
amp = t1 / attack;
}
else if (t1 < attack + decay) {
amp = 1 + ((t1 - attack) / decay) * (sustain - 1);
}
if (t1 < JUMP_LERP_TIME) {
amp = lerpStartAmp + (amp - lerpStartAmp) * t1 / JUMP_LERP_TIME;
}
y[i] = x[i] * amp;
}
}
else if (releasing) {
for (let i = 0; i < y.length; ++i) {
const t1 = t++ / sampleRate;
amp = 0;
if (t1 < release) {
amp = sustain * (1 - t1 / release);
}
if (t1 < JUMP_LERP_TIME) {
amp = lerpStartAmp + (amp - lerpStartAmp) * t1 / JUMP_LERP_TIME;
}
y[i] = x[i] * amp;
}
if (t / sampleRate > release) {
releasing = false;
}
}
else {
amp = 0;
for (let i = 0; i < y.length; ++i) {
y[i] = 0;
}
}
lastAmp = amp;
};
},
};
|
8d0ceb1b403835f63882c2da1349d0f3886d64ed
|
TypeScript
|
ricardosn87/_GIT
|
/EstudoAngular/products-app/src/app/product.service.ts
| 2.640625
| 3
|
import { Injectable, EventEmitter } from '@angular/core';
import { Product } from './models/product.model';
import { DepartamentService } from './departament.service';
@Injectable({
providedIn: 'root'
})
export class ProductService {
private nextID: number
onNewProduct: EventEmitter<Product> = new EventEmitter<Product>();
private dataFromServer: any[] = [{
id: 1, name: "LapTop", departament_id: 4, price: 40, description: "description"
},
{
id: 2, name: "Shirt", departament_id: 1, price: 10, description: "description"
},
{
id: 3, name: "Polo", departament_id: 1, price: 10, description: "description"
},
{
id: 4, name: "Mouse", departament_id: 3, price: 35, description: "description"
},
]
prodcuts: Product[] = []
constructor(private departamentService: DepartamentService) {
for (let p of this.dataFromServer) {
this.prodcuts.push({
id: p.id,
name: p.name,
description: p.description,
price: p.price,
departament: this.departamentService.getDepartamentById(p.id)
})
this.nextID = p.id + 1
}
}
getProducts(): Product[] {
return this.prodcuts;
}
addProduct(p: Product) {
let prod: Product = { ...p, id: this.nextID++ }
this.prodcuts.push(prod)
console.log(this.prodcuts)
this.onNewProduct.emit(prod)
}
}
|
eb08f576cf45c7585ea537781bb3e26dcbe194ba
|
TypeScript
|
eliseuvideira/ev-fns__gzip
|
/test/index.test.ts
| 2.921875
| 3
|
import fs from "fs";
import path from "path";
import { gzip } from "../src";
describe("gzip", () => {
it("gzips a file", async () => {
expect.assertions(3);
const content = "file content".repeat(5);
const filename = path.join(__dirname, Date.now().toString());
const gzipFilename = filename + ".gz";
await fs.promises.writeFile(filename, content);
const fileStats = await fs.promises.stat(filename);
await gzip(filename, gzipFilename);
try {
const gzipStats = await fs.promises.stat(gzipFilename);
const statError = jest.fn();
let error: any = null;
try {
await fs.promises.stat(filename);
} catch (err) {
error = err;
statError(err);
}
expect(statError).toHaveBeenCalled();
expect(statError).toHaveBeenLastCalledWith(error);
expect(gzipStats.size).toBeLessThan(fileStats.size);
} finally {
await fs.promises.unlink(gzipFilename);
}
});
it("gzips as .gz if not output filename", async () => {
expect.assertions(2);
const content = `${Date.now()}`.repeat(5);
const filename = path.join(__dirname, Date.now().toString());
await fs.promises.writeFile(filename, content);
await gzip(filename);
try {
try {
const stat = await fs.promises.stat(filename + ".gz");
expect(stat.isFile()).toBe(true);
expect(stat.size).toBeGreaterThan(0);
} catch (err) {
fail("gzip file doesn't exists");
}
} finally {
await fs.promises.unlink(filename + ".gz");
}
});
});
|
f7bba57f3e61d3939c9dd8804a4604af16df2d97
|
TypeScript
|
SwingDev/table-soccer-backend
|
/src/common/crud.service.ts
| 2.765625
| 3
|
import { FindManyOptions, Repository } from 'typeorm';
/**
* Base class for all services based on crud
*/
export class CRUDService<E, K=number> {
constructor(protected readonly repository: Repository<E>) { }
public async save(entity: E): Promise<E> {
return this.repository.save(entity);
}
public async find(id: K): Promise<E | undefined> {
return this.repository.findOne(id);
}
public async list(options?: FindManyOptions): Promise<E[]> {
return this.repository.find(options);
}
// tslint:disable-next-line: no-reserved-keywords
public async delete(id: number): Promise<void> {
await this.repository.delete(id);
}
}
|
05d274b9af1f79bda7ad0b397f47d51169226533
|
TypeScript
|
typestack/routing-controllers
|
/src/metadata-builder/MetadataArgsStorage.ts
| 2.6875
| 3
|
import { ControllerMetadataArgs } from '../metadata/args/ControllerMetadataArgs';
import { ActionMetadataArgs } from '../metadata/args/ActionMetadataArgs';
import { ParamMetadataArgs } from '../metadata/args/ParamMetadataArgs';
import { ResponseHandlerMetadataArgs } from '../metadata/args/ResponseHandleMetadataArgs';
import { MiddlewareMetadataArgs } from '../metadata/args/MiddlewareMetadataArgs';
import { UseMetadataArgs } from '../metadata/args/UseMetadataArgs';
import { UseInterceptorMetadataArgs } from '../metadata/args/UseInterceptorMetadataArgs';
import { InterceptorMetadataArgs } from '../metadata/args/InterceptorMetadataArgs';
/**
* Storage all metadatas read from decorators.
*/
export class MetadataArgsStorage {
// -------------------------------------------------------------------------
// Properties
// -------------------------------------------------------------------------
/**
* Registered controller metadata args.
*/
controllers: ControllerMetadataArgs[] = [];
/**
* Registered middleware metadata args.
*/
middlewares: MiddlewareMetadataArgs[] = [];
/**
* Registered interceptor metadata args.
*/
interceptors: InterceptorMetadataArgs[] = [];
/**
* Registered "use middleware" metadata args.
*/
uses: UseMetadataArgs[] = [];
/**
* Registered "use interceptor" metadata args.
*/
useInterceptors: UseInterceptorMetadataArgs[] = [];
/**
* Registered action metadata args.
*/
actions: ActionMetadataArgs[] = [];
/**
* Registered param metadata args.
*/
params: ParamMetadataArgs[] = [];
/**
* Registered response handler metadata args.
*/
responseHandlers: ResponseHandlerMetadataArgs[] = [];
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Filters registered middlewares by a given classes.
*/
filterMiddlewareMetadatasForClasses(classes: Function[]): MiddlewareMetadataArgs[] {
return classes.map(cls => this.middlewares.find(mid => mid.target === cls)).filter(midd => midd !== undefined); // this might be not needed if all classes where decorated with `@Middleware`
}
/**
* Filters registered interceptors by a given classes.
*/
filterInterceptorMetadatasForClasses(classes: Function[]): InterceptorMetadataArgs[] {
return this.interceptors.filter(ctrl => {
return classes.filter(cls => ctrl.target === cls).length > 0;
});
}
/**
* Filters registered controllers by a given classes.
*/
filterControllerMetadatasForClasses(classes: Function[]): ControllerMetadataArgs[] {
return this.controllers.filter(ctrl => {
return classes.filter(cls => ctrl.target === cls).length > 0;
});
}
/**
* Filters registered actions by a given classes.
*/
filterActionsWithTarget(target: Function): ActionMetadataArgs[] {
return this.actions.filter(action => action.target === target);
}
/**
* Filters registered "use middlewares" by a given target class and method name.
*/
filterUsesWithTargetAndMethod(target: Function, methodName: string): UseMetadataArgs[] {
return this.uses.filter(use => {
return use.target === target && use.method === methodName;
});
}
/**
* Filters registered "use interceptors" by a given target class and method name.
*/
filterInterceptorUsesWithTargetAndMethod(target: Function, methodName: string): UseInterceptorMetadataArgs[] {
return this.useInterceptors.filter(use => {
return use.target === target && use.method === methodName;
});
}
/**
* Filters parameters by a given classes.
*/
filterParamsWithTargetAndMethod(target: Function, methodName: string): ParamMetadataArgs[] {
return this.params.filter(param => {
return param.object.constructor === target && param.method === methodName;
});
}
/**
* Filters response handlers by a given class.
*/
filterResponseHandlersWithTarget(target: Function): ResponseHandlerMetadataArgs[] {
return this.responseHandlers.filter(property => {
return property.target === target;
});
}
/**
* Filters response handlers by a given classes.
*/
filterResponseHandlersWithTargetAndMethod(target: Function, methodName: string): ResponseHandlerMetadataArgs[] {
return this.responseHandlers.filter(property => {
return property.target === target && property.method === methodName;
});
}
/**
* Removes all saved metadata.
*/
reset() {
this.controllers = [];
this.middlewares = [];
this.interceptors = [];
this.uses = [];
this.useInterceptors = [];
this.actions = [];
this.params = [];
this.responseHandlers = [];
}
}
|
ebcbbaccb19ef6cf464d36064ccfb425eb0e149a
|
TypeScript
|
ShivrajRath/cbsera12
|
/collection.ts
| 3.3125
| 3
|
/**
* Collection class, container for student and subject collection
* http://stackoverflow.com/questions/30174078/how-to-define-singleton-in-typescript
*/
import {
Student
} from 'Student';
import {
Subject
} from 'Subject';
import {
Constant
} from 'Constant';
export class Collection {
private static _instance: Collection;
studentCollection: Array < Student > = [];
subjectCollection: Array < Subject > = [];
private constructor() {
// Does nothing
}
public static getInstance() {
return this._instance || (this._instance = new this());
}
/**
* Returns the instance of a subject or creates a new subject
* @param code Subject code
*/
getSubject(code: number): Subject {
let subject = this.subjectCollection.filter(subject => {
return subject.getCode() === code;
})[0];
if (!(subject instanceof Subject)) {
subject = new Subject(code);
this.subjectCollection.push(subject);
}
return subject;
}
/**
* Returns the instance of a student or creates a new subject
* @param code Subject code
*/
getStudent(roll: number): Student {
let student = this.studentCollection.filter(student => {
return student.getRoll() === roll;
})[0];
if (!(student instanceof Student)) {
student = new Student(roll);
this.studentCollection.push(student);
}
return student;
}
/**
* Returns all the subject codes
*/
getAllSubjectCodes() {
return this.subjectCollection.map(subject => subject.getCode());
}
getTotalAppearedStudents() {
return this.studentCollection.filter(student => student.result !== 'ABST').length;
}
getTotalPassedStudents() {
return this.studentCollection.filter(student => student.result === 'PASS').length;
}
getTotalFailAndCompStudents() {
return this.studentCollection.filter(student => student.result.match(/FAIL|COMP/gi)).length;
}
getTotalAbsentStudents() {
return this.studentCollection.filter(student => student.result === 'ABST').length;
}
getPassPercentage() {
return parseFloat(((this.getTotalPassedStudents() / this.getTotalAppearedStudents()) * 100).toFixed(2));
}
getPercentageRangeStudentCount(min: number, max: number) {
return this.studentCollection.filter(student => {
return student.getPercentage() >= min && student.getPercentage() <= max;
}).length;
}
getTotalGradesArray() {
let gradeObj: any = {};
Constant.GRADES.forEach(grade => {
gradeObj[grade] = 0;
});
gradeObj.totalMarks = 0;
this.subjectCollection.forEach(subject => {
Object.keys(subject.gradeObj).forEach(key => {
gradeObj[key] += subject.gradeObj[key];
gradeObj.totalMarks += subject.gradeObj[key];
});
});
return Object.keys(gradeObj).map(key => gradeObj[key]);
}
getTotalNxW() {
return this.subjectCollection.reduce((acc, subject) => {
return acc + subject.getNxW();
}, 0);
}
getTotalMark() {
return this.subjectCollection.reduce((acc, subject) => {
return acc + subject.getTotalMarks();
}, 0);
}
getTotalMean() {
return parseFloat((this.getTotalMark() / this.getTotalAppearedStudents()).toFixed(2));
}
getTotalPI() {
return parseFloat(((this.getTotalNxW() * 100) / (this.getTotalAppearedStudents() * 40)).toFixed(2));
}
/**
* Clears the collections
*/
clear() {
this.subjectCollection = [];
this.studentCollection = [];
}
}
|
65b395cfd30d05de69ee733bb43d2ef40a02c125
|
TypeScript
|
MrRefactoring/jira.js
|
/src/version2/parameters/getSelectableIssueFieldOptions.ts
| 2.71875
| 3
|
export interface GetSelectableIssueFieldOptions {
/** The index of the first item to return in a page of results (page offset). */
startAt?: number;
/** The maximum number of items to return per page. */
maxResults?: number;
/** Filters the results to options that are only available in the specified project. */
projectId?: number;
/**
* The field key is specified in the following format: **$(app-key)__$(field-key)**. For example,
* _example-add-on__example-issue-field_. To determine the `fieldKey` value, do one of the following:
*
* Open the app's plugin descriptor, then **app-key** is the key at the top and **field-key** is the key in the
* `jiraIssueFields` module. **app-key** can also be found in the app listing in the Atlassian Universal Plugin
* Manager. run [Get fields](#api-rest-api-2-field-get) and in the field details the value is returned in `key`. For
* example, `"key": "teams-add-on__team-issue-field"`
*/
fieldKey: string;
}
|
84c537affc5fdd49365d044fc9b620a42e2fcd0d
|
TypeScript
|
ManivannaBalaji/HiringApp-Angular
|
/src/app/service/job.service.ts
| 2.625
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class JobService {
constructor(private httpClient : HttpClient) { }
/**
* Get all available job offers
*/
getJobOffers(){
let url = "http://localhost:3000/api/jobs";
return this.httpClient.get(url);
}
/**
* Get a job details using job id.
* @param id
*/
getJobOffer(id : any){
let url = "http://localhost:3000/api/jobs/" + id;
return this.httpClient.get(url);
}
/**
* Add new job offer
* @param jobOffer
*/
addJobOffer(jobOffer : any){
let url = "http://localhost:3000/api/jobs";
return this.httpClient.post(url, jobOffer);
}
/**
* Update an already available job details
* @param oldJobOfferId
* @param updatedJob
*/
updateJobOffer(oldJobOfferId : any, updatedJob : any){
let url = "http://localhost:3000/api/jobs/" + oldJobOfferId;
return this.httpClient.put(url, updatedJob);
}
/**
* Delete a job offer
* @param jobId
*/
removeJobOffer(jobId : any){
let url = "http://localhost:3000/api/jobs/" + jobId;
return this.httpClient.delete(url);
}
/**
* Archive the job post (Remove a job and related applications, selected list)
* @param id
*/
archivePost(id : number){
let url = "http://localhost:3000/api/jobs/" + id + "/archive";
return this.httpClient.put(url, {});
}
/**
* Get status of hiring process for dashboard
*/
getStatus(){
let url = "http://localhost:3000/api/dashboard";
return this.httpClient.get(url);
}
/**
* Filter joboffers by job name
* @param jobOfferName
* @param jobOffers
*/
searchJobOffer(jobOfferName : string, jobOffers : any){
let searchedJobOffer : any = [];
jobOffers.forEach(function(element : any) {
if(element.jobtitle.toLowerCase().includes(jobOfferName.toLowerCase())){
searchedJobOffer.push(element);
}
});
return searchedJobOffer;
}
}
|
01d45d694b182341343cb89b0db6b47f07646e27
|
TypeScript
|
tawaship/Pixim.js
|
/src/modules/Container.ts
| 2.625
| 3
|
import * as PIXI from 'pixi.js';
import { Task } from './Task';
//import { TaskManager } from './TaskManager';
import { ITickerData } from './Application';
export interface IContainerData {
task: Task,
taskEnabledChildren: boolean
}
/**
* @ignore
*/
let _lastObserverID = 0;
/**
* [[http://pixijs.download/release/docs/PIXI.Container.html]]
*/
export class Container extends PIXI.Container {
protected _piximData: IContainerData;
constructor(...args: any[]) {
super();
this._piximData = {
task: new Task([], this),
taskEnabledChildren: true
};
this._piximData.task.first();
const _observerID = _lastObserverID++;
/*
this.on('added', () => {
TaskManager.addObserver(_observerID, this);
});
this.on('removed', () => {
TaskManager.removeObserver(_observerID);
});
*/
}
updateTask(e: ITickerData) {
const task: Task = this._piximData.task;
if (!this._piximData.task.enabled) {
return;
}
/*
let p: PIXI.DisplayObject = this;
let f = true;
while (p) {
if (p instanceof Container && !p.taskEnabledChildren) {
f = false;
break;
}
p = p.parent;
}
if (!f) {
return;
}
*/
task.done(e);
// will be deprecated
task.cemitAll(this, e);
}
/**
* Whether the task works.
*/
get taskEnabled(): boolean {
return this._piximData.task.enabled;
}
set taskEnabled(enabled) {
this._piximData.task.enabled = enabled;
}
/**
* Whether the children and subsequent tasks work.
*/
get taskEnabledChildren(): boolean {
return this._piximData.taskEnabledChildren;
}
set taskEnabledChildren(enabled) {
this._piximData.taskEnabledChildren = enabled;
}
/**
* Task object that works only while it is being displayed.
*/
get task(): Task {
return this._piximData.task;
}
/**
* Destroy instance.
*
* @override
*/
destroy(...args: any[]): void {
super.destroy(...args);
this._piximData.task.destroy();
}
}
|
65208199ed2f6d05410eaf3ac30f48544c0db326
|
TypeScript
|
thutterer/veue
|
/app/javascript/controllers/user_menu_controller.ts
| 2.65625
| 3
|
import { Controller } from "stimulus";
import { debounce } from "util/debounce";
export default class extends Controller {
static targets = ["area", "menu"];
areaTarget!: HTMLDivElement;
menuTarget!: HTMLDivElement;
isOpen = false;
connect(): void {
this.isOpen = false;
this.layout();
}
@debounce(100)
openOrCloseEvent(event: Event): void {
switch (event.type) {
case "click":
if (this.areaTarget.dataset["isOpen"] == "true") {
// Since we don't want to interrupt clicks that
// are navigating us somewhere, we should make sure
// we don't close if it's a link being clicked
if (!(event.target instanceof HTMLAnchorElement)) {
this.closeMenu();
}
} else {
this.openMenu();
}
return;
case "pointerenter":
// Touch events work funny with pointerenter / leave / click, so lets disable it.
if (event["pointerType"] !== "mouse") {
return;
}
this.openMenu();
return;
case "pointerleave":
this.closeMenu();
}
}
closeMenu(): void {
this.areaTarget.dataset["isOpen"] = "false";
}
openMenu(): void {
this.areaTarget.dataset["isOpen"] = "true";
}
layout(): void {
if (document.body.clientWidth > 650) {
this.menuTarget.dataset.mode = "dropdown";
this.menuTarget.setAttribute("style", "");
} else {
this.menuTarget.dataset.mode = "mobile";
const height = document.body.clientHeight - 46;
this.menuTarget.setAttribute("style", `height: ${height}px`);
}
}
}
|
72988b3f30e5f099c63d04867ea67f1ad00c57b1
|
TypeScript
|
MapGIS/MapGIS-Mobile-React-Native
|
/src/geodatabase/QueryDef.ts
| 2.828125
| 3
|
/**
* @content 查询条件定义功能组件
* @author fangqi 2021-09-16
*/
import ObjectManager from "../components/ObjectManager";
import type Dot from "../geoobject/Dot";
import Geometry from "../geoobject/Geometry";
import type Rect from "../geoobject/Rect";
/**
* @class QueryDef
* @description 扩展字段头
*/
export default class QueryDef extends ObjectManager {
getClassName(): String {
return this.CLASS_QUERY_DEF;
}
/**
* 构造一个新的 QueryDef 对象。
* @memberOf QueryDef
* @returns {Promise.<QueryDef>} QueryDef 对象。
*/
static async createInstance(): Promise<QueryDef> {
let thisObj = new QueryDef();
thisObj.ObjId = await thisObj.create();
return thisObj;
}
/**
* 设置属性查询条件
* @memberOf QueryDef
* @param whereClause 属性查询条件
* @return {Promise} 成功:>0;失败:<=0
*/
async setFilter(whereClause: String): Promise<number> {
let methodName = "setFilter"
let paramsTypeStr = [this.STRING];
let paramsStr = [whereClause];
return await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.NUMBER);
}
/**
* 获取属性查询条件
* @memberOf QueryDef
* @return {Promise} 属性查询条件
*/
async getFilter(): Promise<String> {
let methodName = "getFilter"
return await this.invoke(methodName, this.NUMBER);
}
/**
* 属性相关选项设置,设置查询结果字段集
* @memberOf QueryDef
* @param flds 查询结果字段集
* @return {Promise} 成功:>0;失败:<=0
*/
async setSubFields(flds: String): Promise<number> {
let methodName = "setSubFields"
let paramsTypeStr = [this.STRING];
let paramsStr = [flds];
return await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.NUMBER);
}
/**
* 获取查询结果字段集
* @memberOf QueryDef
* @return {Promise} 查询结果字段集
*/
async getSubFields(): Promise<String> {
let methodName = "getSubFields"
return await this.invoke(methodName, this.NUMBER);
}
/**
* 是否设置缓存空间图形记录
* @memberOf QueryDef
* @return {Promise} true表示缓存,false表示不缓存。
*/
async getWithSpatial(): Promise<boolean> {
let methodName = "getWithSpatial"
return await this.invoke(methodName, this.NUMBER);
}
/**
* 是否设置缓存空间图形记录
* @memberOf QueryDef
* @param newVal 是否设置缓存空间图形记录
* @return {Promise}
*/
async setWithSpatial(newVal: boolean): Promise<void> {
let methodName = "setWithSpatial"
let paramsTypeStr = [this.BOOLEAN];
let paramsStr = [newVal];
await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.VOID);
}
/**
* 指定结果集按该字段排序 该字段可以是属性表中的任何字段(包括或OID)或空间表(MF)中的任何 字段,可以结合IsAsc属性使用。
* @memberOf QueryDef
* @param field 排序字段
* @return {Promise<number>} 成功:>0;失败:<=0
*/
async setOrderField(field: String): Promise<number> {
let methodName = "setOrderField"
let paramsTypeStr = [this.STRING];
let paramsStr = [field];
return await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.NUMBER);
}
/**
* 获取排序字段
* @memberOf QueryDef
* @return {Promise} 排序字段
*/
async getOrderField(): Promise<String> {
let methodName = "getOrderField"
return await this.invoke(methodName, this.STRING);
}
/**
* 结果集是否升序排列
* @memberOf QueryDef
* @param newVal true:升序;false:降序
* @return {Promise}
*/
async setIsAsc(newVal: boolean): Promise<void> {
let methodName = "setIsAsc"
let paramsTypeStr = [this.BOOLEAN];
let paramsStr = [newVal];
await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.VOID);
}
/**
* 结果集是否升序排列
* @memberOf QueryDef
* @return {Promise} true:升序;false:降序
*/
async getIsAsc(): Promise<boolean> {
let methodName = "getIsAsc"
return await this.invoke(methodName, this.BOOLEAN);
}
/**
* 设置分组字段 未实现
* @memberOf QueryDef
* @param field 分组字段
* @return {Promise<number>} 成功:>0;失败:<=0
*/
async setGroupField(field: String): Promise<number> {
let methodName = "setGroupField"
let paramsTypeStr = [this.STRING];
let paramsStr = [field];
return await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.NUMBER);
}
/**
* 获取分组字段 未实现
* @memberOf QueryDef
* @return {Promise} 分组字段
*/
async getGroupField(): Promise<boolean> {
let methodName = "getGroupField"
return await this.invoke(methodName, this.BOOLEAN);
}
/**
* 设置矩形查询条件
* @memberOf QueryDef
* @param rect 矩形范围
* @param queryMode 空间查询模式
* @return {Promise} 成功:>0;失败:<=0
*/
async setRect(rect: Dot, queryMode: any): Promise<number> {
let methodName = "setRect"
let paramsTypeStr = [this.CLASS_RECT, this.ENUM + this.CLASS_QUERY_MODE];
let paramsStr = [rect.ObjId, queryMode];
return await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.NUMBER);
}
/**
* 获取矩形范围查询条件
* @memberOf QueryDef
* @param rect [out] 矩形范围
* @return {Promise<SpaQueryMode>}
*/
async getRect(rect: Rect) {
let methodName = "getRect"
let paramsTypeStr = [this.CLASS_RECT];
let paramsStr = [rect.ObjId];
return await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.ENUM);
}
/**
* 设置多边形查询条件
* @memberOf QueryDef
* @param geom 多边形
* @param queryMode 空间查询模式
* @return {Promise} 成功:>0;失败:<=0
*/
async setSpatial(geom: Geometry, queryMode: any): Promise<number> {
let methodName = "setSpatial"
let paramsTypeStr = [this.CLASS_GEOMETRY, this.ENUM + this.CLASS_QUERY_MODE];
let paramsStr = [geom.ObjId, queryMode];
return await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.NUMBER);
}
/**
* 获取多边形查询条件
* @memberOf QueryDef
* @param queryMode [out]空间查询模式 结果为SpaQueryMode的枚举值
* @return {Promise} 多边形
*/
async getSpatial(queryMode: any): Promise<Geometry> {
let methodName = "getSpatial"
let paramsTypeStr = [this.ENUM + this.CLASS_QUERY_MODE];
let paramsStr = [queryMode];
let ObjId = await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.OBJID);
return await Geometry.getGeometryById(ObjId);
}
/**
* Near点查询
* @memberOf QueryDef
* @param dot 点坐标
* @param dx x方向最大范围偏移量
* @param dy y方向最大范围偏移量
* @return {Promise} 成功:>0;失败:<=0
*/
async setNear(dot: Dot, dx: number, dy: number): Promise<number> {
let methodName = "setNear"
let paramsTypeStr = [this.CLASS_DOT, this.DOUBLE, this.DOUBLE];
let paramsStr = [dot.ObjId, dx, dy];
return await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.NUMBER);
}
/**
* 设置距离查询条件(不支持,暂未实现) 1.通过传入的要素,根据该要素向外扩展一段距离,在这距离内的要素,就是查询要素; 2.注意:不包括与该要素相交的要素。
* @memberOf QueryDef
* @param geom 几何对象
* @param distance 距离
* @return {Promise} 成功:>0;失败:<=0
*/
async setDistance(geom: Geometry, distance: number): Promise<number> {
let methodName = "setDistance"
let paramsTypeStr = [this.CLASS_GEOMETRY, this.DOUBLE];
let paramsStr = [geom.ObjId, distance];
return await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.NUMBER);
}
/**
* 设置容差半径
* @memberOf QueryDef
* @param esp 容差半径
* @return {Promise} 成功:>0;失败:<=0
*/
async setTolerance(esp: number): Promise<number> {
let methodName = "setTolerance"
let paramsTypeStr = [this.DOUBLE];
let paramsStr = [esp];
return await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.NUMBER);
}
/**
* 获取容差半径
* @memberOf QueryDef
* @return {Promise} 成功:>0;失败:<=0
*/
async getTolerance(): Promise<number> {
let methodName = "getTolerance"
return await this.invoke(methodName, this.NUMBER);
}
/**
* 设置查询顺序
* @memberOf QueryDef
* @param order 查询顺序
* @return {Promise} 成功:>0;失败:<=0
*/
async setSearchOrder(order: String): Promise<number> {
let methodName = "setSearchOrder"
let paramsTypeStr = [this.STRING];
let paramsStr = [order];
return await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.NUMBER);
}
/**
* 获取查询顺序
* @memberOf QueryDef
* @return {Promise} 查询顺序
*/
async getSearchOrder(): Promise<String> {
let methodName = "getSearchOrder"
return await this.invoke(methodName, this.STRING);
}
/**
* 设置是否按照要素ID排序
* @memberOf QueryDef
* @param byFID 是否按照要素ID排序
* @return {Promise} 成功:>0;失败:<=0
*/
async setOrderByFID(byFID: boolean): Promise<number> {
let methodName = "setOrderByFID"
let paramsTypeStr = [this.BOOLEAN];
let paramsStr = [byFID];
return await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.NUMBER);
}
/**
* 获取是否按照要素ID排序
* @memberOf QueryDef
* @return {Promise} 是否按照要素ID排序
*/
async getOrderByFID(): Promise<boolean> {
let methodName = "getOrderByFID"
return await this.invoke(methodName, this.BOOLEAN);
}
/**
* 设置图形表查询条件
* 点图形参数字段 libID; symID; height; width; angle; outpenw0,outpenw1,outpenw2 outclr0,outclr1,outclr2, ovprnt; fillflg; backexp; backclr;
* 用法示例,etInfoFilter("libID>3");
* 线图形参数字段 libID; linstyID; ovprnt; outpenw0,outpenw1,outpenw2 outclr0,outclr1,outclr2, headtype; jointype; adjustflg; makemethod; xscale; yscale;
* 用法示例,etInfoFilter("linstyID>3");
* 区图形参数字段 libID; patID; ovprnt; fillmode; fillclr; endclr; pathei; patwid; ang; patclr; outpenw; fullpatflg;
* 用法示例,etInfoFilter("patID>3");
* @memberOf QueryDef
* @param whereClause 图形表查询条件
* @return {Promise} 成功:>0;失败:<=0
*/
async setInfoFilter(whereClause: String): Promise<number> {
let methodName = "setInfoFilter"
let paramsTypeStr = [this.BOOLEAN];
let paramsStr = [whereClause];
return await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.NUMBER);
}
/**
* 获取图形表查询条件
* @memberOf QueryDef
* @return {Promise} 图形表查询条件
*/
async getInfoFilter(): Promise<String> {
let methodName = "getInfoFilter"
return await this.invoke(methodName, this.STRING);
}
/**
* 按区间内素ID查询
* @memberOf QueryDef
* @param fromFID 开始要素oid
* @param toFID 结束要素oid
* @return {Promise} 成功:>0;失败:<=0
*/
async featureIdBetween(fromFID: number, toFID: number): Promise<number> {
let methodName = "featureIdBetween"
let paramsTypeStr = [this.LONG, this.LONG];
let paramsStr = [fromFID, toFID];
return await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.NUMBER);
}
/**
* 分页查询 目前只有pg和hdb的简单要素类和注记类,以及各数据源的对象类支持该语意。 当lOffset较大时,分页查询效率就大幅下降,所以需要从查询策略上进行
* @memberOf QueryDef
* @param offset 页号(从1开始)
* @param lLimit 每一页的大小
* @return {Promise}
*/
async setPagination(offset: number, lLimit: number): Promise<boolean> {
let methodName = "setPagination"
let paramsTypeStr = [this.LONG, this.INT];
let paramsStr = [offset, lLimit];
return await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.BOOLEAN);
}
/**
* 分页查询
* @memberOf QueryDef
* @param offset [out] 页号(从1开始)
* @param limit [out] 每一页的大小
* @return {Promise}
*/
async getPagination(offset: number, limit: number): Promise<boolean> {
let methodName = "getPagination"
let paramsTypeStr = [this.LONG, this.INT];
let paramsStr = [offset, limit];
return await this.invokeByParam(methodName, paramsTypeStr, paramsStr, this.BOOLEAN);
}
/**
* q清除所有查询标识
* @memberOf QueryDef
* @return {Promise}
*/
async clear(): Promise<boolean> {
let methodName = "clear"
return await this.invoke(methodName, this.BOOLEAN);
}
}
|
294f1ffd0c0fc94d77fb59e75df48d6f43b26007
|
TypeScript
|
chadhietala/castle
|
/packages/avro-ts-cli/test/avro/ComplexRecord.avsc.ts
| 2.9375
| 3
|
/* eslint-disable @typescript-eslint/no-namespace */
export type User = ComExampleAvro.User;
export namespace ComExampleAvro {
export const FooName = "com.example.avro.Foo";
export interface Foo {
label: string;
}
export const EmailAddressName = "com.example.avro.EmailAddress";
/**
* Stores details about an email address that a user has associated with their account.
*/
export interface EmailAddress {
/**
* The email address, e.g. `foo@example.com`
*/
address: string;
/**
* true if the user has clicked the link in a confirmation email to this address.
*
* Default: false
*/
verified?: boolean;
/**
* Timestamp (milliseconds since epoch) when the email address was added to the account.
*/
dateAdded: number;
}
export const StatusName = "com.example.avro.status";
/**
* * `PENDING`: the user has started authorizing, but not yet finished
* * `ACTIVE`: the token should work
* * `DENIED`: the user declined the authorization
* * `EXPIRED`: the token used to work, but now it doesn't
* * `REVOKED`: the user has explicitly revoked the token
*/
export type Status = "ACTIVE" | "INACTIVE";
export const UserName = "com.example.avro.User";
/**
* This is a user record in a fictitious to-do-list management app. It supports arbitrary grouping and nesting of items, and allows you to add items by email or by tweeting.
*
* Note this app doesn't actually exist. The schema is just a demo for [Avrodoc](https://github.com/ept/avrodoc)!
*/
export interface User {
/**
* System-assigned numeric user ID. Cannot be changed by the user.
*/
id: number;
/**
* The username chosen by the user. Can be changed by the user.
*/
username: string;
/**
* The user's password, hashed using [scrypt](http://www.tarsnap.com/scrypt.html).
*/
passwordHash: string;
/**
* Timestamp (milliseconds since epoch) when the user signed up
*/
signupDate: number;
mapField: {
[index: string]: ComExampleAvro.Foo;
};
/**
* All email addresses on the user's account
*/
emailAddresses: ComExampleAvro.EmailAddress[];
/**
* Indicator of whether this authorization is currently active, or has been revoked
*/
status: ComExampleAvro.Status;
}
}
|
6b26c63d0987ab83718de75517a4f7e30ff33c9d
|
TypeScript
|
pedroribeiro89/pizza-nest-prisma
|
/src/pizza/pizza.controller.ts
| 2.578125
| 3
|
import { Controller, Get, Logger, Param, Query } from "@nestjs/common";
import { Pizza } from '@prisma/client';
import { PizzaService } from './pizza.service';
@Controller('pizzas')
export class PizzaController {
private readonly logger = new Logger(PizzaController.name);
constructor(private readonly pizzaService: PizzaService) {}
@Get()
async findAll(@Query('vegs') vegs: boolean = false): Promise<Pizza[]> {
if (vegs) {
this.logger.log('vegs');
return this.pizzaService.vegPizzas();
}
this.logger.log('normal');
return this.pizzaService.pizzas({});
}
@Get(':id')
async findOne(@Param('id') id: string): Promise<Pizza> {
return this.pizzaService.pizza({ id: Number(id) });
}
// @Get('vegs')
// async findVegs(): Promise<Pizza[]> {
// this.logger.log('foi');
// return this.pizzaService.vegPizzas();
// }
// @Get('/vegs')
// async findVegs() {
// console.log('teste');
// }
}
|
8ff5c13f694c937e0ac87606ddc75903a83967a9
|
TypeScript
|
gache/CRUD-avec-Firebase
|
/src/app/pages/models/heroe.model.ts
| 2.515625
| 3
|
export class HeroeModel {
id: string;
Prenom: string;
pouvoir: string;
vivant: boolean;
// j'initialise la propriété vivant par défaut va être true c'est dire vivant
constructor() {
this.vivant = true;
}
}
|
1c33e06ca2b25c8134bba258de9b74741868d24e
|
TypeScript
|
vesanieminen/web-components
|
/packages/grid/src/vaadin-grid-active-item-mixin.d.ts
| 2.5625
| 3
|
/**
* @license
* Copyright (c) 2021 Vaadin Ltd.
* This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
*/
declare function ActiveItemMixin<TItem, T extends new (...args: any[]) => {}>(
base: T
): T & ActiveItemMixinConstructor<TItem>;
interface ActiveItemMixinConstructor<TItem> {
new (...args: any[]): ActiveItemMixin<TItem>;
}
interface ActiveItemMixin<TItem> {
/**
* The item user has last interacted with. Turns to `null` after user deactivates
* the item by re-interacting with the currently active item.
*/
activeItem: TItem | null;
}
declare function isFocusable(target: Element): boolean;
export { ActiveItemMixin, ActiveItemMixinConstructor, isFocusable };
|
56a068b301441bc4950f8bb491dd775e70530a0b
|
TypeScript
|
1thanatos/qi
|
/src/qi/graphics/vertexs.ts
| 2.796875
| 3
|
import {Graphics} from "qi/graphics";
import {Point} from "qi/base/point";
import {can} from "qi/can";
import {Vector} from "qi/base/vector";
class Vertexs{
grap:Graphics
points:Array<Point>=[]
constructor(grap:Graphics) {
this.grap=grap
}
// according to points and transform.draw the graphics.
// this function is important
draw(){
if(this.points.length == 0 || this.points.length == 1)return
let clonePoints=this.clone()
let center:Point
let radian:number
if(this.grap.rotation.radian!=0){
center=new Point(this.grap.pivot.x,this.grap.pivot.y)
// console.log(center)
radian=this.grap.rotation.radian
}
let finalArray:Array<(params:Point)=>void>=[];
if(this.grap.transform.x !=0 || this.grap.transform.y != 0){
finalArray.push( (params:Point)=>{
params.transform(new Point(this.grap.transform.x,this.grap.transform.y))
})
}
if(this.grap.rotation.radian!=0){
finalArray.push((params:Point)=>{
let vector=new Vector(params,center)
let afterRotate =vector.clone().rotateAlong(radian)
params.transform(new Point(afterRotate.x-vector.x,afterRotate.y-vector.y))
})
}
if(this.grap.father.grap!=undefined) {// 以父亲的左上角为坐标轴
this.grap.father.transform(finalArray)
}
for (const finalArrayElement of finalArray) {
for (let params of clonePoints) {
finalArrayElement(params)
}
}
let index=0
can.ctx.moveTo(clonePoints[0].x,clonePoints[0].y)
for (let params of clonePoints) {
index+=1;
if(index == 1)continue
can.ctx.lineTo(params.x, params.y)
}
}
// clone all the points
clone(){
let clonePoints:Array<Point>=[]
for (let params of this.points) {
clonePoints.push(new Point(params.x,params.y))
}
return clonePoints
}
// return all the points's x
allX():Array<number>{
let allX:Array<number>=[]
for (const params of this.points) {
allX.push(params.x)
}
return allX
}
allY():Array<number>{
let allY:Array<number>=[]
for (const params of this.points) {
allY.push(params.y)
}
return allY
}
// add point to points
add(point:Array<Point>){
for (let params of point) {
this.points.push(params);
}
this.draw()
return this
}
// remove point from the points
// remove(point:Point){
// this.points.remove(point);
// this.draw()
// return this
// }
}
export {Vertexs}
|
35326fa6b810ec418fd1a2d120da826f86db04d6
|
TypeScript
|
MichaelShipitsyn/event-crm
|
/src/store/cache/selector.ts
| 2.671875
| 3
|
import { RootState } from 'store';
const isRootState = (state: unknown): state is RootState => {
return !!(state as RootState);
};
export const isCached = (url: string) => (state: RootState) => {
return state.cache.cache.includes(url);
};
export const getCache = (state: unknown) => {
if (isRootState(state)) {
return state.cache.cache;
}
return [];
};
|
1d49a2b8f6323e477bb091e48e404851c31077e3
|
TypeScript
|
xiaoyi20/game-globaltravel
|
/assets/scripts/hall/game/effect/LoadingTip.ts
| 2.5625
| 3
|
import { LanguageLabel } from "../../../core/language/LanguageLabel";
import { ComponentExtends } from "../../../core/ui/ComponentExtends";
const { ccclass, property } = cc._decorator;
@ccclass
export default class LoadingTip extends ComponentExtends {
/** 获取begin到length的随机数 整数 */
public getRandomNum = function (begin: number, length: number) {
return Math.round(Math.random() * (length - begin) + begin);
};
onLoad(){
let comp = this.node.getComponent(LanguageLabel);
comp.dataID = `tips_${this.getRandomNum(1,10)}`;
this.schedule(()=>{
comp.dataID = `tips_${this.getRandomNum(1,10)}`;
},5)
}
onDestroy(){
this.unscheduleAllCallbacks();
super.onDestroy();
}
}
|
f2ee8a2372fe7771d3d3e3aa0615bbcf062a510c
|
TypeScript
|
dudewith3faces/symply-frontend
|
/src/components/services/main.service.ts
| 2.921875
| 3
|
import axios from "axios";
import { useEffect, useState } from "react";
import { IFact, IResponse } from "../interface";
export const HomeService = () => {
const [facts, setFacts] = useState<IFact[]>([]);
const getFacts = async (): Promise<IFact[]> => {
const { data } = await axios.get<{ text: string; _id: string }[]>(
"https://cat-fact.herokuapp.com/facts/random?animal_type=dog&amount=10"
);
const payload: IFact[] = [];
data.forEach(({ text, _id }) => payload.push({ text, id: _id }));
return payload;
// return [
// { title: "Another", id: "1" },
// { title: "Home", id: "2" },
// { title: "Another one", id: "3" },
// { title: "fuck you", id: "4" },
// ];
};
useEffect(() => {
getFacts().then((data) => setFacts(data));
}, []);
const addFav = async (data: IFact) => {
await axios.post<IResponse>("http://localhost:5000/api/fact", data);
return;
};
return { facts, addFav };
};
export const BackendService = () => {
const [favs, setFav] = useState<IFact[]>([]);
const getFav = async () => {
const {
data: { payload },
} = await axios.get<IResponse<IFact[]>>("http://localhost:5000/api/fact");
return payload;
};
useEffect(() => {
getFav().then((data) => setFav(data));
}, []);
const removeFav = async (value: IFact) => {
await axios.delete<IResponse>(`http://localhost:5000/api/fact/${value.id}`);
const data = favs.filter(({ id }) => id !== value.id);
setFav(data);
};
return { favs, removeFav };
};
|
2e074d0f4d281865c241f0e3510548a54549652a
|
TypeScript
|
apiatin/keycloak-admin-ui
|
/src/utils/useRequiredContext.ts
| 3.25
| 3
|
import { useContext } from "react";
import type { Context } from "react";
/**
* Passes the call to `useContext` and throw an exception if the resolved value is either `null` or `undefined`.
* Can be used for contexts that are required and should always have a non nullable value.
*
* @param context The context to pass to `useContext`
* @returns
*/
export default function useRequiredContext<T>(
context: Context<T>
): NonNullable<T> {
const resolved = useContext(context);
if (resolved !== undefined && resolved !== null) {
return resolved as NonNullable<T>;
}
throw new Error(
`No provider found for ${
context.displayName ? `the '${context.displayName}'` : "an unknown"
} context, make sure it is included in your component hierarchy.`
);
}
|
ebe095d4d09e1adeb2caa257c9be89ab958667a9
|
TypeScript
|
spacerkt/nestjs-util
|
/lib/merge-one-to-many.util.ts
| 3.296875
| 3
|
/***
* mergeManyToOneEntity - Used to map an array of Entity2 to a property in an Entity1
* Entity2 should have a foreign key to Entity1
* @param entities1 array of entities
* @param e1PK primary key of entitie1
* @param e1Prop which property of entitie1 will receive the array of entities2
* @param entities2 array of entities2
* @param entityFK fk property of entity2 to entity1
*/
export function mergeManyToOneEntity<E1, E2>(
entities1: readonly E1[],
e1PK: keyof E1,
e1Prop: keyof E1,
entities2: readonly E2[],
entityFK: keyof E2,
) {
if (!entities2.length) {
return;
}
if (e1PK === e1Prop) {
throw new Error('e1PK must not be equal to e1Prop');
}
const pk = e1PK as string;
const prop = e1Prop as string;
const fk = entityFK as string;
const entitiesMap: { [key: string]: E2[] } = {};
entities1.forEach((e1, index, arr) => {
if (!arr[index][prop]) {
arr[index][prop] = [];
}
entitiesMap[e1[pk]] = arr[index][prop];
});
entities2.forEach(entity => {
entitiesMap[entity[fk]].push(entity);
});
}
|
3a481a471bb99b720d04f6801aeeb1ea6ea13d6b
|
TypeScript
|
zirman/aoc2017
|
/src/day11.ts
| 3.203125
| 3
|
import fs from 'fs';
export {};
fs.readFile('../input/day11.txt', 'utf8', (err, contents) => {
if (err !== null) {
console.error(err);
return;
}
let max = 0;
const ds = contents.split(',');
let i = 0;
let j = 0;
for (const d of ds) {
switch (d) {
case 'n':
j += 1;
break;
case 'ne':
i += 1;
break;
case 'se':
i += 1;
j -= 1;
break;
case 's':
j -= 1;
break;
case 'sw':
i -= 1;
break;
case 'nw':
j += 1;
i -= 1;
break;
default:
throw Error();
}
max = Math.max(max, distance(i, j));
}
console.log(distance(i, j));
console.log(max);
});
function distance(i: number, j: number) {
if ((i >= 0 && j >= 0) || (i <= 0 && j <= 0)) {
return Math.abs(i + j);
} else {
return Math.max(Math.abs(i), Math.abs(j));
}
}
|
9c0ecac534d5924069a696b44c68bed1cb232440
|
TypeScript
|
deyvidholz/letsshopping-api
|
/src/interceptors/product-request.interceptor.ts
| 2.6875
| 3
|
import { NextFunction, Request, Response } from 'express';
import unprocessableEntity from '../errors/http/unprocessable-entity.error';
import { HandlerReturn } from '../types/middlewares/interceptors/handler-return.types';
export class ProductRequestInterceptor {
public static handler(req: Request): HandlerReturn {
if (req.body.categories) {
const invalidCategories = req.body.categories.filter(
(categoryId) => typeof categoryId !== 'number',
);
if (invalidCategories.length)
return { success: false, message: 'Invalid value for "categories".' };
req.interceptor.categories = req.body.categories.map((categoryId) => ({
id: categoryId,
}));
}
return {
success: true,
};
}
public static create(req: Request, res: Response, next: NextFunction) {
const handled = ProductRequestInterceptor.handler(req);
if (!handled.success)
return unprocessableEntity({ message: handled.message }).send(res);
next();
}
public static update(req: Request, res: Response, next: NextFunction) {
const handled = ProductRequestInterceptor.handler(req);
if (!handled.success)
return unprocessableEntity({ message: handled.message }).send(res);
next();
}
}
|
4f22646e3af15b6f35c714199bd5c01e27183eb7
|
TypeScript
|
jjvainav/sprig
|
/packages/store/test/store.test.ts
| 3.25
| 3
|
import { combineHandlers, createStore, IAction, IActionHandler, IStore, IStoreOptions, mapHandlers } from "../src";
interface IItem {
readonly id: string;
readonly value: string;
}
interface IState {
readonly items: IItem[];
}
interface IAddItem extends IAction {
readonly type: "add-item";
readonly itemId: string;
readonly value: string;
}
interface IUpdateItem extends IAction {
readonly type: "update-item";
readonly itemId: string;
readonly value: string;
}
const getItem = (state: IState) => (id: string) => {
for (const item of state.items) {
if (item.id === id) {
return item;
}
}
return undefined;
};
const handler = mapHandlers({
"add-item": addItemHandler,
"update-item": updateItemHandler
});
function createTestStore(options?: IStoreOptions<IState>): IStore<IState> {
return createStore(options || { initialState: { items: [] }, handler });
}
function addItemAction(itemId: string, value: string): IAction {
return <IAddItem>{ type: "add-item", itemId, value };
}
function updateItemAction(itemId: string, value: string): IAction {
return <IUpdateItem>{ type: "update-item", itemId, value };
}
function addItemHandler(store: IStore<IState>, action: IAddItem): void {
store.save(state => ({
...state,
items: [...state.items, { id: action.itemId, value: action.value }]
}));
}
function updateItemHandler(store: IStore<IState>, action: IUpdateItem): void {
const item = store.select(getItem, action.itemId);
if (!item) {
throw new Error("Item not found");
}
if (item.value === action.value) {
return;
}
store.save(state => ({
...state,
cart: update(state.items, { id: action.itemId, value: action.value })
}));
}
describe("store", () => {
test("dispatch action", async () => {
const store = createTestStore();
const oldState = store.getState();
await store.dispatch(addItemAction("1", "foo"));
const newState = store.getState();
expect(oldState).not.toBe(newState);
});
test("dispatch multiple actions", async () => {
const store = createTestStore();
let count = 0;
store.onChanged(() => count++);
await store.dispatch(addItemAction("1", "foo"));
await store.dispatch(addItemAction("2", "bar"));
expect(count).toBe(2);
});
test("dispatch action that does not change state", async () => {
const store = createTestStore();
let count = 0;
store.onChanged(() => count++);
await store.dispatch(addItemAction("1", "foo"));
await store.dispatch(updateItemAction("1", "foo"));
await store.dispatch(updateItemAction("1", "foo"));
expect(count).toBe(1);
});
test("dispatch invalid action", async () => {
const store = createTestStore();
const oldState = store.getState();
let flag = false;
store.onChanged(() => flag = true);
await expect(store.dispatch(updateItemAction("1", "foo"))).rejects.toThrow();
const newState = store.getState();
expect(flag).toBeFalsy();
expect(oldState).toBe(newState);
});
test("combine handlers", async () => {
const actions: IAction[] = [];
const customHandler: IActionHandler<IState> = (_, action) => {
actions.push(action);
return Promise.resolve();
};
const store = createTestStore({
initialState: { items: [] },
handler: combineHandlers(customHandler, handler)
});
await store.dispatch(addItemAction("1", "foo"));
expect(actions).toHaveLength(1);
});
});
function update<T extends { id: string }>(array: T[], item: T): T[] {
let index = -1;
for (let i = 0; i < array.length; i++) {
if (array[i].id === item.id) {
index = i;
break;
}
}
if (index < 0) {
return [...array, item];
}
const result = array.slice(0);
result[index] = item;
return result;
}
|
65714788bd4a77cbe07e13afaa09bfe042b3ef29
|
TypeScript
|
murilovmachado/deck-of-cards-ui
|
/src/services/cards-service.ts
| 2.640625
| 3
|
import fetchApi from './fetchApi';
type RequestDeckResponse = {
success: boolean;
deck_id: string;
shuffled: boolean,
remaining: number;
}
type Card = {
image: string;
value: string;
suit: string;
code: string;
};
export type DrawCardResponse = {
success: boolean;
cards: Card[];
deck_id: string,
remaining: number;
};
export const requestDeck = () => fetchApi<RequestDeckResponse>('new');
export const shuffleDeck = (deckId: string) => fetchApi<RequestDeckResponse>(`${deckId}/shuffle/`);
export const drawCard = (deckId: string) => fetchApi<DrawCardResponse>(`${deckId}/draw/?count=1`);
|
4821cc0972af861c148b74969729d5624beb26a3
|
TypeScript
|
chris510/Clouds
|
/src/app/city.model.ts
| 2.671875
| 3
|
export class City {
name: string;
temp: string;
pressure: string;
description: string;
windSpeed: string;
windDegree: string;
}
export interface cityWeather {
name: string,
temp: string;
pressure: string;
description: string;
windSpeed: string;
windDegree: string;
}
|
6619aa7f283408bf83c66f0d0caa83834d2d60c3
|
TypeScript
|
AlmeidaIgorCarlos/uSoftware-bayer-back
|
/src/auth/auth.service.ts
| 2.6875
| 3
|
import { Injectable } from '@nestjs/common';
import { UserService } from 'src/user/user.service';
import { JwtService } from '@nestjs/jwt';
import { InUserDto } from 'src/dto/in-user.dto';
@Injectable()
export class AuthService {
constructor(
readonly userService: UserService,
readonly jwtService: JwtService
){}
async authenticate(email: string, password: string){
const user = await this.userService.getUserByEmail(email)
if(!user)
throw new Error('NOT_FOUND')
if(user.password != password)
throw new Error('WRONG_PASSWORD')
delete user.password
delete user.createdAt
delete user.updatedAt
return user
}
async signIn(user: any) {
const payload = {...user}
return {
access_token: this.jwtService.sign(payload),
...user
}
}
async signUp(inUserDto: InUserDto){
const user = await this.userService.getUserByEmail(inUserDto.email)
if(user)
throw new Error('USER_ALREADY_EXITS')
return await this.userService.saveUser(inUserDto)
}
}
|
f1cc781be0a9c1c3b07dd6e4d992f82a8e3a9820
|
TypeScript
|
sciffany/cadet-frontend
|
/src/features/game/layer/GameLayerManager.ts
| 2.765625
| 3
|
import { defaultLayerSequence, Layer } from './GameLayerTypes';
import { fadeIn } from '../effects/FadeEffect';
import { Constants } from '../commons/CommonConstants';
import GameActionManager from 'src/features/game/action/GameActionManager';
import { sleep } from '../utils/GameUtils';
type Container = Phaser.GameObjects.Container;
type GameObject = Phaser.GameObjects.GameObject;
const { Container } = Phaser.GameObjects;
class GameLayerManager {
private mainLayer: Phaser.GameObjects.Container | undefined;
private layers: Map<Layer, Container>;
constructor() {
this.mainLayer = undefined;
this.layers = new Map<Layer, Container>();
}
public initialiseMainLayer(scene: Phaser.Scene) {
this.mainLayer = new Phaser.GameObjects.Container(scene, 0, 0);
scene.add.existing(this.mainLayer);
for (const layerType of defaultLayerSequence) {
const layerContainer = new Container(scene, 0, 0);
this.layers.set(layerType, layerContainer);
this.mainLayer.add(layerContainer);
}
}
public getLayer(layerType: Layer) {
return this.layers.get(layerType);
}
public hideLayer(layerType: Layer) {
const layerToHide = this.layers.get(layerType);
layerToHide && layerToHide.setVisible(false);
}
public showLayer(layerType: Layer) {
const layerToHide = this.layers.get(layerType);
layerToHide && layerToHide.setVisible(true);
}
public async fadeInLayer(layerType: Layer, fadeDuration = Constants.fadeDuration) {
const gameManager = GameActionManager.getInstance().getGameManager();
if (!gameManager) {
return;
}
const layerToFadeIn = this.layers.get(layerType);
if (!layerToFadeIn) {
return;
}
layerToFadeIn.setAlpha(0);
gameManager.tweens.add(fadeIn([layerToFadeIn], fadeDuration));
sleep(fadeDuration);
}
public addToLayer(layerType: Layer, gameObject: GameObject) {
const layerContainer = this.layers.get(layerType);
if (!layerContainer) {
return;
}
layerContainer.add(gameObject);
}
public clearSeveralLayers(layerTypes: Layer[], withFade = false) {
layerTypes.forEach(layerType => this.clearLayerContents(layerType));
}
public clearAllLayers() {
this.layers.forEach((_, layerType) => this.clearLayerContents(layerType));
}
public clearLayerContents(layerType: Layer) {
const layerContainer = this.layers.get(layerType);
if (!layerContainer) {
return;
}
layerContainer.list.map((gameObject: GameObject) => gameObject.destroy());
}
}
export default GameLayerManager;
|
21b53b21e363b8fae973a3a1cf37c43354ea246c
|
TypeScript
|
B10715018/ticketing
|
/nats-test/src/publisher.ts
| 2.59375
| 3
|
import nats from 'node-nats-streaming';
import {TicketCreatedPublisher} from './events/ticket-created-publisher';
console.clear();
//stan === client
const stan=nats.connect('ticketing','abc',{
url:'http://localhost:4222',
});
//listener
stan.on('connect',async()=>{
console.log('Publisher connected to NATs');
const publisher= new TicketCreatedPublisher(stan);
try{
await publisher.publish({
id:'123',
title:'concert',
price:20
});
} catch(err)
{
console.log(err);
}
// const data=JSON.stringify({
// id: '123',
// title: 'concert',
// price: 20
// });
// //masukin ke channel di nats streaming server
// stan.publish('ticket:created',data,()=>{
// console.log('Published event');
// });
});
|
b5df4509f1eb539815328bc6ab0fa636dbc1584c
|
TypeScript
|
ksquareincmx/ks-hire-backend
|
/app/controllers/v1/Location.ts
| 2.640625
| 3
|
import { Router, Request, Response } from "express";
import { Controller } from "../../libraries/Controller";
import { Countries } from "../../models/Countries";
import { States } from "../../models/States";
import { Cities } from "../../models/Cities";
export class LocationController extends Controller {
constructor() {
super();
this.name = "location";
}
routes(): Router {
this.router.get("/countries", (req, res) => this.countries(req, res));
this.router.get("/states/:countryId", (req, res) => this.states(req, res));
this.router.get("/cities/:stateId", (req, res) => this.cities(req, res));
return this.router;
}
async countries(req: Request, res: Response) {
try {
const countries = await Countries.findAll();
return res.status(201).json(countries);
} catch (error) {
console.log(error);
Controller.serverError(res);
}
}
async states(req: Request, res: Response) {
try {
const states = await States.findAll({
order: [["name", "ASC"]],
where: {
country_id: req.params.countryId,
},
});
return res.status(201).json(states);
} catch (error) {
console.log(error);
Controller.serverError(res);
}
}
async cities(req: Request, res: Response) {
try {
const cities = await Cities.findAll({
order: [["name", "ASC"]],
where: {
state_id: req.params.stateId,
},
});
return res.status(201).json(cities);
} catch (error) {
console.log(error);
Controller.serverError(res);
}
}
}
const location = new LocationController();
export default location;
|
d85c346a48ed6063792f3e5fd8e3956a9df04ab5
|
TypeScript
|
ha-nagisa/BunBunBIKE
|
/src/store/slices/loggedInUserPhotosSlice.ts
| 2.609375
| 3
|
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { responcePhotoDataWithUserInfo } from '../../models/responceData';
interface UpdatePhotoActionType {
docId: string;
title: string;
description: string;
workImageUrl: string;
category: string;
workMoney: string;
workHours: string;
}
interface updateLikesPhotoActionType {
docId: string;
userId: string;
toggleLiked: boolean;
}
interface updateCommentsPhotoActionType {
docId: string;
displayName: string;
comment: string;
}
interface updateLoggeInUserNameActionType {
username: string;
}
export const loggedInUserPhotosSlice = createSlice({
name: 'loggedInUserPhotos',
initialState: {
loggedInUserPhotos: [] as responcePhotoDataWithUserInfo[],
},
reducers: {
setLoggedInUserPhotos: (state, action: PayloadAction<responcePhotoDataWithUserInfo[]>) => {
state.loggedInUserPhotos = action.payload;
},
logoutLoggedInUserPhotos: (state) => {
state.loggedInUserPhotos = [
{
maker: '',
carModel: '',
category: '',
comments: [],
dateCreated: 0,
description: '',
imageSrc: '',
likes: [''],
title: '',
userId: '',
workHours: '',
workMoney: '',
docId: '',
userLikedPhoto: false,
username: '',
},
];
},
addLoggedInUserPhoto: (state, action: PayloadAction<responcePhotoDataWithUserInfo>) => {
state.loggedInUserPhotos = [...state.loggedInUserPhotos, action.payload];
},
updatePhoto: (state, action: PayloadAction<UpdatePhotoActionType>) => {
state.loggedInUserPhotos = state.loggedInUserPhotos.map((userPhoto) => {
if (userPhoto.docId === action.payload.docId) {
userPhoto.title = action.payload.title;
userPhoto.description = action.payload.description;
userPhoto.imageSrc = action.payload.workImageUrl;
userPhoto.category = action.payload.category;
userPhoto.workMoney = action.payload.workMoney;
userPhoto.workHours = action.payload.workHours;
}
return userPhoto;
});
},
updateLikesPhoto: (state, action: PayloadAction<updateLikesPhotoActionType>) => {
state.loggedInUserPhotos = state.loggedInUserPhotos.map((photo) => {
if (photo.docId === action.payload.docId) {
photo.userLikedPhoto = !photo.userLikedPhoto;
photo.likes = action.payload.toggleLiked
? photo.likes.filter((uId) => uId !== action.payload.userId)
: [...photo.likes, action.payload.userId];
}
return photo;
});
},
updateCommentsPhoto: (state, action: PayloadAction<updateCommentsPhotoActionType>) => {
state.loggedInUserPhotos = state.loggedInUserPhotos.map((photo) => {
if (photo.docId === action.payload.docId) {
photo.comments = [...photo.comments, { displayName: action.payload.displayName, comment: action.payload.comment }];
}
return photo;
});
},
updateLoggeInUserName: (state, action: PayloadAction<updateLoggeInUserNameActionType>) => {
state.loggedInUserPhotos = state.loggedInUserPhotos.map((photo) => {
if (photo.comments.some((com) => com.displayName === photo.username)) {
photo.comments = photo.comments.map((com) => {
if (com.displayName === photo.username) {
com.displayName = action.payload.username;
}
return com;
});
}
photo.username = action.payload.username;
return photo;
});
},
},
});
type RootState = {
loggedInUserPhotos: {
loggedInUserPhotos: responcePhotoDataWithUserInfo[];
};
};
export const {
setLoggedInUserPhotos,
logoutLoggedInUserPhotos,
updatePhoto,
addLoggedInUserPhoto,
updateLikesPhoto,
updateCommentsPhoto,
updateLoggeInUserName,
} = loggedInUserPhotosSlice.actions;
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const selectLoggedInUserPhotos = (state: RootState) => state.loggedInUserPhotos.loggedInUserPhotos;
export default loggedInUserPhotosSlice.reducer;
|
06d3051e55c5bc0f0163332bc12d2a13f5d1e113
|
TypeScript
|
mzpkjs/prototypes
|
/visual-layer-editor/lib/Core/Behaviour/RotatableBehaviour.ts
| 2.796875
| 3
|
import { throttle } from "../common"
import Shape from "../Shape/Shape"
class RotatableBehaviour {
private readonly _target: Shape
private readonly _state = {
initialized: null,
active: false,
cursor: ""
}
public static enabled = true
constructor(target: Shape) {
this._target = target
this._state.initialized = requestAnimationFrame(() => {
this._target.element.addEventListener("mousedown", this._onmousedown)
document.addEventListener("mouseup", this._onmouseup)
document.addEventListener("wheel", this._onscroll)
})
}
public destroy(): void {
if (this._state.initialized !== null) {
cancelAnimationFrame(this._state.initialized)
} else {
this._target.element.removeEventListener("mousedown", this._onmousedown)
document.removeEventListener("mouseup", this._onmouseup)
document.removeEventListener("scroll", this._onscroll)
}
}
private readonly _onmousedown = (event: MouseEvent): void => {
event.preventDefault()
if (RotatableBehaviour.enabled) {
this._state.active = true
this._target.element.classList.add("active")
}
}
private readonly _onmouseup = (event: MouseEvent): void => {
event.preventDefault()
if (RotatableBehaviour.enabled) {
this._state.active = false
this._target.element.classList.remove("active")
}
}
private readonly _onscroll = (event: WheelEvent) => {
if (RotatableBehaviour.enabled) {
const speed = 0.025
this._target.direction += speed * Math.PI * Math.sign(event.deltaY)
const rotationEl = document.querySelector(".rotation")
rotationEl.textContent = `${(this._target.direction * (180 / Math.PI)).toFixed(2)}°`
}
}
}
export default RotatableBehaviour
|
3e3c48b7a1304073d1ea3cabe644872ca215dd90
|
TypeScript
|
tcgdex/cards-database
|
/data/Sun & Moon/Celestial Storm/9.ts
| 2.53125
| 3
|
import { Card } from '../../../interfaces'
import Set from '../Celestial Storm'
const card: Card = {
name: {
en: "Grovyle",
fr: "Massko",
es: "Grovyle",
it: "Grovyle",
pt: "Grovyle",
de: "Reptain"
},
illustrator: "Shin Nagasawa",
rarity: "Uncommon",
category: "Pokemon",
set: Set,
dexId: [
253,
],
hp: 80,
types: [
"Grass",
],
evolveFrom: {
en: "Treecko",
fr: "Arcko",
},
stage: "Stage1",
attacks: [
{
cost: [
"Grass",
],
name: {
en: "Leaf Blade",
fr: "Lame-Feuille",
es: "Hoja Aguda",
it: "Fendifoglia",
pt: "Lâmina de Folha",
de: "Laubklinge"
},
effect: {
en: "Flip a coin. If heads, this attack does 40 more damage.",
fr: "Lancez une pièce. Si c’est face, cette attaque inflige 40 dégâts supplémentaires.",
es: "Lanza 1 moneda. Si sale cara, este ataque hace 40 puntos de daño más.",
it: "Lancia una moneta. Se esce testa, questo attacco infligge 40 danni in più.",
pt: "Jogue 1 moeda. Se sair cara, este ataque causará 40 pontos de dano a mais.",
de: "Wirf 1 Münze. Bei Kopf fügt diese Attacke 40 Schadenspunkte mehr zu."
},
damage: "20+",
},
],
weaknesses: [
{
type: "Fire",
value: "×2"
},
],
retreat: 1,
}
export default card
|
27689f69cf4d1b55a6b5f9139687ef20579b9a12
|
TypeScript
|
sabinmarcu/memorize
|
/packages/config/src/utils.ts
| 2.890625
| 3
|
import {
KeyValue,
KV,
Obj,
ConfigID,
IConfig,
IsSetterKey,
IsDynamicKey,
IsProxyKey,
IsOwnKey,
OnlySetters,
OnlyDynamicSetters,
OnlyProxies,
PropertyToSetter,
OwnPropertyKey,
PropertiesToObject,
} from './types';
export const propertyToSetter = <
S extends OwnPropertyKey,
>(
property: S,
): PropertyToSetter<S> => {
if (typeof property === 'string') {
return `set${property[0].toUpperCase()}${property.slice(1)}` as any as PropertyToSetter<S>;
}
return `set${property}` as PropertyToSetter<S>;
};
export const keyValue = <T extends Obj>(
source: T,
): KeyValue<T>[] => [
...Object.getOwnPropertyNames(source),
...Object.getOwnPropertySymbols(source),
].reduce(
(acc, key) => [
...acc,
{
key,
value: source[key],
},
],
[] as any,
) as KeyValue<T>[];
export const isSetterKey = <
T extends KV,
>(
source: T,
): source is IsSetterKey<T> => (
typeof source.key === 'string'
);
export const onlySetterKeys = <
T extends KV,
>(
source: T[],
): IsSetterKey<T>[] => (
source.filter(isSetterKey)
);
export const isDynamicKey = <
T extends KV,
>(
source: T,
): source is IsDynamicKey<T> => (
!isSetterKey(source)
);
export const onlyDynamicKeys = <
T extends KV,
>(
source: T[],
): IsDynamicKey<T>[] => (
source.filter(isDynamicKey)
);
export const isProxyKey = <
T extends KV,
>(
source: T,
): source is IsProxyKey<T> => (
!!source.value[ConfigID]
);
export const onlyProxyKeys = <
T extends KV,
>(
source: T[],
): IsProxyKey<T>[] => (
source.filter(isProxyKey)
);
export const isOwnKey = <
T extends KV,
>(
source: T,
): source is IsOwnKey<T> => (
!isProxyKey(source)
);
export const onlyOwnKeys = <
T extends KV,
>(
source: T[],
): IsOwnKey<T>[] => (
source.filter(isOwnKey)
);
export const onlySetters = <
T extends KV,
>(
source: T[],
): OnlySetters<T>[] => (
onlySetterKeys(onlyOwnKeys(source))
);
export const onlyDynamicSetters = <
T extends KV,
>(
source: T[],
): OnlyDynamicSetters<T>[] => (
onlyDynamicKeys(onlyOwnKeys(source))
);
export const onlyProxies = <
T extends KV,
>(
source: T[],
): OnlyProxies<T>[] => (
onlyProxyKeys(source)
);
export const isConfig = (
it: any,
): it is IConfig => typeof it[ConfigID] !== 'undefined';
export const propsToObject = <
T extends KV,
>(
src: T[],
): PropertiesToObject<T> => src.reduce(
(acc, { key, value }) => ({
...acc,
[key]: value,
}),
{},
) as PropertiesToObject<T>;
export const allKeys = (
obj: Obj,
) => new Set<PropertyKey>([
...Object.getOwnPropertySymbols(obj),
...Object.keys(Object.getOwnPropertyDescriptors(obj)),
]) as Set<PropertyKey>;
export const areEqual = (
A: Obj,
B: Obj,
): boolean => {
const AKeys = allKeys(A);
const BKeys = allKeys(B);
if (AKeys.size !== BKeys.size) {
return false;
}
return [...AKeys].every((it) => BKeys.has(it));
};
export const getSubset = (
A: Obj,
B: Obj,
): Obj | undefined => {
const AKeys = allKeys(A);
const BKeys = allKeys(B);
if ([...BKeys].every((it) => AKeys.has(it))) {
const proc = [...AKeys].filter((it) => !BKeys.has(it))
.reduce((acc, it) => ({
...acc,
[it]: A[it],
}), {});
return proc;
}
return undefined;
};
|
fc260f0f93c42afc9dfd50e9259267c1bf8f42d7
|
TypeScript
|
JohanG2012/scrape-helpers
|
/src/fs-helpers.ts
| 3.0625
| 3
|
import fs from "fs";
import { readdirSync, statSync } from "fs";
import { join } from "path";
export const copyFile = (source: string, dest: string): Promise<any> =>
new Promise((resolve, reject) => {
fs.copyFile(source, dest, err => {
if (err) return reject(err);
return resolve();
});
});
export const readJSONFile = (source: string): Promise<any> =>
new Promise((resolve, reject) => {
fs.readFile(source, (err, data) => {
if (err) return reject(err);
const result = JSON.parse(data.toString());
return resolve(result);
});
});
export const renameFile = (source: string, dest: string): Promise<any> =>
new Promise((resolve, reject) => {
fs.rename(source, dest, function(err) {
if (err) return reject(err);
return resolve();
});
});
const reservedUnixNames = () => /[<>:"\/\\|?*\x00-\x1F]/g;
const reservedWindowsNames = () => /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i;
export const createDirIfNotExists = (dir: string) =>
!fs.existsSync(dir) && fs.mkdirSync(dir, { recursive: true });
export const validFilename = (fileName: string) => {
if (!fileName || fileName.length > 255) {
return false;
}
if (
reservedUnixNames().test(fileName) ||
reservedWindowsNames().test(fileName)
) {
return false;
}
if (/^\.\.?$/.test(fileName)) {
return false;
}
return true;
};
export const isDirectory = (path: string) => statSync(path).isDirectory();
export const getDirectories = (path: string) =>
readdirSync(path)
.map(name => join(path, name))
.filter(isDirectory);
export const isFile = (path: string) => statSync(path).isFile();
export const getFiles = (path: string) =>
readdirSync(path)
.map(name => join(path, name))
.filter(isFile);
export const getFilesRecursively = (path: string): any => {
let dirs = getDirectories(path);
let files = dirs
.map(dir => getFilesRecursively(dir)) // go through each directory
.reduce((a, b) => a.concat(b), []); // map returns a 2d array (array of file arrays) so flatten
return files.concat(getFiles(path));
};
export const copyRecursiveSync = (source: string, dest: string) => {
const exists = fs.existsSync(source);
const isDir = exists && isDirectory(source);
if (isDir) {
createDirIfNotExists(dest);
fs.readdirSync(source).forEach(function(childItemName) {
copyRecursiveSync(join(source, childItemName), join(dest, childItemName));
});
} else {
fs.copyFileSync(source, dest);
}
};
|
d9cfc34658a775d3eb38da48239a7354f3287793
|
TypeScript
|
VictorGabriel-Oliveira/letmeask
|
/src/hooks/useRoom.ts
| 2.75
| 3
|
import { useState , useEffect, useContext} from "react"
import { AuthContext } from "../contexts/AuthContext"
import { data } from '../services/firebase'
type QuestionsType = {
id:string,
author:{
name:string,
avatar:string,
},
content:string,
isAnswered:boolean,
isHighlighted:boolean,
likeCount:number,
likeId:string | undefined,
}
type FirebaseQuestions = Record<string ,{
author:{
name:string,
avatar:string,
},
content:string,
isAnswered:boolean,
isHighlighted:boolean,
like:Record<string,{
authorId:string,
}>
}>
export function useRoom( roomId: string){
const user = useContext(AuthContext)
const [questions, setQuestions]= useState<QuestionsType[]>([])
const [title, setTitle]=useState('')
useEffect(()=>{
const roomRef = data.ref(`rooms/${roomId}`)
roomRef.on('value', room => {
const databaseRoom = room.val()
const firebaseQuestions: FirebaseQuestions = databaseRoom?.questions
const parsedQuestions = Object.entries(firebaseQuestions ?? {} ).map(([key,value])=>{
return {
id:key,
content: value.content,
author: value.author,
isHighlighted: value.isHighlighted,
isAnswered: value.isAnswered,
likeCount: Object.values(value.like ?? {} ).length,
likeId: Object.entries(value.like ?? {} ).find(([key,like]) => like.authorId === user.user?.id)?.[0]
}
})
setTitle(databaseRoom?.title)
setQuestions(parsedQuestions)
})
return()=>{
roomRef.off("value")
}
},[roomId,user.user?.id])
return{
questions,
title
}
}
|
1a3caac77141237e3061fb3601fdc9042b2a5611
|
TypeScript
|
NalinLuthra/rx-player
|
/src/core/fetchers/segment/segment_fetcher_creator.ts
| 2.609375
| 3
|
/**
* Copyright 2015 CANAL+ Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Subject } from "rxjs";
import config from "../../../config";
import { ITransportPipelines } from "../../../transports";
import {
IABRMetricsEvent,
IABRRequestBeginEvent,
IABRRequestEndEvent,
IABRRequestProgressEvent,
} from "../../abr";
import { IBufferType } from "../../source_buffers";
import getSegmentBackoffOptions from "./get_segment_backoff_options";
import applyPrioritizerToSegmentFetcher, {
IPrioritizedSegmentFetcher,
} from "./prioritized_segment_fetcher";
import ObservablePrioritizer from "./prioritizer";
import createSegmentFetcher, {
ISegmentFetcherEvent,
} from "./segment_fetcher";
const { MIN_CANCELABLE_PRIORITY,
MAX_HIGH_PRIORITY_LEVEL } = config;
/** Options used by the `SegmentFetcherCreator`. */
export interface ISegmentFetcherCreatorBackoffOptions {
/**
* Whether the content is played in a low-latency mode.
* This has an impact on default backoff delays.
*/
lowLatencyMode : boolean;
/** Maximum number of time a request on error will be retried. */
maxRetryRegular : number | undefined;
/** Maximum number of time a request be retried when the user is offline. */
maxRetryOffline : number | undefined;
}
/**
* Interact with the transport pipelines to download segments with the right
* priority.
*
* @class SegmentFetcherCreator
*
* @example
* ```js
* const creator = new SegmentFetcherCreator(transport);
*
* // 2 - create a new fetcher with its backoff options
* const fetcher = creator.createSegmentFetcher("audio", {
* maxRetryRegular: Infinity,
* maxRetryOffline: Infinity,
* });
*
* // 3 - load a segment with a given priority
* fetcher.createRequest(myContent, 1)
* // 4 - parse it
* .pipe(
* filter(evt => evt.type === "chunk"),
* mergeMap(response => response.parse());
* )
* // 5 - use it
* .subscribe((res) => console.log("audio chunk downloaded:", res));
* ```
*/
export default class SegmentFetcherCreator<T> {
private readonly _transport : ITransportPipelines;
private readonly _prioritizer : ObservablePrioritizer<ISegmentFetcherEvent<T>>;
private readonly _backoffOptions : ISegmentFetcherCreatorBackoffOptions;
/**
* @param {Object} transport
*/
constructor(
transport : ITransportPipelines,
options : ISegmentFetcherCreatorBackoffOptions
) {
this._transport = transport;
this._prioritizer = new ObservablePrioritizer({
prioritySteps: { high: MAX_HIGH_PRIORITY_LEVEL,
low: MIN_CANCELABLE_PRIORITY },
});
this._backoffOptions = options;
}
/**
* Create a segment fetcher, allowing to easily perform segment requests.
* @param {string} bufferType - The type of buffer concerned (e.g. "audio",
* "video", etc.)
* @param {Subject} requests$ - Subject through which request-related events
* (such as those needed by the ABRManager) will be sent.
* @returns {Object}
*/
createSegmentFetcher(
bufferType : IBufferType,
requests$ : Subject<IABRRequestBeginEvent |
IABRRequestProgressEvent |
IABRRequestEndEvent |
IABRMetricsEvent>
) : IPrioritizedSegmentFetcher<T> {
const backoffOptions = getSegmentBackoffOptions(bufferType, this._backoffOptions);
const segmentFetcher = createSegmentFetcher<T>(bufferType,
this._transport,
requests$,
backoffOptions);
return applyPrioritizerToSegmentFetcher<T>(this._prioritizer, segmentFetcher);
}
}
|
2b482594736f3bc8c1dc06d316f4ba2f88efe525
|
TypeScript
|
NickCaminer/dgraph-orm
|
/src/metadata/with-facet.ts
| 2.6875
| 3
|
import { Constructor } from '../utils/class';
export class WithFacetMetadata {
constructor(readonly args: WithFacetMetadata.IArgs) {
//
}
}
export namespace WithFacetMetadata {
export interface IArgs {
/**
* Target class which the facet is added to.
*/
target: Object;
/**
* Name of the property which facet is applied to.
*/
propertyName: string;
/**
* Constructor class of the facet definition.
*/
constructor: Constructor;
}
}
|
937aff89955ce9f4c0996850109f83bfdf91fed4
|
TypeScript
|
tcgdex/cards-database
|
/data/Sun & Moon/Unbroken Bonds/233.ts
| 2.640625
| 3
|
import { Card } from '../../../interfaces'
import Set from '../Unbroken Bonds'
const card: Card = {
name: {
en: "Pokégear 3.0",
fr: "Pokématos 3.0",
es: "Pokégear 3.0",
it: "Pokégear 3.0",
pt: "Pokégear 3.0",
de: "Pokécom 3.0"
},
illustrator: "Studio Bora Inc.",
rarity: "Secret Rare",
category: "Trainer",
set: Set,
trainerType: "Item",
effect: {
en: "Look at the top 7 cards of your deck. You may reveal a Supporter card you find there and put it into your hand. Shuffle the other cards back into your deck.",
fr: "Regardez les 7 cartes du dessus de votre deck. Vous pouvez montrer une carte Supporter que vous y trouvez, puis l’ajouter à votre main. Mélangez les autres cartes avec votre deck.",
es: "Mira las 7 primeras cartas de tu baraja. Puedes enseñar 1 carta de Partidario que encuentres entre ellas y ponerla en tu mano. Pon el resto de cartas de nuevo en tu baraja y barájalas todas.",
it: "Guarda le prime sette carte del tuo mazzo. Puoi mostrare una carta Aiuto presente tra esse e aggiungerla alle carte che hai in mano. Poi rimischia le altre carte nel tuo mazzo.",
pt: "Olhe as 7 primeiras cartas do seu baralho. Você poderá revelar 1 carta de Apoiador que encontrar lá e colocá-la na sua mão. Embaralhe as demais cartas de volta no seu baralho.",
de: "Schau dir die obersten 7 Karten deines Decks an. Du kannst 1 Unterstützerkarte, die du dort findest, deinem Gegner zeigen und auf deine Hand nehmen. Mische die anderen Karten zurück in dein Deck."
}
}
export default card
|
b21631c4068227e1f2ec747785ea03bb39cafde1
|
TypeScript
|
jorgecasar/pwa-auth
|
/src/google-provider.ts
| 2.5625
| 3
|
import { SignInResult } from "./signin-result";
export class GoogleProvider {
private resolve: ((result: SignInResult) => void) | null = null;
private reject: ((error: any) => void) | null = null;
static readonly apiUrl = "https://apis.google.com/js/api:client.js";
constructor(private clientId: string, private shadowRoot: ShadowRoot) {
}
signIn(): Promise<SignInResult> {
this.resolve = null;
this.reject = null;
return new Promise<SignInResult>((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
this.appendGoogleScript();
});
}
private appendGoogleScript() {
const gapiLoad = window.gapi?.auth2;
if (!gapiLoad) {
const scriptEl = window.document.createElement("script");
scriptEl.async = true;
scriptEl.src = GoogleProvider.apiUrl;
scriptEl.onload = () => this.scriptLoadSucceded();
scriptEl.onerror = (error) => this.scriptLoadFailed(error);
window.document.head.appendChild(scriptEl);
} else {
this.loadAuth();
}
}
private scriptLoadSucceded() {
if (!gapi?.load) {
this.reject?.("Google Platform library loaded, but couldn't find window.gapi.load");
} else {
this.loadAuth();
}
}
private scriptLoadFailed(error: string | Event) {
console.error("Error loading Google Platform library", error);
this.reject?.(error);
}
private loadAuth() {
window.gapi.load("auth2", () => this.initAuth());
}
private initAuth() {
const auth = gapi.auth2.init({
client_id: this.clientId,
cookie_policy: "single_host_origin"
});
const signInOptions: gapi.auth2.SigninOptions = { };
// Speed through the process if we're already signed in.
if (auth.isSignedIn.get()) {
const user = auth.currentUser.get();
this.signInSucceeded(user);
} else {
const fakeBtn = this.getOrCreateFakeBtn();
auth.attachClickHandler(fakeBtn,
signInOptions,
user => this.signInSucceeded(user),
error => this.signInFailed(error));
fakeBtn.click();
}
}
private getOrCreateFakeBtn() {
// This needs to be done because Google Platform API requires you to attach a
// click handler to an actual element. This fake button will be our actual element.
let fakeBtn = this.shadowRoot.querySelector("#pwa-auth-google-sign-in-pseudo-btn") as HTMLButtonElement;
if (!fakeBtn) {
fakeBtn = document.createElement("button");
fakeBtn.style.display = "none";
this.shadowRoot.appendChild(fakeBtn);
};
return fakeBtn;
}
private signInSucceeded(user: gapi.auth2.GoogleUser) {
const loginResult = this.getLoginResult(user);
this.resolve?.(loginResult);
}
private signInFailed(error: any) {
this.reject?.(error);
}
private getLoginResult(user: gapi.auth2.GoogleUser): SignInResult {
const profile = user.getBasicProfile();
return {
email: profile.getEmail(),
name: profile.getName(),
imageUrl: profile.getImageUrl(),
provider: "Google",
error: null,
providerData: user
};
}
}
|
485b7e830ce21bee0a38cb00a0baa3e072fcf087
|
TypeScript
|
chrisd08/typescript-observable
|
/src/observable.ts
| 3.203125
| 3
|
import "core-js/es6/promise";
import "core-js/es6/array";
import "core-js/es6/set";
import {
IObservable,
IObserverItem,
IObservableEvent,
ObserverCallback,
IObserver,
ICancel,
ObservableEventType,
} from ".";
/**
* Check if the item is of type IObservableEvent
* @param tested is the parameter to be tested
* @return {boolean} true if the item is instance of IObservableEvent, otherwise false
*/
function isObservableEvent(arg: ObservableEventType): arg is IObservableEvent {
return !!arg && typeof arg !== "string";
}
/**
* Check if the item is of type IObserver
* @param arg is the parameter to be tested
* @return {boolean} true if the item is instance of IObserver, otherwise false
*/
function isObserver(arg: ObserverCallback | IObserver): arg is IObserver {
return !!arg && typeof arg !== "function";
}
export class Observable implements IObservable {
private observers: IObserverItem[] = [];
public count = (): number => this.observers.length;
public clear = (): void => {
this.observers.length = 0;
};
public on(
type: ObservableEventType | ObservableEventType[],
callback: ObserverCallback | IObserver
): ICancel {
const id: ICancel = {
cancel: () => {
const index = this.observers.findIndex(item => item.id === id);
return index > -1 && !!this.observers.splice(index, 1);
},
};
const types = new Set(
(Array.isArray(type) ? type : [type]).map(item =>
isObservableEvent(item) ? item.name : item
)
);
this.observers.push({
id,
callback,
types,
});
return id;
}
public off(observer: IObserver): boolean {
const index = this.observers.findIndex(item => item.callback === observer);
return index > -1 && !!this.observers.splice(index, 1);
}
public notify(event: IObservableEvent, data: unknown): Promise<void> {
// Make non-blocking
return Promise.resolve().then(() => {
const { name: calledEventName } = event,
typesToCall = [calledEventName];
// Select all events to be called
while (event.parent) {
event = event.parent;
typesToCall.push(event.name);
}
// Call all observers having the type
this.observers.forEach(({ types, callback }) => {
if (typesToCall.some(type => types.has(type))) {
const call = isObserver(callback) ? callback.update : callback;
call(data, calledEventName);
}
});
});
}
}
|
3611ab2b2fff5161d7165d3660a0ff5cd56f0039
|
TypeScript
|
olimorri/codehort
|
/server/src/task/task.controller.ts
| 2.625
| 3
|
import {
Body,
Controller,
Get,
Param,
Post,
NotFoundException,
InternalServerErrorException,
} from '@nestjs/common';
import { TaskDto } from './dto/task.dto';
import { TaskService } from './task.service';
@Controller('task')
export class TaskController {
constructor(private taskService: TaskService) {}
@Post()
async createTasks(@Body() tasks: TaskDto[]): Promise<string> {
try {
await this.taskService.createTasks(tasks);
return 'tasks saved';
} catch (error) {
throw new InternalServerErrorException('An internal server error occured');
}
}
@Get(':id')
async getTask(@Param('id') id: number): Promise<TaskDto> {
const newTask = await this.taskService.fetchTask(id);
if (!newTask) throw new NotFoundException(`Task for id ${id} could not be found`);
return newTask;
}
}
|
95d7ca9cb97b5c91d6990428fa68bd720664d9e2
|
TypeScript
|
WendyChenj/burger-queen
|
/src/common/store/customBurgerStore/customBurgerReducer.ts
| 2.84375
| 3
|
import { Meat, Vegetable, BurgerState, Cheese, Sauce } from '../../models/customBurgerTypes';
import {
CustomBurgerActionTypes,
CHOOSE_BURGER_BREAD,
ADD_BURGER_MEAT,
REMOVE_BURGER_MEAT,
ADD_BURGER_VEGETABLE,
REMOVE_BURGER_VEGETABLE,
ADD_BURGER_CHEESE,
REMOVE_BURGER_CHEESE,
ADD_BURGER_SAUCE,
REMOVE_BURGER_SAUCE,
} from './customBurgerActionTypes';
const initialState: BurgerState = {
bread: 'hamburger',
vegetable: [
{
name: 'tomato',
amount: 0,
price: 0.5,
},
{
name: 'lettuce',
amount: 0,
price: 0.5,
},
{
name: 'pickle',
amount: 0,
price: 0.5,
},
],
meat: [
{
name: 'beef',
amount: 0,
price: 1.8,
},
{
name: 'chicken',
amount: 0,
price: 1.5,
},
{
name: 'ham',
amount: 0,
price: 1.2,
},
{
name: 'bacon',
amount: 0,
price: 1.2,
},
],
cheese: [
{
name: 'white processed cheddar',
amount: 0,
price: 0.3,
},
{
name: 'shredded monterey cheddar',
amount: 0,
price: 0.3,
},
],
sauce: [
{
name: 'mayo',
choose: false,
},
{
name: 'mustard',
choose: false,
},
],
totalPrice: 2.0,
};
const customBurgerReducer = (state: BurgerState = initialState, action: CustomBurgerActionTypes): BurgerState => {
switch (action.type) {
case CHOOSE_BURGER_BREAD:
return {
...state,
bread: action.bread,
};
case ADD_BURGER_MEAT:
let addedMeatPrice = 0;
const addedMeat = state.meat.map((ele: Meat) => {
if (ele.name === action.meatName) {
addedMeatPrice = ele.price;
return {
...ele,
amount: (ele.amount += 1),
};
} else {
return ele;
}
});
return {
...state,
meat: addedMeat,
totalPrice: state.totalPrice + addedMeatPrice,
};
case REMOVE_BURGER_MEAT:
let deductedMeatPrice = 0;
const removedMeat = state.meat.map((ele: Meat) => {
if (ele.name === action.meatName) {
deductedMeatPrice = ele.price;
return {
...ele,
amount: (ele.amount -= 1),
};
} else {
return ele;
}
});
return {
...state,
meat: removedMeat,
totalPrice: state.totalPrice - deductedMeatPrice,
};
case ADD_BURGER_VEGETABLE:
let addedVegetablePrice = 0;
const addedVeg = state.vegetable.map((ele: Vegetable) => {
if (ele.name === action.vegName) {
addedVegetablePrice = ele.price;
return {
...ele,
amount: (ele.amount += 1),
};
} else {
return ele;
}
});
return {
...state,
vegetable: addedVeg,
totalPrice: state.totalPrice + addedVegetablePrice,
};
case REMOVE_BURGER_VEGETABLE:
let deductedVegetablePrice = 0;
const removedVeg = state.vegetable.map((ele: Vegetable) => {
if (ele.name === action.vegName) {
deductedVegetablePrice = ele.price;
return {
...ele,
amount: (ele.amount -= 1),
};
} else {
return ele;
}
});
return {
...state,
vegetable: removedVeg,
totalPrice: state.totalPrice - deductedVegetablePrice,
};
case ADD_BURGER_CHEESE:
let addedCheesePrice = 0;
const addedCheese = state.cheese.map((ele: Cheese) => {
if (ele.name === action.cheeseName) {
addedCheesePrice = ele.price;
return {
...ele,
amount: (ele.amount += 1),
};
} else {
return ele;
}
});
return {
...state,
cheese: addedCheese,
totalPrice: state.totalPrice + addedCheesePrice,
};
case REMOVE_BURGER_CHEESE:
let deductedCheesePrice = 0;
const removedCheese = state.cheese.map((ele: Cheese) => {
if (ele.name === action.cheeseName) {
deductedCheesePrice = ele.price;
return {
...ele,
amount: (ele.amount -= 1),
};
} else {
return ele;
}
});
return {
...state,
cheese: removedCheese,
totalPrice: state.totalPrice - deductedCheesePrice,
};
case ADD_BURGER_SAUCE:
const addedSauce = state.sauce.map((ele: Sauce) => {
if (ele.name === action.sauceName) {
return {
...ele,
choose: true,
};
} else {
return ele;
}
});
return {
...state,
sauce: addedSauce,
};
case REMOVE_BURGER_SAUCE:
const removedSauce = state.sauce.map((ele: Sauce) => {
if (ele.name === action.sauceName) {
return {
...ele,
choose: false,
};
} else {
return ele;
}
});
return {
...state,
sauce: removedSauce,
};
default:
return state;
}
};
export default customBurgerReducer;
|
595434a543950ee2c004aafd38c9d3beac4f0863
|
TypeScript
|
outdatedpizzatech/2djs
|
/src/reducers/player_reducer.ts
| 2.734375
| 3
|
import { GameState } from "../game_state";
import { GRID_INTERVAL } from "../common";
import { Direction, getModsFromDirection } from "../direction";
import { isPlayer, Player, playerFactory } from "../models/player";
import { GameObject } from "../game_object";
import { cloneDeep } from "../clone_deep";
export const addPlayer = (
gameState: GameState,
player: Partial<Player> & { _id: string }
): GameState => {
const newPlayer = playerFactory(player);
if (!gameState.myClientId) {
gameState.myClientId = newPlayer.clientId;
}
gameState.players[newPlayer.clientId] = newPlayer;
return gameState;
};
export const removePlayer = (
gameState: GameState,
clientId: string
): GameState => {
delete gameState.players[clientId];
return gameState;
};
export const updatePlayerMovementDirection = (params: {
direction: Direction;
gameState: GameState;
player: Player;
}) => {
const { gameState, direction, player } = params;
const playerToUpdate = gameState.players[player.clientId];
if (playerToUpdate) {
playerToUpdate.movementQueue.push(direction);
gameState.players[player.clientId] = playerToUpdate;
}
return gameState;
};
export const updatePlayerFacingDirection = (params: {
direction: Direction;
gameState: GameState;
player: Player;
}) => {
const { gameState, direction, player } = params;
const newGameState = cloneDeep(gameState);
const playerToUpdate = newGameState.players[player.clientId];
if (playerToUpdate) {
playerToUpdate.facingDirection = direction;
newGameState.players[player.clientId] = playerToUpdate;
}
return newGameState;
};
export const updatePlayerCoordinates = (params: {
direction: Direction;
gameState: GameState;
player: Player;
}) => {
const { gameState, direction, player } = params;
const [xMod, yMod] = getModsFromDirection(direction);
const playerToUpdate = gameState.players[player.clientId];
if (playerToUpdate) {
playerToUpdate.x += xMod;
playerToUpdate.y += yMod;
gameState.players[player.clientId] = playerToUpdate;
}
return gameState;
};
export const updatePlayerMovement = (
deltaTime: number,
gameState: GameState,
player: Player
): GameState => {
const playerToUpdate = gameState.players[player.clientId];
if (!playerToUpdate) {
return gameState;
}
const { movementQueue, movementSpeed } = playerToUpdate;
const movementDirection = movementQueue[0];
const [xMod, yMod] = getModsFromDirection(movementDirection);
const destinationX = playerToUpdate.x * GRID_INTERVAL;
const destinationY = playerToUpdate.y * GRID_INTERVAL;
playerToUpdate.worldX += xMod * movementSpeed * deltaTime;
playerToUpdate.worldY += yMod * movementSpeed * deltaTime;
playerToUpdate.moving = true;
let haltMovement = false;
const { worldX, worldY } = playerToUpdate;
if (movementDirection == Direction.UP) {
haltMovement = worldY < destinationY;
if (haltMovement) playerToUpdate.worldY = destinationY;
} else if (movementDirection == Direction.DOWN) {
haltMovement = worldY > destinationY;
if (haltMovement) playerToUpdate.worldY = destinationY;
} else if (movementDirection == Direction.LEFT) {
haltMovement = worldX < destinationX;
if (haltMovement) playerToUpdate.worldX = destinationX;
} else if (movementDirection == Direction.RIGHT) {
haltMovement = worldX > destinationX;
if (haltMovement) playerToUpdate.worldX = destinationX;
}
if (haltMovement) {
playerToUpdate.moving = false;
playerToUpdate.movementQueue = playerToUpdate.movementQueue.slice(1);
}
gameState.players[player.clientId] = playerToUpdate;
return gameState;
};
export const updatePlayers = (
gameObjects: GameObject[],
gameState: GameState
) => {
const newGameState = cloneDeep(gameState);
const players = gameObjects.filter((gameObject) => {
return isPlayer(gameObject);
}) as Player[];
players
.filter((player) => player.clientId !== gameState.myClientId)
.forEach((player) => {
newGameState.players[player.clientId] = player;
});
return newGameState;
};
|
d30550029e5d178f043dbff6b6ba42fdb5104501
|
TypeScript
|
kierstone/RamenRanger
|
/RamenRanger/src/scene/msgdlg/horizontalFoodCourt/HorizontalFoodCourt_DishButton.ts
| 2.515625
| 3
|
class HorizontalFoodCourt_DishButton extends eui.Component implements eui.UIComponent {
private Label_Name:eui.Label;
private Group_Ramen:eui.Group;
private dishSpr:RamenSprite;
private Rect_ColorSign:eui.Rect;
private Button_Eat:eui.Button;
private Group_Buddy:eui.Group;
private Group_Ingredient:eui.Group;
private dish:FoodCourtDishObj;
private caller:HorizontalFoodCourt;
private eve:(caller:HorizontalFoodCourt, dish:FoodCourtDishObj)=>void;
private favourGuy:Array<FoodCourtBuddy>;
private currentHunger:number;
private hungerMax:number;
private clicked:boolean = false;
public constructor(
dish:FoodCourtDishObj, favourGuyCount:Array<FoodCourtBuddy>, currentHunger:number, hungerMax:number,
caller:HorizontalFoodCourt, eve:(caller:HorizontalFoodCourt, dish:FoodCourtDishObj)=>void
) {
super();
this.dish = dish;
this.caller = caller;
this.eve = eve;
this.favourGuy = favourGuyCount;
this.currentHunger = currentHunger;
this.hungerMax = Math.max(1, hungerMax);
}
protected partAdded(partName:string,instance:any):void
{
super.partAdded(partName,instance);
}
protected childrenCreated():void
{
super.childrenCreated();
this.init();
}
private init(){
this.dishSpr = new RamenSprite(this.dish.dish);
this.Group_Ramen.addChild(this.dishSpr);
this.Label_Name.text = this.dish.model.name;
for (let i = 0; i < this.dish.model.reward.length; i++){
let ingModel = GetIngredientModelById(this.dish.model.reward[i].ingredientId);
if (ingModel){
let ing = new eui.Image(ingModel.img);
ing.width = ing.height = 50;
this.Group_Ingredient.addChild(ing);
}
}
let sgc = 0;
for (let i = 0; i < this.favourGuy.length; i++){
let port = new RandomBuddyPortSprite(this.favourGuy[i].portrait, 50, 50);
if (port){
this.Group_Buddy.addChild(port);
sgc += 1;
}
if (sgc >= 3) break;
}
this.Rect_ColorSign.fillColor = GetFoodCourtDishTypeColor(this.dish.model.type);
this.SetSelect(false);
this.Button_Eat.addEventListener(egret.TouchEvent.TOUCH_TAP, ()=>{
if (this.clicked == true) return;
this.clicked = true;
if (this.caller && this.eve){
this.eve(this.caller, this.dish);
}
},this);
}
public SetSelect(s:boolean){
this.currentState = s == true ? "selected":"normal";
}
}
|
b6b501de792c2ce89786e3e497a495a46780ecbc
|
TypeScript
|
homebridge/homebridge-examples
|
/static-platform-example-typescript/src/static-platform.ts
| 3.09375
| 3
|
import {AccessoryPlugin, API, HAP, Logging, PlatformConfig, StaticPlatformPlugin,} from "homebridge";
import {ExampleSwitch} from "./switch-accessory";
const PLATFORM_NAME = "ExampleStaticPlatform";
/*
* IMPORTANT NOTICE
*
* One thing you need to take care of is, that you never ever ever import anything directly from the "homebridge" module (or the "hap-nodejs" module).
* The above import block may seem like, that we do exactly that, but actually those imports are only used for types and interfaces
* and will disappear once the code is compiled to Javascript.
* In fact you can check that by running `npm run build` and opening the compiled Javascript file in the `dist` folder.
* You will notice that the file does not contain a `... = require("homebridge");` statement anywhere in the code.
*
* The contents of the above import statement MUST ONLY be used for type annotation or accessing things like CONST ENUMS,
* which is a special case as they get replaced by the actual value and do not remain as a reference in the compiled code.
* Meaning normal enums are bad, const enums can be used.
*
* You MUST NOT import anything else which remains as a reference in the code, as this will result in
* a `... = require("homebridge");` to be compiled into the final Javascript code.
* This typically leads to unexpected behavior at runtime, as in many cases it won't be able to find the module
* or will import another instance of homebridge causing collisions.
*
* To mitigate this the {@link API | Homebridge API} exposes the whole suite of HAP-NodeJS inside the `hap` property
* of the api object, which can be acquired for example in the initializer function. This reference can be stored
* like this for example and used to access all exported variables and classes from HAP-NodeJS.
*/
let hap: HAP;
export = (api: API) => {
hap = api.hap;
api.registerPlatform(PLATFORM_NAME, ExampleStaticPlatform);
};
class ExampleStaticPlatform implements StaticPlatformPlugin {
private readonly log: Logging;
constructor(log: Logging, config: PlatformConfig, api: API) {
this.log = log;
// probably parse config or something here
log.info("Example platform finished initializing!");
}
/*
* This method is called to retrieve all accessories exposed by the platform.
* The Platform can delay the response my invoking the callback at a later time,
* it will delay the bridge startup though, so keep it to a minimum.
* The set of exposed accessories CANNOT change over the lifetime of the plugin!
*/
accessories(callback: (foundAccessories: AccessoryPlugin[]) => void): void {
callback([
new ExampleSwitch(hap, this.log, "Switch 1"),
new ExampleSwitch(hap, this.log, "Switch 2"),
]);
}
}
|
045f6a434a7dd96672b82aed758064602b01a35f
|
TypeScript
|
KohlerAl/EIA2
|
/Endabgabe/Form.ts
| 2.828125
| 3
|
namespace EIA2_Endabgabe {
export enum FORM_MOVE {
ROTATE = "rotate",
MOVE = "move"
}
export abstract class Form {
public color: string;
public size: Vector;
public position: Vector;
public rotation: number;
public moveType: FORM_MOVE;
public active: boolean;
public velocity: Vector = new Vector(5, 5);
public type: string;
public neon: boolean;
public threeD: boolean;
public constructor(_info?: string[]) {
console.log(_info);
if (_info) {
if (_info[0] == "true") {
this.active = true;
console.log("This is true");
}
else
this.active = false;
this.size = new Vector(parseInt(_info[1]), parseInt(_info[2]));
this.position = new Vector(parseInt(_info[3]), parseInt(_info[4]));
console.log(this.position);
this.rotation = parseInt(_info[5]);
if (_info[6] == "move")
this.moveType = FORM_MOVE.MOVE;
else
this.moveType = FORM_MOVE.ROTATE;
this.color = _info[7];
this.velocity = new Vector(parseInt(_info[8]), parseInt(_info[9]));
if (_info[10] == "true") {
this.neon = true;
}
else
this.neon = false;
if (_info[11] == "true") {
this.threeD = true;
}
else
this.threeD = false;
}
else {
this.color = "#ffffff";
this.size = new Vector(40, 40);
this.position = new Vector(50, 50);
this.rotation = 0;
this.active = true;
this.moveType = FORM_MOVE.MOVE;
this.neon = false;
this.threeD = false;
}
}
public draw(): void {
if (this.neon == true) {
crc2.globalCompositeOperation = "lighter";
crc2.shadowColor = this.color;
crc2.lineWidth = 8;
crc2.shadowOffsetX = 2;
crc2.shadowOffsetY = 2;
crc2.shadowBlur = 15;
crc2.strokeStyle = "#ffffff88";
}
else if (this.threeD == true) {
crc2.fillStyle = "414141";
crc2.shadowBlur = 10;
crc2.shadowColor = "cyan";
crc2.shadowOffsetX = -5;
crc2.shadowOffsetY = 0;
crc2.lineWidth = 2;
crc2.strokeStyle = "#ff3a1f80";
crc2.fill();
}
else {
crc2.strokeStyle = this.color;
crc2.fillStyle = this.color;
crc2.lineWidth = 4;
crc2.fill();
}
if (this.active == true) {
crc2.strokeStyle = "red";
crc2.lineWidth = 4;
crc2.stroke();
}
else {
crc2.strokeStyle = this.color;
crc2.stroke();
}
}
public move(_rotateValue: number): void {
switch (this.moveType) {
case FORM_MOVE.MOVE:
let offset: Vector = new Vector(this.velocity.x, this.velocity.y);
offset.scale(1 / 50);
this.position.add(offset);
break;
case FORM_MOVE.ROTATE:
this.rotation += _rotateValue;
break;
default:
break;
}
}
public changeColor(_newColor: string): void {
this.color = _newColor;
}
public changeRotation(_factor: number): void {
this.rotation = _factor;
}
public resize(_factor: number): void {
this.size.scale(_factor);
}
public changePosition(_x: number, _y: number): void {
this.position.x = _x;
this.position.y = _y;
}
}
}
|
ecbfd283a6e64bb3f96a843cf8004e3ac763ba3a
|
TypeScript
|
Maxouize/ControlCare
|
/src/app/core/models/Fichier.ts
| 2.90625
| 3
|
export class Fichier {
idFichier: number;
nomFichier: string;
fichier: Blob;
}
export const createFichier = <T extends Partial<Fichier>>(initialValues: T): Fichier & T => {
return Object.assign(emptyFichier(), initialValues);
};
export const emptyFichier = (): Fichier => ({
idFichier: null,
nomFichier: '',
fichier: null
});
|
9743c51d08b6cf3101fc0fd429731f8914474140
|
TypeScript
|
jamesmanning/emotes
|
/ts/spec/EmoteFlags.spec.ts
| 2.578125
| 3
|
/// <reference path="../typings/mocha/mocha.d.ts" />
/// <reference path="../typings/should/should.d.ts" />
var should = require('should');
import EmoteFlags from '../EmoteFlags';
describe('EmoteFlags', () => {
describe('#getSpeedForDescription', () => {
it('should work for a valid description', () => {
const input = 'fastest';
const expected = '2s';
const actual = EmoteFlags.getSpeedForDescription(input);
should(actual).eql(expected);
});
it('should return input for an invalid description', () => {
const input = '9s';
const expected = '9s';
const actual = EmoteFlags.getSpeedForDescription(input);
should(actual).eql(expected);
});
});
describe('#getDescriptionForSpeed', () => {
it('should work for a speed found in the map', () => {
const input = '2s';
const expected = 'fastest';
const actual = EmoteFlags.getDescriptionForSpeed(input);
should(actual).eql(expected);
});
it('should return input for a speed not found in the map', () => {
const input = '9s';
const expected = '9s';
const actual = EmoteFlags.getDescriptionForSpeed(input);
should(actual).eql(expected);
});
});
});
|
e435dae50ece9371a760fcac1bb5a28cc58fc203
|
TypeScript
|
zcorky/zodash
|
/packages/extend/src/index.ts
| 3.75
| 4
|
/**
* Copy all of the properties in the source objects over to the destination object
*
* @param origin Origin Object
* @param sources Source Objects
* @returns New Object based Origin Object
*
* @example
* extend({ name: 'Any' }, { age: 18 }); // => { name: 'Any', age: 18 }
*/
export function extend<T = any>(
origin: Partial<T>,
...sources: Partial<T>[]
): Partial<T> {
const _origin = { ...origin };
sources.forEach((source) => {
Object.keys(source).forEach((key) => {
_origin[key] = source[key];
});
});
return _origin;
}
export default extend;
|
8e2c626d3455cd179a3dc522e2e00ded110c7ca0
|
TypeScript
|
a572251465/webpack5-vue3-demo
|
/src/assets/js/lodash.ts
| 2.578125
| 3
|
const merge = require('single-merge')
interface ICommon {
name: string
age: number
}
interface ICommon1 {
address: string
}
interface IMerge {
merge: (data: ICommon1, data1: ICommon) => ICommon1 & ICommon
}
const _: IMerge = {
merge
}
export default _
|
53b484f7396c3c502cb492005ad5289187942bbe
|
TypeScript
|
leonardfactory/advent-of-code-2020
|
/src/day-2/part-2.ts
| 3.265625
| 3
|
import fs from 'fs';
let input = fs.readFileSync(__dirname + '/input.txt', 'utf-8');
let test = fs.readFileSync(__dirname + '/input-test.txt', 'utf-8');
function parse(data: string) {
const lines = data.split('\n');
return lines.map(parseRow);
}
const REGEX = /^(\d+)\-(\d+) (\w): (\w+)$/;
function parseRow(row: string) {
const parsed = row.match(REGEX);
if (!parsed) throw new Error(`Row "${row}" is not valid`);
const [_, index1, index2, char, password] = parsed;
return {
index1: parseInt(index1, 10),
index2: parseInt(index2, 10),
char,
password
};
}
type Row = ReturnType<typeof parseRow>;
function check(rows: Row[]) {
console.log(`Rows ex.`, rows[0]);
return rows.filter((row) => isValid(row)).length;
}
function isValid(row: Row) {
const char1 = row.password.charAt(row.index1 - 1) === row.char ? 1 : 0;
const char2 = row.password.charAt(row.index2 - 1) === row.char ? 1 : 0;
// console.log(`Row`, row, ` isValid? ${char1 ^ char2}`);
return char1 ^ char2;
}
console.log(`Checked: ${check(parse(input))}`);
|
a51bd93e83bc803345bea89d2dc542ba57f0a680
|
TypeScript
|
whatasoda/the-pen
|
/src/shared/complete-axis.ts
| 2.625
| 3
|
import { vec3 } from 'gl-matrix';
const INDICES = [0, 1, 2];
const completeAxis = (outX: vec3, outY: vec3, outZ: vec3, inZ: number[]) => {
const absZ = [...inZ].map(Math.abs);
const [i0, i1, i2] = [...INDICES].sort((a, b) => absZ[a] - absZ[b]);
vec3.normalize(outZ, inZ);
const sign = -(Math.sign(outZ[i0]) * Math.sign(outZ[i1])) || 1;
outX[i0] = outZ[i1] * sign;
outX[i1] = outZ[i0] * sign;
outX[i2] = outZ[i2];
vec3.cross(outX, outZ, outX);
vec3.cross(outY, outZ, outX);
vec3.normalize(outX, outX);
vec3.normalize(outY, outY);
};
export default completeAxis;
|
a0074bf01daf2d29271c992ade6568781bf70956
|
TypeScript
|
camifernweh/booksplorer
|
/lib/utils/strings.ts
| 3.03125
| 3
|
import { Country, Book } from '../types';
export const getTitleString = (
title: string | string[] | undefined,
): string => {
let titleString = 'Booksplorer';
if (title) {
titleString += ' | ';
if (Array.isArray(title)) {
titleString += title.join(' | ');
} else {
titleString += title;
}
}
return titleString;
};
export const getBookCoverUrl = (books: Book[]): string => {
let cover = 'fallback';
for (let i = 0; i < books.length; i++) {
if (books[i].cover.includes('gr-assets')) {
cover = books[i].cover;
break;
}
}
return cover;
};
interface Path {
params: {
country: string;
};
}
export const createPathStrings = (countries: Country[]): Path[] => {
// Returns an array that looks like this:
// [
// {
// params: {
// country: 'germany',
// }
// },
// {
// params: {
// country: 'united-kingdom'
// }
// }
// ]
const paths = countries.map((country) => {
return {
params: {
country: country.name.toLowerCase().replace(/\s/g, '-'),
},
};
});
return paths;
};
export const getPathFromName = (name: string): string => {
return name.toLowerCase().replace(/\s/g, '-');
};
export const getNameFromPath = (name: string): string => {
if (name === 'guinea-bissau') return 'Guinea-Bissau';
else if (name === 'timor-leste') return 'Timor-Leste';
else if (name === "côte-d'ivoire") return "Côte d'Ivoire";
let normalizedName: string;
if (!name.includes('-')) {
normalizedName = name.charAt(0).toUpperCase() + name.slice(1);
} else {
normalizedName = name.charAt(0).toUpperCase();
for (let i = 1; i < name.length; i++) {
if (name[i] !== '-' && name[i - 1] !== '-') {
normalizedName += name.charAt(i);
} else if (name[i] === '-') {
normalizedName += ' ' + name.charAt(i + 1).toUpperCase();
}
}
}
if (normalizedName.includes(' Of ')) {
normalizedName = normalizedName.replace(' Of ', ' of ');
} else if (normalizedName.includes(' And ')) {
normalizedName = normalizedName.replace(' And ', ' and ');
}
return normalizedName;
};
|
d09d4d75cfcfba56f472bacd8749ee91f0d4eedc
|
TypeScript
|
Ahmed-Salama/YetAnotherPhysicsEngine
|
/src/game_level_manager.ts
| 2.78125
| 3
|
import GameElement from "./game_element";
import Constants from "./constants";
import GameLevel from "./game_level";
export default class GameLevelManager extends GameElement {
public original_game_level: GameLevel;
public current_game_level: GameLevel;
public finished: boolean;
constructor(initialize: boolean, game_level: GameLevel) {
super(initialize, game_level);
}
protected initialize(game_level: GameLevel) {
this.current_game_level = game_level;
this.original_game_level = game_level;
}
public updated(time_unit: number): GameLevelManager {
if (this.finished) return this;
const updated_game_level = this.current_game_level.updated(time_unit);
if (updated_game_level.won) {
return this.copy({ finished: true, current_game_level: updated_game_level });
}
if (updated_game_level.lost || Constants.key_pressed.get("reset")) {
return this.copy({ current_game_level: this.original_game_level });
}
return this.copy({ current_game_level: updated_game_level });
}
public draw(ctx: CanvasRenderingContext2D) {
this.current_game_level.draw(ctx);
}
}
|
86950f7927da6552e6204fefb36c98095aab78ee
|
TypeScript
|
N0XIRE/xivanalysis
|
/src/parser/core/modules/FFLogsEventNormaliser.ts
| 2.828125
| 3
|
import {Event} from 'fflogs'
import Module from 'parser/core/Module'
const CALCULATED_EVENTS: Array<Event['type']> = [
'calculateddamage',
'calculatedheal',
]
const BASELINE_EVENTS: Array<Event['type']> = [
'damage',
'heal',
]
export class FFLogsEventNormaliser extends Module {
static handle: string = 'fflogsEvents'
private _hasCalculatedEvents: boolean = false
get hasCalculatedEvents() {
return this._hasCalculatedEvents
}
get damageEventName() {
return (this._hasCalculatedEvents ? 'calculateddamage': 'damage')
}
get healEventName() {
return (this._hasCalculatedEvents ? 'calculatedheal': 'heal')
}
normalise(events: Event[]): Event[] {
for (const event of events) {
// Check to see if this is a calculated damage/heal event and set the _hasCalculated events flag if it is
// Once we've seen one, return
if (CALCULATED_EVENTS.includes(event.type)) {
this._hasCalculatedEvents = true
return events
}
// If we see a standard damage/heal event before a calculated event, the log doesn't have any calculated events, return early
if (BASELINE_EVENTS.includes(event.type)) {
return events
}
}
return events
}
}
|
8cc05dc7b41de5dba83ec661147bee3bc781b486
|
TypeScript
|
gaohejin/ynm3000
|
/src/after.ts
| 2.90625
| 3
|
/**
* n次之后都会被执行
* @param n
* @param func
*/
function after(n, func) {
if (typeof func !== 'function') {
throw new TypeError('Excepted function')
}
n = n || 0
return function (...args) {
if (--n < 1) {
return func.apply(this, args)
}
}
}
export default after
|
2f1d2b9e7e353410d42ca98d151fef1faefad748
|
TypeScript
|
GrubbyHunter/LeetCode
|
/Dynamic programming/hard/309.最佳买卖股票时机含冷冻期.ts
| 3.59375
| 4
|
/*
* @lc app=leetcode.cn id=309 lang=typescript
*
* [309] 最佳买卖股票时机含冷冻期
*/
// @lc code=start
function maxProfit(prices: number[]): number {
// 当天的状态,持有、不持有、冻结
let dp = new Array(prices.length).fill(0).map(() => new Array(3).fill(0))
dp[0][0] = -prices[0] // 第一天持有,挣的钱为-prices[0]
dp[0][1] = 0 // 第一天不持有,挣的钱为0
dp[0][2] = 0 // 第一天冻结,挣的钱为0
for (let i = 1; i < prices.length; i++) {
// 第i天持有股票有2种情况
// a.第i-1天也持有股票,第i天不操作,
// b.第i-1天不持有股票,在第i天买入
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i])
// 第i天不持有股票的情况有3种
// a.第i-1天也不持有股票
// b.第i-1天是过渡期
// c.第i-1天卖出
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][2], dp[i][0] - prices[i])
//第i天是冷冻期只有一种情况,第i-1天持有股票且卖出
dp[i][2] = dp[i - 1][0] + prices[i];
}
let last = dp[dp.length - 1]
// 去最后一天,不持有股票和冻结期的情况,取最大值,因为持有股票的情况挣的钱肯定小于这两种
return Math.max(last[1], last[2])
};
// @lc code=end
|