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
|
|---|---|---|---|---|---|---|
ed23f551fb865198fea3b7e69952297a2f256a4d
|
TypeScript
|
beingOptimusP/stv
|
/src/examples/stv.counting.example.ts
| 2.875
| 3
|
/* istanbul ignore file */
import { Vote } from "../model";
import { repeat } from "../utils";
export const andreaSymbol = "Andrea";
export const bradSymbol = "Brad";
export const carterSymbol = "Carter";
export const delilahSymbol = "Delilah";
//As taken from https://en.wikipedia.org/wiki/Counting_single_transferable_votes
export function getExampleElectionData(): { candidates: string[], votes: Vote[], seatsToFill: number } {
const candidates = [andreaSymbol, bradSymbol, carterSymbol, delilahSymbol];
const votes: Vote[] = [];
repeat(16, () => {
votes.push({
weight: 1,
preferences: [andreaSymbol, bradSymbol, carterSymbol, delilahSymbol]
});
});
repeat(24, () => {
votes.push({
weight: 1,
preferences: [andreaSymbol, carterSymbol, bradSymbol, delilahSymbol]
});
});
repeat(17, () => {
votes.push({
weight: 1,
preferences: [delilahSymbol, andreaSymbol, bradSymbol, carterSymbol]
});
});
return {
candidates: candidates,
votes: votes,
seatsToFill: 2
}
}
|
e2e84b13a944ce0484d809b1149cb844cffc95e6
|
TypeScript
|
jpaul34/Test-Phaser3-Typescript-Ionic5
|
/ionic-frontend/src/game/componets/scoreTable/score-table.ts
| 2.546875
| 3
|
import {GameTitles} from '../../consts/gameTitles/game-titles'
import { bindCallback } from 'rxjs';
interface scoreInterface {
id: number,
name: string,
dependenci: string,
acronym: string,
score: string
}
export class ScoreTable {
//scoreTable: Phaser.GameObjects.Grid;
scoreTable: Phaser.GameObjects.GameObject;
scoreText: Phaser.GameObjects.Text;
scoreBody: Phaser.GameObjects.Container;
constructor(scene: Phaser.Scene, scores: scoreInterface[] , titleId: number,
xPosition: number, yPosition: number,
width: number, height: number){
let titleContent = GameTitles.find((title)=>{
return title.id === titleId;
});
let scoreContent: string = titleContent.name+"\n";
scores.forEach(score => {
let salida: string ='';
if(titleContent.id == 4 || titleContent.id == 5){
salida = '\n'+score.name + ' ('+
score.acronym +') '+
score.score;
}else{
salida = '\n\n'+score.name + ' ('+
score.acronym +') '+
score.score;
}
scoreContent = scoreContent.concat(salida);
});
this.scoreText = scene.add.text(0, 0, scoreContent,
{
fontFamily:'Arial',
fontSize:20,
color:'#ffffff',
align:'center'
}
);
this.scoreText.setOrigin (0.5);
this.scoreTable = scene.add.rectangle(0,0, this.scoreText.width+15, this.scoreText.height+15, 0xfff55, 1);
/*
graphics.lineStyle(5, 0xFF00FF, 1.0);
graphics.fillStyle(0xFFFFFF, 1.0);
graphics.fillRect(50, 50, 400, 200);
graphics.strokeRect(50, 50, 400, 200);*/
//this.scoreTable = scene.add.grid(0,0, width, height, 1, 1, 0x000000);
//console.log(this.scoreTable.strokeColor);
//this.scoreTable.setFillStyle(0x000000, 1.0);;
//console.log(this.scoreTable.strokeColor);
//this.scoreTable.setOrigin (0.5)
//this.scoreBackground.setScale(0.2);
//this.scoreText = scene.add.text(0, 0, buttonDefinition.text.content, scoreDefinition.text.style);
//this.scoreText.setOrigin (0.5)
//let scoreText = new Title(scene, 2, xPosition, yPosition);
this.scoreBody = scene.add.container(xPosition,yPosition,[this.scoreTable, this.scoreText]);
this.scoreBody.setSize(this.scoreText.width,this.scoreText.height);
this.scoreBody.setInteractive();
}
}
|
05e6f864727db1c9fa4e4bfa4631259fda7fb5ef
|
TypeScript
|
audipasuatmadi/startup-backend
|
/src/services/user/validator.ts
| 2.734375
| 3
|
import { RegisterRequestBody } from './usertypes';
import Joi, { ValidationError } from 'joi';
const baseValidationMessage = {
'string.lowercase': '{{#label}} tidak boleh mengandung huruf besar',
'string.trim': '{{#label}} tidak boleh mengandung spasi',
'string.empty': '{{#label}} harus diisi',
};
const userRegisterBodySchema = Joi.object({
name: Joi.string().trim().required().label('nama').messages(baseValidationMessage),
username: Joi.string()
.trim()
.lowercase()
.required()
.pattern(new RegExp('^\\S*$'))
.messages({
'string.pattern.base': '{{#label}} tidak boleh mengandung spasi',
...baseValidationMessage,
}),
password: Joi.string().required().messages(baseValidationMessage),
});
export const validateUserRegisterBody = async (
userRegisterBody: RegisterRequestBody
) => {
try {
const validateResult = await userRegisterBodySchema.validateAsync(
userRegisterBody,
{ abortEarly: false, convert: false }
);
const validateDecision = validateResult as RegisterRequestBody;
return validateDecision;
} catch (e) {
const validateDecision = e as ValidationError;
return validateDecision;
}
};
|
9cbfb3a265a34b1138135e034beb042044a107f3
|
TypeScript
|
parklover/skryba
|
/web/essentialjs/JavaScript - EJ2/17.3.0.26/Web (Essential JS 2)/JavaScript/ej2-diagrams/src/diagram/interaction/spatial-search/quad.d.ts
| 2.53125
| 3
|
import { IGroupable, SpatialSearch } from './spatial-search';
import { Rect } from '../../primitives/rect';
/**
* Quad helps to maintain a set of objects that are contained within the particular region
*/
/** @private */
export declare class Quad {
/** @private */
objects: IGroupable[];
/** @private */
left: number;
/** @private */
top: number;
/** @private */
width: number;
/** @private */
height: number;
/** @private */
first: Quad;
/** @private */
second: Quad;
/** @private */
third: Quad;
/** @private */
fourth: Quad;
/** @private */
parent: Quad;
private spatialSearch;
/** @private */
constructor(left: number, top: number, width: number, height: number, spatialSearching: SpatialSearch);
/** @private */
findQuads(currentViewPort: Rect, quads: Quad[]): void;
private isIntersect;
/** @private */
selectQuad(): Quad;
private getQuad;
/** @private */
isContained(): boolean;
/** @private */
addIntoAQuad(node: IGroupable): Quad;
private add;
}
/** @private */
export interface QuadSet {
target?: Quad;
source?: Quad;
}
/** @private */
export interface QuadAddition {
quad?: Quad;
isAdded?: boolean;
}
|
14f3e551aa11bf71b81e64234ae81229bc60a913
|
TypeScript
|
tajpouria/cors
|
/examples/attain/configuring-cors-asynchronously.ts
| 2.8125
| 3
|
import { App, Request } from "https://deno.land/x/attain/mod.ts";
import { attainCors, CorsOptionsDelegate } from "../../mod.ts";
const sleep = (ms: number) =>
new Promise((resolve) => {
setTimeout(resolve, ms);
});
const books = new Map<string, any>();
books.set("1", {
id: "1",
title: "Frankenstein",
author: "Mary Shelley",
});
const whitelist = ["http://localhost:1234", "http://localhost:3000"];
const corsOptionsDelegate: CorsOptionsDelegate<Request> = async (request) => {
const isOriginAllowed = whitelist.includes(
request.headers.get("origin") ?? "",
);
await sleep(100); // Simulate asynchronous task
return { origin: isOriginAllowed }; // Reflect (enable) the requested origin in the CORS response if isOriginAllowed is true
};
const app = new App();
app.get("/book", attainCors(corsOptionsDelegate), (req, res) => {
res.status(200).send(Array.from(books.values()));
});
console.info("CORS-enabled web server listening on port 8000");
await app.listen({ port: 8000 });
|
820c63312d08200252edb1274c82fc39a4c5ac5a
|
TypeScript
|
TanyaMykhnevych/GreedyOptimization
|
/src/app/components/table/table.component.ts
| 2.5625
| 3
|
import { Component, Input } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
@Component({
selector: 'app-table',
templateUrl: './table.component.html',
styleUrls: ['./table.component.scss']
})
export class TableComponent {
public displayedColumns: string[] = [' '];
public dataSource = new MatTableDataSource([]);
@Input() public set data(data: number[][]) {
this.dataSource = new MatTableDataSource(data);
this.displayedColumns = [' '];
Array.from(Array(data[0].length).keys()).map(d => { if (d) { this.displayedColumns.push(d.toString()); } });
}
public editor = {
// use to change the switch to input
editPointer: {
col: -1,
row: -1,
},
};
public deleteColumn(): void {
if (this.displayedColumns.length === 1) {
console.log('Cannot delete all headers.');
return;
}
this.displayedColumns.splice(-1, 1);
const tempDataSource = [...this.dataSource.data];
for (let i = 0; i < tempDataSource.length - 1; i++) {
tempDataSource[i].splice(-1, 1);
}
this.dataSource.data = tempDataSource;
}
public addColumn(): void {
this.displayedColumns.push((+this.displayedColumns[this.displayedColumns.length - 1] + 1).toString());
const tempDataSource = [...this.dataSource.data];
for (let i = 0; i < tempDataSource.length; i++) {
tempDataSource[i].push(0);
}
this.dataSource.data = tempDataSource;
}
public deleteRow(): void {
if (this.dataSource.data.length === 1) {
console.log('Cannot delete all rows.');
return;
}
const tempDataSource = [...this.dataSource.data];
tempDataSource.splice(-1, 1);
this.dataSource.data = tempDataSource;
}
public addRow(): void {
const tempDataSource = [...this.dataSource.data];
tempDataSource[tempDataSource.length] = [].concat(... new Array(this.displayedColumns.length - 1).fill([0]));
this.dataSource.data = tempDataSource;
}
public switchToInput(rindex: number, cindex: number): void {
this.editor.editPointer.col = cindex;
this.editor.editPointer.row = rindex;
}
}
|
36adf968b87d62d7743209677a5ebcdaa448a54d
|
TypeScript
|
hanokhaloni/zoombiesZoo
|
/src/app/game/board/tile/tile-buy-popup/buy-item/buy-item.ts
| 2.734375
| 3
|
export interface ICost {
lumber?: number;
block?: number;
coin?: number;
wheat?: number;
}
export interface IBuyItem {
cost: ICost;
icon: string;
type: number;
}
export class BuyItem {
woodCost: number;
coinCost: number;
stoneCost: number;
constructor() {
}
}
|
0a060bb3db6bf595af3d687f87edc1f25a4c9bc0
|
TypeScript
|
kurehajime/colamone_js
|
/src/static/canvas/BackgroundDraw.ts
| 3.125
| 3
|
import Params from "../Params"
export class BackgroundDraw {
/**
* 盤面を描画してDataURLを返す。
*/
static drawBoard(): string {
const canvas: HTMLCanvasElement = document.createElement("canvas")
const canvSize = Params.CANV_SIZE * 3
const cellSize = canvSize / 6
canvas.width = canvSize
canvas.height = canvSize
const ctx_board = canvas.getContext("2d")
if (ctx_board) {
ctx_board.clearRect(0, 0, canvSize, canvSize)
const grad = ctx_board.createLinearGradient(0, 0, canvSize, canvSize)
grad.addColorStop(0, Params.COLOR_PANEL_6)
grad.addColorStop(0.3, Params.COLOR_PANEL_5)
grad.addColorStop(1, Params.COLOR_PANEL_4)
for (let x = 0; x < 6; x++) {
for (let y = 0; y < 6; y++) {
// パネル描画
ctx_board.strokeStyle = Params.COLOR_LINE
if (y === 0) {
ctx_board.fillStyle = Params.COLOR_PANEL_1
} else if (y === 5) {
ctx_board.fillStyle = Params.COLOR_PANEL_2
} else if ((x + y) % 2 === 0) {
ctx_board.fillStyle = Params.COLOR_PANEL_3
} else {
ctx_board.fillStyle = Params.COLOR_PANEL_4
ctx_board.fillStyle = grad
}
ctx_board.beginPath()
ctx_board.fillRect(x * cellSize, y * cellSize, cellSize, cellSize)
ctx_board.strokeRect(x * cellSize, y * cellSize, cellSize, cellSize)
}
}
}
return canvas.toDataURL()
}
static drawBoard2() {
const canvas: HTMLCanvasElement = document.createElement("canvas")
const canvSize = Params.CANV_SIZE * 3
const cellSize = canvSize / 6
const ctx_board2 = canvas.getContext("2d")
if (ctx_board2) {
ctx_board2.clearRect(0, 0, canvSize, canvSize)
ctx_board2.globalAlpha = 0.07
ctx_board2.fillStyle = Params.COLOR_WHITE
ctx_board2.beginPath()
ctx_board2.arc(
cellSize * 1,
-3 * cellSize,
7 * cellSize,
0,
Math.PI * 2,
false
)
ctx_board2.fill()
}
return canvas.toDataURL()
}
}
|
0ee84820e6877debbf782bec1ceb67c3d99be615
|
TypeScript
|
WooodHead/codeglide
|
/packages/domain/src/searchRepository/mutations.ts
| 2.59375
| 3
|
import { State, SearchRepositoryResult } from "./state";
export const makeBusy = (state: State): State => {
return {
...state,
fetching: true
};
};
export const setResult = (
state: State,
result: SearchRepositoryResult
): State => {
return {
...state,
fetching: false,
totalCount: result.total_count,
loadedCount: result.items.length,
incomplete: result.incomplete_results,
repositories: result.items
};
};
export const appendResult = (
state: State,
result: SearchRepositoryResult
): State => {
return {
...state,
fetching: false,
totalCount: result.total_count,
loadedCount: state.loadedCount + result.items.length,
incomplete: result.incomplete_results,
repositories: state.repositories.concat(result.items)
};
};
|
54084e890aa2391b55d98e8cb824302a4176e340
|
TypeScript
|
Red2Blaze/azure-serverless-discord-bot
|
/HttpTrigger1/commands/button.ts
| 2.625
| 3
|
import {
SlashCommand,
ComponentType,
ButtonStyle,
SlashCreator,
CommandContext,
ComponentContext,
} from "slash-create";
import { env } from "process";
export class ButtonCommand extends SlashCommand {
constructor(creator: SlashCreator) {
let cDesc = {
name: "button",
description: "Show some buttons.",
guildIDs: ["867048548838539326"],
};
if (env.COMMANDS_GUILD_ID)
cDesc = Object.assign(cDesc, { guildIDs: [env.COMMANDS_GUILD_ID] });
super(creator, cDesc);
// Not required initially, but required for reloading with a fresh file.
this.filePath = __filename;
}
async run(ctx: CommandContext): Promise<void> {
// There is a 3 seconds windows to answer to an interactions.
// Deferring the response sends an acknowledge, informing Discord that we are going
// to answer
await ctx.defer();
await ctx.send("here is some buttons", {
components: [
{
type: ComponentType.ACTION_ROW,
components: [
{
type: ComponentType.BUTTON,
style: ButtonStyle.PRIMARY,
label: "button",
custom_id: "example_button",
emoji: {
name: "👌",
},
},
],
},
],
});
/**
* This function handles component contexts within a command, so you
* can use the previous context aswell.
*/
ctx.registerComponent(
"example_button",
async (btnCtx: ComponentContext) => {
await btnCtx.editParent("You clicked the button!");
}
);
}
}
|
0b5051754a09de942399536a7f189f26ed7895bb
|
TypeScript
|
Starholme/GeneratorGame
|
/BoS/src/engine/Network.ts
| 3.15625
| 3
|
import { Box, Levels, Resource } from './interfaces'
interface Lvl {
current: number;
max: number;
diff: number;
mult: number;
}
export class Network {
public id: number;
private name: string;
private resource: Resource;
private boxes: Array<Box>;
constructor(id: number, name: string, resource: Resource) {
this.id = id;
this.name = name
this.resource = resource;
this.boxes = new Array<Box>();
}
public GetDescription() {
return this.name + ': ' + this.resource.name;
}
public AddBox(box: Box) {
this.boxes.push(box);
this.Sort();
}
public RemoveBox(box: Box): boolean {
const index = this.boxes.indexOf(box);
if (index > -1) {
this.boxes.splice(index, 1);
return true;
}
return false;
}
public Update() {
const levels = new Array<Lvl>();
levels[Levels.Low] =
{
current: 0,
max: 0,
diff: 0,
mult: 0
};
levels[Levels.Storage] =
{
current: 0,
max: 0,
diff: 0,
mult: 0
};
levels[Levels.High] =
{
current: 0,
max: 0,
diff: 0,
mult: 0
};
//Get current and used for each level
this.boxes.forEach(function (box) {
levels[box.level].current += box.current;
levels[box.level].max += box.max;
});
//Starting from lowest level, attempt to fill from higher levels
levels.forEach((toLevel: Lvl, toIdx: number) => {
levels.forEach((fromLevel: Lvl, fromIdx: number) => {
if (toIdx < fromIdx) {
this.PullFromTo(fromLevel, toLevel);
}
});
toLevel.mult = toLevel.max / toLevel.current;
});
//Spread the current amount for each level across boxes of that level
let extra = 0;
this.boxes.forEach((box) => {
const mult = levels[box.level].mult;
extra = this.FillInt(box, extra, mult);
});
}
private PullFromTo(from: Lvl, to: Lvl) {
to.diff = to.max - to.current;
if (to.diff > 0) {
//If enough in from, fill to
if (from.current >= to.diff) {
to.current += to.diff;
from.current -= to.diff;
}
//Otherwise, take what is available
else {
to.current += from.current;
from.current = 0;
}
}
}
private FillInt(box: Box, extra: number, mult: number): number {
let current = mult * box.max;
extra += current % 1;
current = Math.floor(current);
if (Math.round(extra) === 1) {
extra--;
current++;
}
box.current = current;
return extra;
}
private Sort() {
this.boxes.sort(function (a: Box, b: Box): number {
return a.level - b.level;
})
}
}
|
dc4071ad9265d97e116992ee835663ce5a805171
|
TypeScript
|
BlackspaceInc/typescript-microservices-template
|
/libs/kernel/test/domain/aggregate-root.spec.ts
| 3.109375
| 3
|
import { UniqueEntityId } from '../../src/domain/unique-entity-id';
import { Address, Contact } from './models';
describe('AggregateRoot', () => {
let address: Address;
let contact: Contact;
beforeEach(() => {
address = Address.create({
address: 'Av. Lima 123',
city: 'Lima',
latitude: '1.111',
longitude: '2.222',
});
contact = Contact.create({
firstName: 'Luis',
lastName: 'Diego',
age: 30,
address,
status: true,
});
});
it('should create an instance', () => {
expect(contact).toBeTruthy();
});
it('should if the entity is valid', () => {
const id: UniqueEntityId = new UniqueEntityId();
const newContact = Contact.create(
{
firstName: 'Luis',
lastName: 'Diego',
age: 30,
address,
status: true,
},
id
);
const otherContact = Contact.create(
{
firstName: 'Luis',
lastName: 'Diego',
age: 30,
address,
status: true,
},
id
);
expect(newContact.equals(otherContact)).toBeTruthy();
});
it('should compare aggregate root with nullable or undefined', () => {
expect(contact.equals()).toBeFalsy();
expect(contact.equals(undefined)).toBeFalsy();
});
it('should compare the aggregate root with itself', () => {
expect(contact.equals(contact)).toBeTruthy();
});
it('should validate entity fields', () => {
const id = new UniqueEntityId();
const firstName = 'Luis';
const lastName = 'Diego';
const age = 30;
const status = true;
const contact = Contact.create(
{
firstName,
lastName,
age,
address,
status,
},
id
);
expect(contact.id.equals(id)).toBeTruthy();
expect(contact.firstName).toEqual(firstName);
expect(contact.lastName).toEqual(lastName);
expect(contact.age).toEqual(age);
expect(contact.birthday).toEqual(0);
expect(contact.status).toEqual(status);
expect(contact.address?.id).toEqual(address.id);
expect(contact.address?.address).toEqual(address.address);
expect(contact.address?.city).toEqual(address.city);
expect(contact.address?.latitude).toEqual(address.latitude);
expect(contact.address?.longitude).toEqual(address.longitude);
});
it('should validate change status', () => {
const status = true;
const contact = Contact.create({
firstName: 'Luis',
lastName: 'Diego',
age: 30,
address,
status,
});
contact.status = false;
expect(contact.status).not.toEqual(status);
});
it('should validate change birthday', () => {
const birthday = 123;
const contact = Contact.create({
firstName: 'Luis',
lastName: 'Diego',
age: 30,
address,
status: true,
});
contact.birthday = birthday;
expect(contact.birthday).not.toEqual(0);
});
it('should firstName is undefined', () => {
expect(() =>
Contact.create({
lastName: 'Diego',
age: 30,
address,
status: true,
})
).toThrowError(new Error('The firstName is undefined'));
});
it('should firstName is nullable', () => {
const contact = Contact.create({
firstName: null,
lastName: 'Diego',
age: 30,
address,
status: true,
});
expect(contact.firstName).toEqual('');
});
it('should lastName is nullable', () => {
const contact = Contact.create({
firstName: 'Luis',
lastName: null,
age: 30,
address,
status: true,
});
expect(contact.lastName).toEqual('');
});
it('should address is nullable', () => {
expect(() =>
Contact.create({
firstName: 'Luis',
lastName: 'Diego',
age: 30,
address: null,
status: true,
})
).toThrowError(/The address is null or undefined/);
});
});
|
403467c4c5e7f6b9cdac5ae5eae698ffca4e53ce
|
TypeScript
|
AMfalme/mars-rover-photos
|
/src/data/mars-photos.ts
| 2.75
| 3
|
import axios from 'axios'
import { fireStore } from '../firebaseConfig';
export type Photo = {
id: number
sol: number
camera : {
id: number
name: string
rover_id: number
full_name: string
}
img_src: string
earth_date: string
rover: {
id: number
name: string
landing_date: string
launch_date: string
status: string
}
}
// import Constants from '../constants'
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const nasa_mars_rover_api : string = "https://api.nasa.gov/mars-photos/api/v1"
const heroku_nasa_mars_rover_api = "https://mars-photos.herokuapp.com/api/v1/rovers/curiosity/photos"
export const dateToShortFormat = function (date: Date) {
console.log(date);
let day = date.getDate();
let monthIndex = date.getMonth();
let year = date.getFullYear();
const selectedDate = `${year}-${monthIndex}-${day}`
console.log(selectedDate)
return selectedDate
};
// This section returns a promise which does not seem to be returning expected values
export function getPhotosFromNasaApi(dateChosen: String) {
return axios({
method: 'get',
url: heroku_nasa_mars_rover_api,
responseType: 'json',
params: {
earth_date: dateChosen
},
headers: {
'x-auth-token': 'DEMO_KEY',
"content-type": "application/json",
"Access-Control-Allow-Origin": "*"
}
})
}
export function getSavedPhotos() {
return fireStore.collection("Photos").get();
}
// export const getPhoto = getPhotosFromNasaApi(id: number) => getPhotos.find(p => p.id === id)
// We try to use a different approach where minimalistic approach
|
fa5a7caa7858c705186eb14e9598350d89b401d2
|
TypeScript
|
davidohlin/vite-aliases
|
/src/generator.ts
| 2.65625
| 3
|
import type { Alias, Options, Path } from './types';
import { slash, split, terminal, toArray, toCamelCase, toRelative } from './utils';
import chokidar from 'chokidar';
import { config } from './constants';
import { getDirectories } from './fs/glob';
import { resolve } from 'path';
import { writeConfig } from './fs/config';
import { writeLog } from './fs/log';
/**
* Reads the Projectpath and returns Vite Aliases
* @param options
* @returns Record<string, string>
*/
export class Generator {
readonly options: Options;
readonly fullPath: string;
public aliases: Alias[] = [];
public directories = new Set<string>();
public paths: Path = {};
constructor(public readonly servermode: String, options?: Partial<Options>) {
this.options = Object.assign({}, config, options);
const {
dir,
depth,
root,
}: Options = this.options;
this.fullPath = slash(resolve(root, dir)); // needed for absolute paths in watcher
// only watch on dev not on build
if (servermode === 'serve') {
// watch for directory changes
const watcher = chokidar.watch(this.fullPath, { ignoreInitial: true, depth: depth });
watcher.on('addDir', (path) => {
this.addAlias(path);
})
.on('unlinkDir', (path) => {
this.removeAlias(path);
});
}
}
/**
* Add Alias
* @param path
*/
addAlias(path: string | string[]) {
toArray(path).forEach((p) => {
p = slash(p);
// turn path into array and get last folder
const folders = split(p.replace(this.fullPath, this.options.dir), '/').filter(Boolean);
const lastDir = folders.slice(-1)[0];
let key = `${this.options.prefix}${lastDir}`;
const uniques = [...new Set(folders)];
if(folders.length !== uniques.length) {
const duplicates = [...folders].sort().filter((f, i, self) => {
if(self[i + 1] === self[i]) {
return f;
}
});
terminal(`Path: '${p}' contains multiple folders with same name: ${duplicates.toString()}`, 'warning');
}
if(this.aliases.some(a => a.find === key)) {
terminal('There are duplicate Aliases generated, either fix the folderstructure or enable adjustDuplicates', 'warning');
if(this.options.adjustDuplicates && this.options.depth > 1) {
const name = folders.filter(f => !split(slash(this.options.dir), '/').includes(f)).join('-');
key = `${this.options.prefix}${toCamelCase(name)}`;
}
}
if (lastDir === this.options.dir && this.options.allowGlobalAlias) {
key = `${this.options.prefix}`;
}
this.directories.add(p);
this.aliases.push({
find: `${key}`,
replacement: `${p}`
});
this.handleConfigPath(p, `${key}/*`);
});
}
/**
* Remove Alias
* @param path
*/
removeAlias(path: string | string[]) {
toArray(path).forEach((p) => {
p = slash(p);
if(this.directories.has(p)) {
this.directories.delete(p);
this.aliases = this.aliases.filter((a) => a.replacement != p);
this.handleConfigPath(p);
}
});
}
/**
*
* @param path
* @param key
*/
handleConfigPath(path: string, key ?:string) {
const p = this.options.useRelativePaths ? toRelative(path, this.options.dir) : slash(`${path}/*`);
if(key) {
this.paths[key] = [p];
} else {
this.paths = Object.fromEntries(Object.entries(this.paths).filter((cp) => cp[1][0] === p));
}
}
/**
* Glob Directories
* writes Logfile
* writes IDE Config
*/
private searched: boolean = false;
glob() {
if(this.searched) {
return;
}
getDirectories(this);
if (this.options.allowGlobalAlias) {
this.addAlias(this.fullPath);
}
if (this.options.allowLogging) {
writeLog(this);
}
if (this.options.useConfig) {
writeConfig(this);
}
this.searched = true;
}
}
|
0a5ce5ab6691d3d4b9568892fbd3d599a13d63b7
|
TypeScript
|
camronkhan/mancalaNg
|
/src/app/gameboard/gameboard.component.ts
| 2.609375
| 3
|
import { Component, OnInit, OnDestroy, Inject } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { GameStartService } from '../services/game-start.service';
import { GameRestartService } from '../services/game-restart.service';
import { GameOverService } from '../services/game-over.service';
import { HistoryService } from '../services/history.service';
import { Player } from '../models/player';
@Component({
selector: 'app-gameboard',
templateUrl: './gameboard.component.html',
styleUrls: ['./gameboard.component.css']
})
export class GameboardComponent implements OnInit, OnDestroy {
private _gameboardVisible: boolean;
private _subscription: Subscription;
private _gameboard: Array<number>;
constructor(
private _gameStartService: GameStartService,
private _gameRestartService: GameRestartService,
private _gameOverService: GameOverService,
private _historyService: HistoryService,
@Inject('PlayerA') private _playerA: Player,
@Inject('PlayerB') private _playerB: Player
) {
this._gameStartService.gameStartAnnounced$.subscribe(p => { this._gameboardVisible = true; });
this._gameRestartService.gameRestartAnnounced$.subscribe(p => { this.restartGame(); });
}
/*
* Set starting values when gameboard component is initialized
* Requirement:
*/
ngOnInit() {
this._gameboardVisible = false;
this._playerA.turn = true;
this._gameboard = [4, 4, 4, 4, 4, 4, 0, 4, 4, 4, 4, 4, 4, 0];
this._historyService.history.push('Let\'s play Mancala!');
}
/*
* Unsubscribe from subscriptions when component is destroyed
* Requirement:
*/
ngOnDestroy() {
this._subscription.unsubscribe();
}
/*
* Resets gameboard, player attributes, and game history on restart
* Requirement:
*/
restartGame() {
this._playerA.resetScore();
this._playerB.resetScore();
this._playerA.turn = true;
this._playerB.turn = false;
this._gameboard = [4, 4, 4, 4, 4, 4, 0, 4, 4, 4, 4, 4, 4, 0];
while (this._historyService.history.length > 0) {
this._historyService.history.pop();
}
this._historyService.history.push('Let\'s play Mancala!');
this._gameboardVisible = true;
}
/*
* Hide gameboard and emit game over observable when game ends
* Requirement:
*/
endGame() {
this._gameboardVisible = false;
this._gameOverService.confirmGameOver();
}
/*
* When a user clicks a pocket remove stones and distribute them among the gameboard
* Requirement:
*/
pocketClicked(pocket: number) {
// if player clicks on opponent's or empty pocket, do nothing
let isOwnPocket: boolean = this.checkIfOwnPocket(pocket);
if (!isOwnPocket || this._gameboard[pocket] === 0) { return; }
// pick up stones
let currentPlayerName = this.getCurrentPlayerName();
let stones: number = this.removeStonesFromPocket(pocket);
this._historyService
.add(`${currentPlayerName} picked up ${stones} stones from pocket ${this.getPositionName(pocket)}.`);
// distribute stones and determine ending position
let endPosition: number = this.distributeStones(pocket, stones);
// if Player A's pockets are all empty, added stones in Player B's pockets to Player B's score
// then game over
if (this._gameboard[0] === 0 &&
this._gameboard[1] === 0 &&
this._gameboard[2] === 0 &&
this._gameboard[3] === 0 &&
this._gameboard[4] === 0 &&
this._gameboard[5] === 0
) {
this._gameboard[13] += this._gameboard[7];
this._gameboard[13] += this._gameboard[8];
this._gameboard[13] += this._gameboard[9];
this._gameboard[13] += this._gameboard[10];
this._gameboard[13] += this._gameboard[11];
this._gameboard[13] += this._gameboard[12];
this.updateScores();
this.endGame();
}
// if Player B's pockets are all empty, added stones in Player A's pockets to Player A's score
// then game over
if (this._gameboard[7] === 0 &&
this._gameboard[8] === 0 &&
this._gameboard[9] === 0 &&
this._gameboard[10] === 0 &&
this._gameboard[11] === 0 &&
this._gameboard[12] === 0
) {
this._gameboard[6] += this._gameboard[0];
this._gameboard[6] += this._gameboard[1];
this._gameboard[6] += this._gameboard[2];
this._gameboard[6] += this._gameboard[3];
this._gameboard[6] += this._gameboard[4];
this._gameboard[6] += this._gameboard[5];
this.updateScores();
this.endGame();
}
// update players' scores
this.updateScores();
// if player lands in own mancala, it remains same player's turn
let currentPlayer: number = this.getCurrentPlayer();
let currentMancala = this.getCurrentMancala(currentPlayer);
if (endPosition === currentMancala) {
this._historyService
.add(`${currentPlayerName} landed on ${this.getPositionName(endPosition)}. Take another turn!`);
return;
}
// change current player
let opponent: string = this.getOpposingPlayerName();
this._historyService
.add(`${currentPlayerName} landed on ${this.getPositionName(endPosition)}. ${opponent}, it's your turn!`);
let nextPlayer = this.changeCurrentPlayer(currentPlayer);
}
/*
* Checks if pocket clicked belongs to current player
* Requirement:
*/
checkIfOwnPocket(pocket: number): boolean {
let currentPlayer: number = this.getCurrentPlayer();
let playerPocket: number = Math.floor(pocket / 7);
if (playerPocket === currentPlayer) { return true; }
return false;
}
/*
* Retrieves the current player
* Requirement:
*/
getCurrentPlayer(): number {
if (this._playerA.turn && !this._playerB.turn) {
return 0;
} else if (this._playerB.turn && !this._playerA.turn) {
return 1;
} else {
throw new Error('Player turns unsynchronized')
}
}
/*
* Retrieves the current player's name
* Requirement:
*/
getCurrentPlayerName(): string {
if (this._playerA.turn && !this._playerB.turn) {
return this._playerA.name;
} else if (this._playerB.turn && !this._playerA.turn) {
return this._playerB.name;
} else {
throw new Error('Player turns unsynchronized')
}
}
/*
* Retrieves the opposing player
* Requirement:
*/
getOpposingPlayer(currentPlayer: number): number {
switch (currentPlayer) {
case 0:
return 1;
case 1:
return 0;
default:
throw new Error('Current player is not set to 0 or 1');
}
}
/*
* Retrieves the opposing player's name
* Requirement:
*/
getOpposingPlayerName(): string {
if (this._playerA.turn && !this._playerB.turn) {
return this._playerB.name;
} else if (this._playerB.turn && !this._playerA.turn) {
return this._playerA.name;
} else {
throw new Error('Player turns unsynchronized')
}
}
/*
* Retrieves number of stones from the clicked pocket and sets the pocket's stone number to zero
* Requirement:
*/
removeStonesFromPocket(pocket: number): number {
let stones: number = this._gameboard[pocket];
this._gameboard[pocket] = 0;
return stones;
}
/*
* Distribute the retrieved stones among the pockets in counter clockwise order, skipping the opponent's mancala
* Return the pocket location where the player lands
* Requirement:
*/
distributeStones(pocket: number, stones: number): number {
let currentPosition: number = pocket;
let remainingStones: number = stones;
let currentPlayer: number = this.getCurrentPlayer();
let currentPlayerName: string = this.getCurrentPlayerName();
let currentMancala: number = this.getCurrentMancala(currentPlayer);
let opponentMancala: number = this.getOpponentMancala(currentPlayer);
// loop while stones remain
while (remainingStones > 0) {
// move to next position
currentPosition++;
// if end of array reached, move to beginning
if (currentPosition > 13) { currentPosition = 0; }
// only increment stone count if current position is not opponent's mancala
if (currentPosition !== opponentMancala) {
this._gameboard[currentPosition]++;
remainingStones--;
// announce point scored
if (this._gameboard[currentPosition] === 6 || this._gameboard[currentPosition] === 13) {
this._historyService.add(`${currentPlayerName} scored a point!`);
}
}
}
// if last stone placed in own empty pocket, get contents of own pocket and of opponent's cross-pocket
let isOwnPocket = this.checkIfOwnPocket(currentPosition);
let isMancala = this.checkIfMancala(currentPosition);
if (isOwnPocket && !isMancala && this._gameboard[currentPosition] === 1) {
// own current pocket
this._gameboard[currentMancala]++;
this._gameboard[currentPosition]--;
// opponent's cross pocket
let crossPocket: number = this.getCrossPocket(currentPosition);
this._gameboard[currentMancala] += this._gameboard[crossPocket];
this._gameboard[crossPocket] = 0;
}
return currentPosition;
}
/*
* Retrieves the current player's mancala
* Requirement:
*/
getCurrentMancala(currentPlayer: number): number {
switch (currentPlayer) {
case 0:
return 6;
case 1:
return 13;
default:
throw new Error('Current player is not set to 0 or 1');
}
}
/*
* Retrieves the opposing player's mancala
* Requirement:
*/
getOpponentMancala(currentPlayer: number): number {
switch (currentPlayer) {
case 0:
return 13;
case 1:
return 6;
default:
throw new Error('Current player is not set to 0 or 1');
}
}
/*
* Changes the current player designation from one player to the other
* Requirement:
*/
changeCurrentPlayer(currentPlayer): number {
switch (currentPlayer) {
case 0:
this._playerA.turn = false;
this._playerB.turn = true;
return 1;
case 1:
this._playerA.turn = true;
this._playerB.turn = false;
return 0;
default:
throw new Error('Current player is not set to 0 or 1');
}
}
/*
* Retrieves the pocket directly across the board from the current pocket
* Utilized when players land in their own empty pockets
* They can steal stones from the opposing player's "cross-pocket"
* Requirement:
*/
getCrossPocket(pocket: number): number {
if ((pocket >= 0 && pocket <= 5) || (pocket >= 7 && pocket <= 12)) {
return (pocket + 12) - (pocket * 2);
} else {
throw new Error('Pocket provided is either a mancala or out of bounds');
}
}
/*
* Retrieves the name of the a pocket given the position number
* Requirement:
*/
getPositionName(position: number): string {
if (position >= 0 && position <= 5) {
return 'A' + (position + 1);
} else if (position === 6) {
return 'Mancala A';
} else if (position >= 7 && position <= 12) {
return 'B' + (position - 6);
} else if (position === 13) {
return 'Mancala B';
} else {
throw new Error('Position provided is out of bounds');
}
}
/*
* Returns true if the location is a mancala, otherwise return false
* Requirement:
*/
checkIfMancala(pocket: number): boolean {
return (pocket === 6 || pocket === 13) ? true : false;
}
/*
* Synchronizes the players' scores with number of stones in their respective mancalas
* Requirement:
*/
updateScores() {
this._playerA.score = this._gameboard[6];
this._playerB.score = this._gameboard[13];
}
}
|
cd18dd8cd696ddf66b90e173436e45b1b982cb4e
|
TypeScript
|
mion-madiori/deckBuilder
|
/js/patternSpecification/NotSpecification.ts
| 3.046875
| 3
|
class NotSpecification<T> extends AbstractCompositeSpecification<T>{
private other:Specification<T>;
constructor(other:Specification<T>){
super();
this.other = other;
}
isSatisfiedBy(candidate:T):boolean{
return !this.other.isSatisfiedBy(candidate);
}
toString():string{
return `(not ${this.other.toString()})`;
}
}
|
6f0f8f5b868544d1f81fc42768eb4e6e0298180d
|
TypeScript
|
inker/metro
|
/src/utils/math/index.ts
| 3.046875
| 3
|
import { Point, point } from 'leaflet'
import { head, last } from 'lodash'
import {
bisect,
dot,
det,
intersection,
orthogonal,
normalize,
} from './vector'
export const isNatural = (n: number) =>
n > 0 && Number.isInteger(n)
export const isArbitrarilySmall = (n: number) =>
Math.abs(n) <= Number.EPSILON
const getMidPoint = (a: Point, b: Point, part: number) =>
b.subtract(a).multiplyBy(part).add(a)
const getMidPoints = (points: Point[], part: number) =>
points.slice(1).map((p, i) => getMidPoint(points[i], p, part))
const getMidVertices = (points: Point[], part: number) =>
getVertices(getMidPoints(points, part), part)
const getVertices = (points: Point[], part: number): Point[] =>
points.length < 2 ? points : [
head(points)!,
...getMidVertices(points, part),
last(points)!,
]
export function splitInTwo(points: Point[], part: number): [Point[], Point[]] {
const cps = getVertices(points, part)
const mid = cps.length >> 1
return [
cps.slice(0, mid + 1),
cps.slice(mid),
]
}
export function split(points: Point[], k: number): Point[][] {
if (!isNatural(k)) {
throw new Error(`k must be a natural number, got ${k} instead`)
}
if (k === 1) {
return [points]
}
const [first, rest] = splitInTwo(points, 1 / k)
return [first, ...split(rest, k - 1)]
}
export function offsetLine(points: Point[], d: number): Point[] {
if (points.length !== 2) {
throw new Error('line must have 2 points')
}
if (points[0].equals(points[1])) {
throw new Error('points are overlapped')
}
const vec = points[1].subtract(points[0])
const [o] = orthogonal(vec)
const normal = normalize(o)
const offsetVec = normal.multiplyBy(d)
return points.map(p => p.add(offsetVec))
}
export function offsetPath(controlPoints: Point[], d: number): Point[] {
if (controlPoints.length < 2) {
throw new Error('there should be at least 2 control points for an offset')
}
return controlPoints.map((cp, i) => {
const prev = controlPoints[i - 1]
const next = controlPoints[i + 1]
if (!prev) {
return offsetLine([cp, next], d)[0]
}
if (!next) {
return offsetLine([prev, cp], d)[1]
}
const [prevO, cpO] = offsetLine([prev, cp], d)
const [nextO] = offsetLine([next, cp], -d)
const ba = prev.subtract(cp)
const bc = next.subtract(cp)
return intersection([prevO, ba], [nextO, bc]) || cpO
})
}
export function makeWings(a: Point, b: Point, c: Point, length = 1): Point[] {
const ba = a.subtract(b)
const bc = c.subtract(b)
const bis = bisect(ba, bc)
const t = det(ba, bc) < 0 ? -length : length
return orthogonal(bis.multiplyBy(t))
}
export function getCircumcenter(pts: Point[]): Point | null {
if (pts.length !== 3) {
throw new Error('must have 3 vertices')
}
const a = pts[0]
const b = pts[1].subtract(a)
const c = pts[2].subtract(a)
const bb = dot(b, b)
const cc = dot(c, c)
const bxc = det(b, c)
if (Math.abs(bxc) < Number.EPSILON) {
// points are placed on a straight line
return null
}
return point(c.y * bb - b.y * cc, b.x * cc - c.x * bb)
.divideBy(2 * bxc)
.add(a)
}
export function vectorToGradCoordinates(vec: Point) {
const x = Math.abs(vec.x)
const y = Math.abs(vec.y)
return vec.divideBy(x < y ? y : x)
}
|
ac5086b340cd8bcc61dce6a94c4f77644ed4c5dd
|
TypeScript
|
green-fox-academy/tundecsapo
|
/week-02/day-01/bubble.ts
| 4.125
| 4
|
// Create a function that takes a list of numbers as parameter
// Returns a list where the elements are sorted in ascending numerical order
// Make a second boolean parameter, if it's `True` sort that list descending
//NOTE: the given example for the advanced function are incorrect
function bubble(list: number[]): number[] {
list = list.sort(function(a, b) {
return a - b
});
return list;
}
console.log(bubble([34, 12, 24, 9, 5]));
//Advanced function
function advancedBubble(list: number[], bool?: boolean) {
if (bool === true) {
list = list.sort(function(a, b) {
return b - a
})
} else {
list = list.sort(function(a, b) {
return a - b
});
}
return list;
}
console.log(advancedBubble([34, 12, 24, 9, 5]));
console.log(advancedBubble([34, 12, 24, 9, 5], true));
console.log(advancedBubble([34, 12, 24, 9, 5], false));
|
48f832c44e501073e7238188c32384b6d99663f6
|
TypeScript
|
guimpo/internet_banking
|
/frontend/src/app/new-mensagens.component.ts
| 2.59375
| 3
|
import { Component , Output, EventEmitter } from '@angular/core'
//tem que importa o que foi criado tal sera webservice
import { WebService } from './web.service';
@Component({
selector: 'new-mensagem',
template: `
<mat-card style="margin:18px;">
<mat-card-content>
<mat-form-field>
<input [(ngModel)]="message.nome" matInput placeholder="Name">
</mat-form-field>
<mat-form-field>
<input [(ngModel)]="message.sobrenome" matInput placeholder="Sobrenome">
</mat-form-field>
<mat-card-actions>
<button (click)="post()" mat-button color="primary">POST</button>
</mat-card-actions>
</mat-card-content>
</mat-card>
`,
})
export class NewMenssageComponent {
// atualiza em tempo real
@Output() onPosted = new EventEmitter();
constructor(private webService : WebService){}
// iniciando menssage
message = {
nome: "",
sobrenome: ""
}
post(){
this.webService.postMessage(this.message);
// atualiza pagina em tempo real
this.onPosted.emit(this.message);
}
}
|
1a1baf40e39ab3944b85174100ec5cf0cc04a901
|
TypeScript
|
enixdark/ClusterWS-Client-JS
|
/src/modules/parser.ts
| 2.671875
| 3
|
import ClusterWS from '../index'
import { CustomObject, Message } from '../utils/types'
export function decode(socket: ClusterWS, message: Message): void {
const userMessage: Message = socket.options.encodeDecodeEngine ?
socket.options.encodeDecodeEngine.decode(message['#'][2]) : message['#'][2]
const actions: CustomObject = {
e: (): void => socket.events.emit(message['#'][1], userMessage),
p: (): void => socket.channels[message['#'][1]] && socket.channels[message['#'][1]].onMessage(userMessage),
s: {
c: (): void => {
socket.useBinary = userMessage.binary
socket.resetPing(userMessage.ping)
socket.events.emit('connect')
}
}
}
return message['#'][0] === 's' ?
actions[message['#'][0]][message['#'][1]] && actions[message['#'][0]][message['#'][1]]() :
actions[message['#'][0]] && actions[message['#'][0]]()
}
export function encode(event: string, data: Message, eventType: string): string {
const message: CustomObject = {
emit: { '#': ['e', event, data] },
publish: { '#': ['p', event, data] },
system: {
subscribe: { '#': ['s', 's', data] },
unsubscribe: { '#': ['s', 'u', data] }
}
}
return JSON.stringify(eventType === 'system' ?
message[eventType][event] : message[eventType])
}
|
db86805a502d8f1323fb312720a79564ed4c22fe
|
TypeScript
|
nkint/umbrella
|
/packages/color/src/hsva.ts
| 2.75
| 3
|
import { declareIndices, IVector } from "@thi.ng/vectors";
import { Color, ColorMode } from "./api";
import { AColor } from "./internal/acolor";
import { ensureArgs } from "./internal/ensure-args";
export function hsva(col: Color, offset?: number, stride?: number): HSVA;
export function hsva(h?: number, s?: number, v?: number, a?: number): HSVA;
export function hsva(...args: any[]) {
return new HSVA(...ensureArgs(args));
}
export class HSVA extends AColor<HSVA> implements IVector<HSVA> {
h!: number;
s!: number;
v!: number;
a!: number;
get mode() {
return ColorMode.HSVA;
}
copy() {
return new HSVA(this.deref());
}
copyView() {
return new HSVA(this.buf, this.offset, this.stride);
}
empty() {
return new HSVA();
}
}
declareIndices(HSVA.prototype, ["h", "s", "v", "a"]);
|
2368e0b0df58940894c119c0edc53eca81708ff6
|
TypeScript
|
Camille1007/tsharp
|
/test/extentions/test_String.ts
| 3.34375
| 3
|
import "../../src/extentions/String";
import "../../src/extentions/Number";
import "../../src/extentions/Date";
import "mocha"
import * as assert from "assert";
describe("String", () => {
describe("String.isNullOrEmpty", () => {
it("null is nullOrEmpty", () => {
assert.equal(String.isNullOrEmpty(null), true);
});
it("undefined is nullOrEmpty", () => {
assert.equal(String.isNullOrEmpty(undefined), true);
});
it("'' is nullOrEmpty", () => {
assert.equal(String.isNullOrEmpty(''), true);
});
it("'abc' is not nullOrEmpty", () => {
assert.equal(String.isNullOrEmpty('abc'), false);
});
it("' ' is not nullOrEmpty", () => {
assert.equal(String.isNullOrEmpty(' '), false);
});
it("'\\t' is not nullOrEmpty", () => {
assert.equal(String.isNullOrEmpty('\t'), false);
});
it("'\\n' is not nullOrEmpty", () => {
assert.equal(String.isNullOrEmpty('\n'), false);
});
it("'\\r' is not nullOrEmpty", () => {
assert.equal(String.isNullOrEmpty('\r'), false);
});
it("'\\r\\n' is not nullOrEmpty", () => {
assert.equal(String.isNullOrEmpty('\r\n'), false);
});
it("'0' is not nullOrEmpty", () => {
assert.equal(String.isNullOrEmpty('0'), false);
});
});
describe("String.isNullOrWhiteSpace", () => {
it("null is nullOrWhiteSpace", () => {
assert.equal(String.isNullOrWhiteSpace(null), true);
});
it("undefined is nullOrWhiteSpace", () => {
assert.equal(String.isNullOrWhiteSpace(undefined), true);
});
it("'' is nullOrWhiteSpace", () => {
assert.equal(String.isNullOrWhiteSpace(''), true);
});
it("'abc' is not nullOrWhiteSpace", () => {
assert.equal(String.isNullOrWhiteSpace('abc'), false);
});
it("' ' is nullOrWhiteSpace", () => {
assert.equal(String.isNullOrWhiteSpace(' '), true);
});
it("'\\t' is nullOrWhiteSpace", () => {
assert.equal(String.isNullOrWhiteSpace('\t'), true);
});
it("'\\n' is nullOrWhiteSpace", () => {
assert.equal(String.isNullOrWhiteSpace('\n'), true);
});
it("'\\r' is nullOrWhiteSpace", () => {
assert.equal(String.isNullOrWhiteSpace('\r'), true);
});
it("'\\r\\n' is nullOrWhiteSpace", () => {
assert.equal(String.isNullOrWhiteSpace('\r\n'), true);
});
it("'0' is not nullOrWhiteSpace", () => {
assert.equal(String.isNullOrWhiteSpace('0'), false);
});
});
describe("String.format", () => {
it("null format result is null", () => {
assert.equal(String.format(null), null);
});
it("'' format result is ''", () => {
assert.equal(String.format(''), '');
});
it("format null or undefined value", () => {
assert.equal(String.format('ab{0}c', null), "abc");
assert.equal(String.format('ab{0}c', undefined), "abc");
});
it('no custom format', () => {
assert.equal(String.format('{0:f2}', {}), '[object Object]');
});
it("format width is ok", () => {
assert.equal(String.format("a{0,3}b", 12), "a 12b");
assert.equal(String.format("a{0,-3}b", 12), "a12 b");
assert.equal(String.format("a{0,3}b", 123), "a123b");
assert.equal(String.format("a{0,-3}b", 123), "a123b");
assert.equal(String.format("a{0,3}b", 1234), "a1234b");
assert.equal(String.format("a{0,-3}b", 1234), "a1234b");
});
it("'{0}+{1}={2}' with args [2,3,5] format result is '2+3=5'", () => {
assert.equal(String.format('{0}+{1}={2}', 2, 3, 5), '2+3=5');
});
it("'{0,-8#green:f2}+{1#red#bold}={2,10 # # blue #bgRed ### :f3}' with args [2,3,5] format result is '...'", () => {
let expected="\x1B[32m2.00\x1B[39m +\x1B[1m\x1B[31m3\x1B[39m\x1B[22m= \x1B[41m\x1B[34m5.000\x1B[39m\x1B[49m";
let actual=String.format('{0,-8#green:f2}+{1#red#bold}={2,10 # # blue #bgRed ### :f3}', 2, 3, 5);
assert.equal(actual,expected);
});
it("format styled text",function(){
let expected=' \x1B[32mABC\x1B[39m';
let actual= String.format("{0,5:upper}","abc".toColorful('green'))
assert.equal(actual,expected)
});
it("'{0,-2}*{1,2} = {2:f2}' with args [8,9,72] format result is '8 * 9= 72.00'", () => {
assert.equal(String.format('{0,-2}*{1,2} = {2:f2}', 8, 9, 72), '8 * 9 = 72.00');
});
it("format datetime is ok.", () => {
assert.equal(String.format('北京时间:{time:YYYY年MM月DD日 HH:mm:ss}', { time: new Date('2018-11-10 23:58:40') }), '北京时间:2018年11月10日 23:58:40');
});
it("'[{name},{age}]' with args {name:'zhangsan',age:17} format result is '[zhangsan,17]'", () => {
assert.equal(String.format('[{name},{age}]', { name: 'zhangsan', age: 17 }), '[zhangsan,17]');
});
});
describe("String.from", () => {
it("String.from(' ', 5) equals ' '", () => {
assert.equal(String.from(' ', 5), ' ');
});
it("String.from('ab', 3) equals 'ababab'", () => {
assert.equal(String.from('ab', 3), 'ababab');
});
it("String.from('', 10) equals ''", () => {
assert.equal(String.from('', 10), '');
});
it("String.from(null, 10) equals null", () => {
assert.equal(String.from(null, 10), "");
});
it("String.from(undefined, 10) equals undefined", () => {
assert.equal(String.from(undefined, 10), "");
});
});
describe("startWithPattern", () => {
it("abc start with pattern abc", () => {
assert.equal('abc'.startsWithPattern(/abc/), true);
});
it("abc start with pattern a", () => {
assert.equal('abc'.startsWithPattern(/a/), true);
});
it("123abc start with pattern ^\\d", () => {
assert.equal('123abc'.startsWithPattern(/^\d/), true);
});
it("abc not start with pattern b", () => {
assert.equal('abc'.startsWithPattern(/b/), false);
});
it("abc start with pattern \\w", () => {
assert.equal('abc'.startsWithPattern(/\w/), true);
});
it("abc123 start with pattern \\w+", () => {
assert.equal('abc123'.startsWithPattern(/\w+/), true);
});
it("abc123 not start with pattern \\d+", () => {
assert.equal('abc123'.startsWithPattern(/\d+/), false);
});
it("123abc start with pattern \\d+", () => {
assert.equal('123abc'.startsWithPattern(/\d+/), true);
});
it("'' not start with pattern \\d+", () => {
assert.equal(''.startsWithPattern(/\\d+/), false);
});
it("'' start with pattern \\d*", () => {
assert.equal(''.startsWithPattern(/\d*/), true);
});
it(' start with null pattern throws error', () => {
assert.throws(() => { ''.startsWithPattern(null) });
});
});
describe("endsWithPattern", () => {
it("abc end with pattern abc", () => {
assert.equal('abc'.endsWithPattern(/abc/), true);
});
it("abc end with pattern c", () => {
assert.equal('abc'.endsWithPattern(/c/), true);
});
it("abc123 end with pattern \\d+$", () => {
assert.equal('abc123'.endsWithPattern(/\d+$/), true);
});
it("abc end end with pattern b", () => {
assert.equal('abc'.endsWithPattern(/b/), false);
});
it("abc end with pattern \\w", () => {
assert.equal('abc'.endsWithPattern(/\w/), true);
});
it("abc123 not end with pattern \\w+", () => {
assert.equal('abc123'.endsWithPattern(/\w+/), true);
});
it("abc123 end with pattern \\d+", () => {
assert.equal('abc123'.endsWithPattern(/\d+/), true);
});
it("123abc not end with pattern \\d+", () => {
assert.equal('123abc'.endsWithPattern(/\d+/), false);
});
it("'' not end with pattern \\d+", () => {
assert.equal(''.endsWithPattern(/\d+/), false);
});
it("'' end with pattern \\d*", () => {
assert.equal(''.endsWithPattern(/\d*/), true);
});
it(' end with null pattern throws error', () => {
assert.throws(() => { ''.endsWithPattern(null) });
});
});
describe("trimStart", () => {
it("abc trim start equals 'abc'", () => {
assert.equal("abc".trimStart(), "abc")
});
it("' abc' trim start equals 'abc'", () => {
assert.equal(" abc".trimStart(), "abc")
});
it("'\\tabc' trim start equals 'abc'", () => {
assert.equal("\tabc".trimStart(), "abc")
});
it("'\\nabc' trim start equals 'abc'", () => {
assert.equal("\nabc".trimStart(), "abc")
});
it("'\\rabc' trim start equals 'abc'", () => {
assert.equal("\rabc".trimStart(), "abc")
});
it("' \\r\\n\\t abc' trim start equals 'abc'", () => {
assert.equal(" \r\n\t abc".trimStart(), "abc")
});
it("' \\r\\n\\t abc ' trim start equals 'abc '", () => {
assert.equal(" \r\n\t abc ".trimStart(), "abc ")
});
});
describe("trimEnd", () => {
it("'abc' trim end equals 'abc'", () => {
assert.equal("abc".trimEnd(), "abc");
});
it("'abc ' trim end equals 'abc'", () => {
assert.equal("abc ".trimEnd(), "abc");
});
it("'abc\\t' trim end equals 'abc'", () => {
assert.equal("abc\t".trimEnd(), "abc");
});
it("'abc\\n' trim end equals 'abc'", () => {
assert.equal("abc\n".trimEnd(), "abc");
});
it("'abc\\r' trim end equals abc", () => {
assert.equal("abc\r".trimEnd(), "abc");
});
it("'abc \\r\\n\\t ' trim end equals abc", () => {
assert.equal("abc \r\n\t ".trimEnd(), "abc");
});
it("'abc \\r\\n\\t ' trim end equals ' abc'", () => {
assert.equal(" abc \r\n\t ".trimEnd(), " abc");
});
});
describe("trimChars", () => {
it(`" abc " trimChars(null) get "abc"`, function () {
assert.equal(" abc ".trimChars(null), "abc");
})
it(`" abc " trimChars() get "abc"`, function () {
assert.equal(" abc ".trimChars(""), "abc");
})
it(`" abc d" trimChars() get "abc d"`, function () {
assert.equal(" abc d".trimChars(""), "abc d");
})
it(`" " trimChars() get ""`, function () {
assert.equal(" ".trimChars(""), "");
})
it(`"aaaa" trimChars(a) get ""`, function () {
assert.equal("aaaa".trimChars("a"), "");
})
it(`" aaaa" trimChars(a) get " "`, function () {
assert.equal(" aaaa".trimChars("a"), " ");
})
it(`" aaaa " trimChars(a) get " aaaa "`, function () {
assert.equal(" aaaa ".trimChars("a"), " aaaa ");
})
it(`"abaaab" trimChars(ab) get ""`, function () {
assert.equal("abaaab".trimChars("ab"), "");
})
it(`"abcabcabc" trimChars(ab) get "cabcabc"`, function () {
assert.equal("abcabcabc".trimChars("ab"), "cabcabc");
})
});
describe("replaceAll", () => {
it("'abc' replaceall 'b' to '#' get 'a#c'", () => {
assert.equal("abc".replaceAll('b', '#'), "a#c");
});
it("'abcabcabc' replaceall 'b' to '#' get 'a#ca#ca#c'", () => {
assert.equal("abcabcabc".replaceAll('b', '#'), "a#ca#ca#c");
});
it("'abcabcabc' replaceall 'b' to '' get 'acacac'", () => {
assert.equal("abcabcabc".replaceAll('b', ''), "acacac");
});
it("'abcabcabc' replaceall '' to '##' get 'abcabcabc'", () => {
assert.equal("abcabcabc".replaceAll('', '##'), "abcabcabc");
});
it("'abcabcabc' replaceall null to '##' get 'abcabcabc'", () => {
assert.equal("abcabcabc".replaceAll(null, '##'), "abcabcabc");
});
it("'abcabcabc' replaceall ' ' to '##' get 'abcabcabc'", () => {
assert.equal("abcabcabc".replaceAll(' ', '##'), "abcabcabc");
});
});
describe("equals", () => {
it("'abc' equals 'abc'", () => {
assert.equal("abc".equals("abc"), true);
});
it("'abc' not equals null", () => {
assert.equal("abc".equals(null), false);
});
it("'abc' not equals ''", () => {
assert.equal("abc".equals(''), false);
});
it("'' equals ''", () => {
assert.equal("".equals(''), true);
});
it("'' not equals null", () => {
assert.equal("".equals(null), false);
});
it("'' not equals ' '", () => {
assert.equal("".equals(" "), false);
});
it("'abc' not equals 'Abc'", () => {
assert.equal("abc".equals("Abc"), false);
});
it("'abc' equals 'Abc' if ignore case", () => {
assert.equal("abc".equals("Abc", true), true);
});
it("'abc' not equals 'ABCD' if ignore case", () => {
assert.equal("abc".equals("ABCD", true), false);
});
});
describe("contains", () => {
it("'abcde' contains 'bcd'", () => {
assert.equal("abcde".contains("bcd"), true);
});
it("'abcde' contains 'abcde'", () => {
assert.equal("abcde".contains("abcde"), true);
});
it("'abcde' not contains 'abcdef'", () => {
assert.equal("abcde".contains("abcdef"), false);
});
it("'abcde' contains ''", () => {
assert.equal("abcde".contains(""), true);
});
it("'abcde' not contains null", () => {
assert.equal("abcde".contains(null), false);
});
it("'abcde' not contains 'BCD'", () => {
assert.equal("abcde".contains('BCD'), false);
});
it("'abcde' contains 'BCD' if ignore case", () => {
assert.equal("abcde".contains('BCD', true), true);
});
it("'abcde' contains 'ABCDE' if ignore case", () => {
assert.equal("abcde".contains('ABCDE', true), true);
});
it("'abcde' not contains 'ABCDEF' if ignore case", () => {
assert.equal("abcde".contains('ABCDEF', true), false);
});
});
describe("reverse", () => {
it("'abc'reverse() equals 'cba'", () => {
assert.equal("abc".reverse(), "cba");
});
});
describe("toCharArray", () => {
it("'abc'toCharArray() equals ['a','b','c']", () => {
assert.deepEqual("abc".toCharArrays(), ['a', 'b', 'c']);
})
});
describe("isLower", () => {
it("'abc'isLower() is true", () => {
assert.equal("abc".isLower(), true);
});
it("''isLower() is false", () => {
assert.equal("".isLower(), false);
});
it("'abc123'isLower() is false", () => {
assert.equal("abc123".isLower(), false);
});
it("'Abc'isLower() is false", () => {
assert.equal("Abc".isLower(), false);
})
});
describe("isUpper", () => {
it("'ABC'isUpper() is true", () => {
assert.equal("ABC".isUpper(), true);
});
it("''isUpper() is false", () => {
assert.equal("".isUpper(), false);
});
it("'ABC123'isUpper() is true", () => {
assert.equal("ABC123".isUpper(), false);
});
it("'Abc'isUpper() is false", () => {
assert.equal("Abc".isUpper(), false);
})
});
describe("isSpace", () => {
it("' \\t\\n\\t\\r'isSpace() is true", () => {
assert.equal(" \t\n\t\r".isSpace(), true);
});
it("''isSpace() is false", () => {
assert.equal("".isSpace(), false);
});
it("' a 'isSpace() is false", () => {
assert.equal(" a ".isSpace(), false);
});
});
describe("isDigit", () => {
it("'123'isDigit() is true", () => {
assert.equal("123".isDigit(), true);
});
it("''isDigit() is false", () => {
assert.equal("".isDigit(), false);
});
it("'123abc'isDigit() is false", () => {
assert.equal("123abc".isDigit(), false);
});
it("'abc123'isDigit() is false", () => {
assert.equal("abc123".isDigit(), false);
})
});
describe("isLowerOrDigit", () => {
it("'123'isLowerOrDigit() is true", () => {
assert.equal("123".isLowerOrDigit(), true);
});
it("'abc'isLowerOrDigit() is true", () => {
assert.equal("abc".isLowerOrDigit(), true);
});
it("''isLowerOrDigit() is false", () => {
assert.equal("".isLowerOrDigit(), false);
});
it("'123abc123'isLowerOrDigit() is true", () => {
assert.equal("123abc123".isLowerOrDigit(), true);
});
it("'123ABC123'isLowerOrDigit() is false", () => {
assert.equal("123ABC123".isLowerOrDigit(), false);
});
});
describe("isUpperOrDigit", () => {
it("'123'isUpperOrDigit() is true", () => {
assert.equal("123".isUpperOrDigit(), true);
});
it("'ABC'isUpperOrDigit() is true", () => {
assert.equal("ABC".isUpperOrDigit(), true);
});
it("''isUpperOrDigit() is false", () => {
assert.equal("".isUpperOrDigit(), false);
});
it("'123abc123'isUpperOrDigit() is false", () => {
assert.equal("123abc123".isUpperOrDigit(), false);
});
it("'123ABC123'isUpperOrDigit() is true", () => {
assert.equal("123ABC123".isUpperOrDigit(), true);
});
});
describe("isAlpha", () => {
it("'abc'isAlpha() is true", () => {
assert.equal("abc".isAlpha(), true);
});
it("'ABC'isAlpha() is true", () => {
assert.equal("ABC".isAlpha(), true);
});
it("'abcABC'isAlpha() is true", () => {
assert.equal("abcABC".isAlpha(), true);
});
it("''isAlpha() is false", () => {
assert.equal("".isAlpha(), false);
});
it("'123abcABC'isAlpha() is false", () => {
assert.equal("123abcABC".isAlpha(), false);
});
});
describe("isAlphaOrDigit", () => {
it("'abc'isAlphaOrDigit() is true", () => {
assert.equal("abc".isAlphaOrDigit(), true);
});
it("'ABC'isAlphaOrDigit() is true", () => {
assert.equal("ABC".isAlphaOrDigit(), true);
});
it("'abcABC'isAlphaOrDigit() is true", () => {
assert.equal("abcABC".isAlphaOrDigit(), true);
});
it("'123abcABC'isAlphaOrDigit() is true", () => {
assert.equal("123abcABC".isAlphaOrDigit(), true);
});
it("''isAlphaOrDigit() is false", () => {
assert.equal("".isAlphaOrDigit(), false);
});
it("'Hello,World'isAlphaOrDigit() is false", () => {
assert.equal("Hello,World".isAlphaOrDigit(), false);
});
});
describe("isBoolean", () => {
it("'true' is boolean", () => {
assert.equal('true'.isBoolean(), true);
});
it("'TRUE' is boolean", () => {
assert.equal('TRUE'.isBoolean(), true);
});
it("'True' is boolean", () => {
assert.equal('True'.isBoolean(), true);
});
it("'+True' is not boolean", () => {
assert.equal('+True'.isBoolean(), false);
});
it("'false' is boolean", () => {
assert.equal('false'.isBoolean(), true);
});
it("'FALSE' is boolean", () => {
assert.equal('FALSE'.isBoolean(), true);
});
it("'False' is boolean", () => {
assert.equal('False'.isBoolean(), true);
});
it("'-False' is not boolean", () => {
assert.equal('-False'.isBoolean(), false);
});
it("'' is not boolean", () => {
assert.equal(''.isBoolean(), false);
});
it("'abc' is not boolean", () => {
assert.equal('abc'.isBoolean(), false);
});
});
describe("isNumber", () => {
it("'123' is number", () => {
assert.equal('123'.isNumber(), true);
});
it("'.123' is number", () => {
assert.equal('.123'.isNumber(), true);
});
it("'-.123' is number", () => {
assert.equal('-.123'.isNumber(), true);
});
it("'+.123' is number", () => {
assert.equal('+.123'.isNumber(), true);
});
it("'123a' is not number", () => {
assert.equal('123a'.isNumber(), false);
});
it("'abc' is not number", () => {
assert.equal('abc'.isNumber(), false);
});
it('Infinity is not number', () => {
assert.equal((1 / 0).toString().isNumber(), false);
});
});
describe("isPattern", () => {
it("'123' is '\\d+' pattern ", () => {
assert.equal('123'.isPattern(/\d+/), true);
});
it("'abc' is not '\\d+' pattern ", () => {
assert.equal('abc'.isPattern(/\d+/), false);
});
it("throw error if pattern is null ", () => {
assert.throws(() => { 'abc'.isPattern(null) });
});
});
describe("isEmail", () => {
const validEmails = [
"ma@hostname.com",
"ma@hostname.comcom",
"m.a@hostname.co",
"m_a1a@hostname.com",
"ma-a@hostname.com",
"ma-a@hostname.com.edu",
"ma-a.aa@hostname.com.edu",
"ma.h.saraf.onemore@hostname.com.edu",
"ma12@hostname.com",
"12@hostname.com",
];
const invalidEmails = [
"Abc.example.com", // No `@`
"A@b@c@example.com", // multiple `@`
"ma...ma@jjf.co", // continuous multiple dots in name
"ma@jjf..com", // continuous multiple dots in domain
"ma@@jjf.com", // continuous multiple `@`
"@majjf.com", // nothing before `@`
"ma.@jjf.com", // nothing after `.`
"ma_@jjf", // no domain extension
"ma_@jjf.", // nothing after `_` and .
"ma@jjf.", // nothing after `.`
];
describe('valid email address', () => {
validEmails.forEach(text => {
it(`'${text} is valid email'`, () => {
assert.equal(text.isEmail(), true);
});
});
});
describe('invalid eamil address', () => {
invalidEmails.forEach(text => {
it(`'${text} is invalid email'`, () => {
assert.equal(text.isEmail(), false);
});
});
});
});
describe("isVarName", () => {
const validNames = [
'_',
'$',
'__',
'$$',
'$a$',
'_a_',
'name',
'name100',
'name_100'
];
const invalidNames = [
'123',
'abc.efg',
'abc\nefg',
''
]
describe('valid var name', () => {
validNames.forEach(text => {
it(`'${text} is valid var name'`, () => {
assert.equal(text.isVarName(), true);
});
});
});
describe('invalid var name', () => {
invalidNames.forEach(text => {
it(`'${text} is invalid var name'`, () => {
assert.equal(text.isVarName(), false);
});
});
});
});
describe("hashCode", () => {
it("the hash code is unique and fixed", () => {
let text1 = Math.round((Math.random() * 1000)).toString();
let text2 = Math.round((Math.random() * 1000)).toString();
let hashCode1 = text1.hashCode();
let hashCode2 = text2.hashCode();
if (text1 === text2) {
assert.equal(hashCode1, hashCode2);
} else {
assert.notEqual(hashCode1, hashCode2);
}
})
});
describe("truncat", () => {
it("'abcde' truncat 10 is 'abcde'", () => {
assert.equal('abcde'.truncat(10), 'abcde');
});
it("'abcde' truncat 5 is 'abcde'", () => {
assert.equal('abcde'.truncat(5), 'abcde');
});
it("'abcdef' truncat 5 is 'abcde'", () => {
assert.equal('abcdef'.truncat(5), 'ab...');
});
it("'abcdef' truncat(5,'##') is 'abcde'", () => {
assert.equal('abcdef'.truncat(5, '##'), 'abc##');
});
it('throws error if the ends text too long', () => {
assert.throws(() => { 'abc'.truncat(2) });
});
});
describe("htmlEncode", () => {
const datas = [
["", ""],
["\n", "<br>"],
["<", "<"],
[">", ">"],
["&", "&"],
["<>", "<>"],
["<>\"abc&", "<>\"abc&"],
["<p>test!</p>", "<p>test!</p>"]
]
datas.forEach(([text, encode]) => {
it(`htmlencode "${text}" get "${encode}"`, () => {
assert.equal(encode, text.htmlEncode());
})
})
});
describe("htmlDecode", () => {
const datas = [
["", ""],
["\n", "<br>"],
["<", "<"],
[">", ">"],
["&", "&"],
["<>", "<>"],
["<>\"abc&", "<>\"abc&"],
["<p>test!</p>", "<p>test!</p>"]
]
datas.forEach(([text, encode]) => {
it(`htmldecode "${encode}" get "${text}"`, () => {
assert.equal(text, encode.htmlDocode());
})
})
});
describe("toTitleCase", () => {
const data = [
["", ""],
["abc", "Abc"],
["Hello world", "Hello World"],
["wAr aNd pEaCe", "War And Peace"],
["ABC", "Abc"],
["Abc", "Abc"],
];
data.forEach(([from, to]) => {
it(`"${from}" toTileCase get "${to}"`, function () {
assert.equal(from.toTitleCase(), to);
});
});
});
describe("toCamelCase", () => {
const data = [
["", ""],
["abc", "abc"],
["Hello world", "helloWorld"],
["background-color", "backgroundColor"],
["background_color", "backgroundColor"],
["backgroundColor", "backgroundColor"],
["ab-cd-ef", "abCdEf"],
["ab-cd-ef-", "abCdEf"],
["ab-cd-ef--", "abCdEf"],
["ab-cd--ef--", "abCdEf"],
["--ab-cd--ef--", "abCdEf"],
["--ab-cd-__-ef--", "abCdEf"]
];
data.forEach(([from, to]) => {
it(`"${from}" toCamelCase get "${to}"`, function () {
assert.equal(from.toCamelCase(), to);
});
});
const data2 = [
["", ""],
["abc", "Abc"],
["Hello world", "HelloWorld"],
["background-color", "BackgroundColor"],
["background_color", "BackgroundColor"],
["backgroundColor", "BackgroundColor"],
["ab-cd-ef", "AbCdEf"],
["ab-cd-ef-", "AbCdEf"],
["ab-cd-ef--", "AbCdEf"],
["ab-cd--ef--", "AbCdEf"],
["--ab-cd--ef--", "AbCdEf"],
["--ab-cd-__-ef--", "AbCdEf"]
];
data2.forEach(([from, to]) => {
it(`"${from}" toCamelCase with firstWorldUpper get "${to}"`, function () {
assert.equal(from.toCamelCase(true), to);
});
});
});
describe("toCssName", () => {
const data = [
["", ""],
["border", "border"],
["borderBottom", "border-bottom"],
["borderBottomColor", "border-bottom-color"],
["border-bottom", "border-bottom"],
["border-bottom-color", "border-bottom-color"],
];
data.forEach(([from, to]) => {
it(`"${from}" toCssName get "${to}"`, function () {
assert.equal(from.toCssName(), to);
});
})
});
describe("toColorful", () => {
it(`abc toColorful("blue") == "\x1B[34mabc\x1B[39m"`, function () {
let actual = "abc".toColorful("blue")
assert.equal(actual, "\x1B[34mabc\x1B[39m");
});
it('redBright',function(){
let actual = "abc".toColorful("redBright");
assert.equal(actual, "\x1B[91mabc\x1B[39m");
}
)
it(`abc toColorful("blue","cyanBG") == "\x1B[46m\x1B[34mabc\x1B[39m\x1B[49m"`, function () {
let actual = "abc".toColorful("blue", "bgCyan")
assert.equal(actual, "\x1B[46m\x1B[34mabc\x1B[39m\x1B[49m");
});
it(`abc toColorful("blue","cyanBG","bold","italic") == "\x1B[46m\x1B[34mabc\x1B[39m\x1B[49m"`, function () {
let actual = "abc".toColorful("blue", "bgCyan", "bold", "italic")
assert.equal(actual, "\x1B[3m\x1B[1m\x1B[46m\x1B[34mabc\x1B[39m\x1B[49m\x1B[22m\x1B[23m");
});
it(`nested colorful works ok`,function(){
let actual=`a${'b'.toColorful('red')}c`.toColorful('blue');
let expected='\x1B[34ma\x1B[31mb\x1B[34mc\x1B[39m';
assert.equal(actual,expected);
})
});
describe("clearColorful", () => {
it(`"abc" clearColorful() == "abc"`, function () {
let actual = "abc".clearColurful();
assert.equal(actual, "abc");
});
it(`"\x1B[34mabc\x1B[39m" clearColorful() == "abc"`, function () {
let actual = "\x1B[34mabc\x1B[39m".clearColurful();
assert.equal(actual, "abc");
});
it(`"\x1B[46m\x1B[34mabc\x1B[39m\x1B[49m" clearColorful() == "abc"`, function () {
let actual = "\x1B[46m\x1B[34mabc\x1B[39m\x1B[49m".clearColurful()
assert.equal(actual, "abc");
});
});
describe("toFormat", () => {
const data = [["abc", "lower", "abc"],
["abc", "upper", "ABC"],
["abc", "title", "Abc"],
["abcBcd", "css", "abc-bcd"],
["abc-bcd", "camel", "abcBcd"]
]
data.forEach(([text, fmt, res]) => {
it(`"${text}".toFormat(${fmt})=="${res}"`, function () {
assert.equal(text.toFormat(fmt as any), res);
})
});
});
});
|
6bfa29f57270199242807e2d70463cbfa8ca7f12
|
TypeScript
|
brikr/advent-of-code-2020
|
/src/day13/day13.ts
| 3.046875
| 3
|
import {fileLines} from '../utils';
function part1(): number {
const [earliestLine, idsLine] = fileLines('src/day13/input.txt');
const earliest = Number(earliestLine);
const ids = idsLine
.split(',')
.map(Number)
.filter(id => !isNaN(id));
let closestMod = ids[0] - (earliest % ids[0]);
let closestModId = ids[0];
for (const id of ids) {
const delta = id - (earliest % id);
if (delta < closestMod) {
closestMod = delta;
closestModId = id;
}
}
return closestModId * closestMod;
}
function gcd(x: number, y: number): number {
if (y === 0) {
return x;
} else {
return gcd(y, x % y);
}
}
function lcm(x: number, y: number): number {
return Math.abs(x * y) / gcd(x, y);
}
function part2(): number {
const [_, idsLine] = fileLines('src/day13/input.txt');
const busses = idsLine
.split(',')
.map((id, idx) => {
return {
id: Number(id),
offset: idx,
};
})
.filter(bus => !isNaN(bus.id))
.sort((a, b) => b.id - a.id);
const first = busses.splice(0, 1)[0];
let delta = first.id;
let next = busses.splice(0, 1)[0];
let i = -first.offset;
let answerFound = false;
// console.log(`Current delta: ${delta}, next ID: ${next.id}`);
while (!answerFound) {
// console.log(i);
i += delta;
if ((next.id - (i % next.id)) % next.id === next.offset % next.id) {
// found match for next bus
// console.log(`Found match for bus ${next.id}: ${i}`);
delta = lcm(delta, next.id);
if (busses.length === 0) {
answerFound = true;
} else {
next = busses.splice(0, 1)[0];
}
}
}
return i;
}
function printSolution() {
console.log('Part 1:');
console.log(part1());
console.log('Part 2:');
console.log(part2());
// test();
}
printSolution();
|
2c15588e22d7ce8d74b499919d50dbbcc7d994ff
|
TypeScript
|
mc-aweaver/ng-conf-managing-async-with-rxjs
|
/exercises-final-with-notes/node/15-subject-subscriptions.ts
| 2.953125
| 3
|
import { Subject } from 'rxjs';
import { createLoggingObserver } from './helpers/createLoggingObserver';
const observerA = createLoggingObserver('A');
const observerB = createLoggingObserver('B');
const subject = new Subject();
const subA = subject.subscribe(observerA);
const subB = subject.subscribe(observerB);
subject.next(1);
subject.next(2);
subA.unsubscribe();
subject.next(3);
subject.next(4);
subB.unsubscribe();
subject.next(5);
subject.complete();
// TODO: Add code to unsubscribe observerA after the first two values
// TODO: Add code to unsubscribe observerB after the first four values
/**
NOTE: expected output
A 1
B 1
A 2
B 2
B 3
B 4
*/
// NOTE: this `unsubscribe` is really just removing the observer from the
// subject's internal list of observers.
// TODO: Bonus... try calling unsubscribe on the Subject itself in a few places!
|
84b7a765b92b5a61ee57be84aa4489c75ddd5efe
|
TypeScript
|
cothema/nlp-tools
|
/packages/core/src/interfaces/IStringableTokenizer.ts
| 2.625
| 3
|
import { Token } from "@cothema/nlp-model";
import { TokenizableStringableEntity } from "@cothema/nlp-model";
import { IStringable } from "@cothema/nlp-model";
export interface IStringableTokenizer<
Entity extends TokenizableStringableEntity
> {
tokenize(input: IStringable): Token<Entity>[];
tokenizeToEntities(input: IStringable): Entity[];
tokenizeToValues(input: IStringable): string[];
}
|
d85ecd07357f6be407fade6fb3f1e044ca23a34b
|
TypeScript
|
webhintio/hint
|
/packages/hint/src/lib/utils/resource-loader.ts
| 2.53125
| 3
|
/**
* @fileoverview Locates and requires resources (connectors, parsers, hints, formatters)
* for hint across different places in the tree.
* By convention, these resources need to be under
* {/, /node_modules/}lib/{connectors, formatters, parsers, hints}/*.js
*/
/*
* ------------------------------------------------------------------------------
* Requirements
* ------------------------------------------------------------------------------
*/
import * as path from 'path';
import * as globby from 'globby';
import {
findNodeModulesRoot,
findPackageRoot,
hasMultipleResources,
isFullPackageName,
loadResource,
requirePackage,
ResourceError,
ResourceErrorStatus,
ResourceType
} from '@hint/utils';
import { readFile } from '@hint/utils-fs';
import { debug as d } from '@hint/utils-debug';
import { IHintConstructor, HintResources } from '../types';
import { Configuration } from '../config';
import { IConnectorConstructor } from '../types/connector';
const debug: debug.IDebugger = d(__filename);
const HINT_ROOT: string = findPackageRoot();
const NODE_MODULES_ROOT: string = (() => {
const root: string = findNodeModulesRoot();
return root;
})();
/** Cache of resources ids. */
const resourceIds: Map<string, string[]> = new Map<string, string[]>();
/*
* ------------------------------------------------------------------------------
* Public
* ------------------------------------------------------------------------------
*/
/** Returns a list with the ids of all the core resources of the given `type`. */
/* istanbul ignore next */
export const getCoreResources = (type: string): string[] => {
if (resourceIds.has(type)) {
return resourceIds.get(type)!;
}
const resourcesFiles: string[] = globby.sync(`dist/src/lib/${type}s/**/*.js`, { cwd: HINT_ROOT });
const ids: string[] = resourcesFiles.reduce((list: string[], resourceFile: string) => {
const resourceName: string = path.basename(resourceFile, '.js');
if (path.dirname(resourceFile).includes(resourceName)) {
list.push(resourceName);
}
return list;
}, []);
resourceIds.set(type, ids);
return ids;
};
export const getInstalledResources = (type: ResourceType): string[] => {
const installedType = `installed-${type}`;
/* istanbul ignore if */
if (resourceIds.has(installedType)) {
return resourceIds.get(installedType)!;
}
const resourcesFiles: string[] = globby.sync(`${NODE_MODULES_ROOT.replace(/\\/g, '/')}/@hint/${type}-*/package.json`);
const ids: string[] = resourcesFiles.reduce((list: string[], resourceFile: string) => {
const resource = requirePackage(path.dirname(resourceFile));
const packageName = JSON.parse(readFile(resourceFile)).name;
const resourceName = packageName.substr(packageName.lastIndexOf('/') + 1).replace(`${type}-`, '');
/* istanbul ignore else */
if (!hasMultipleResources(resource, type)) {
list.push(resourceName);
} else {
const hints = Object.entries(resource);
if (hints.length === 1 && resource[resourceName]) {
list.push(resourceName);
} else {
for (const [key] of hints) {
list.push(`${resourceName}/${key}`);
}
}
}
return list;
}, []);
resourceIds.set(installedType, ids);
return ids;
};
const loadListOfResources = (list: string[] | Object = [], type: ResourceType, configurations: string[] = []): { incompatible: string[]; missing: string[]; resources: any[] } => {
const missing: string[] = [];
const incompatible: string[] = [];
// In the case of hints, we get an object with hintname/priority, not an array
const items = Array.isArray(list) ?
list :
Object.keys(list);
const loadedResources = items.reduce((loaded, resourceId) => {
try {
const resource = loadResource(resourceId, type, configurations, true);
loaded.push(resource);
} catch (e) /* istanbul ignore next */ {
const name = isFullPackageName(resourceId, type) ? resourceId : `${type}-${resourceId}`;
const error = e as ResourceError;
if (error.status === ResourceErrorStatus.NotCompatible) {
incompatible.push(name);
} else if (error.status === ResourceErrorStatus.NotFound) {
missing.push(name);
} else {
throw error;
}
}
return loaded;
}, [] as any[]);
return {
incompatible,
missing,
resources: loadedResources
};
};
export const loadHint = (hintId: string, configurations?: string[]): IHintConstructor => {
return loadResource(hintId, ResourceType.hint, configurations);
};
export const loadConfiguration = (configurationId: string, configurations?: string[]) => {
return loadResource(configurationId, ResourceType.configuration, configurations);
};
/** Returns all the resources from a `HintConfig` */
export const loadResources = (config: Configuration): HintResources => {
// TODO: validate connector version is OK once all are extracted
let connector: IConnectorConstructor | null = null;
const connectorName = config.connector && config.connector.name || '';
try {
connector = loadResource(connectorName, ResourceType.connector, config.extends, true);
} catch (e) /* istanbul ignore next */ {
debug(e);
if ((e as ResourceError).status === ResourceErrorStatus.DependencyError) {
throw e;
}
}
const { incompatible: incompatibleHints, resources: hints, missing: missingHints } = loadListOfResources(config.hints, ResourceType.hint, config.extends);
const { incompatible: incompatibleParsers, resources: parsers, missing: missingParsers } = loadListOfResources(config.parsers, ResourceType.parser, config.extends);
const { incompatible: incompatibleFormatters, resources: formatters, missing: missingFormatters } = loadListOfResources(config.formatters, ResourceType.formatter, config.extends);
const missing = ([] as string[]).concat(missingHints, missingParsers, missingFormatters);
const incompatible = ([] as string[]).concat(incompatibleFormatters, incompatibleParsers, incompatibleHints);
if (!connector) {
missing.push(`${ResourceType.connector}-${connectorName || config.connector}`);
}
return {
connector,
formatters,
hints,
incompatible,
missing,
parsers
};
};
|
0065edba55a24a8643d7e9df408106c2eb04be8e
|
TypeScript
|
sundogrd/theworld
|
/packages/theworld-core/src/game/types/common.ts
| 2.671875
| 3
|
export enum EDirection {
WEST = 'west',
EAST = 'east',
NORTH = 'north',
SOUTH = 'south',
}
export enum ECreatureGender {
FEMALE = 'female',
MALE = 'male',
}
export type QueryType = {
is: {
[key: string]: any;
};
not: {
[key: string]: any;
};
};
|
a31d993ba566e4f86c6b61cc2fe375143e993891
|
TypeScript
|
airgap-it/airgap-coin-lib
|
/packages/substrate/src/v1/data/scale/type/SCALEHash.ts
| 2.71875
| 3
|
import { InvalidValueError } from '@airgap/coinlib-core/errors'
import { Domain } from '@airgap/coinlib-core/errors/coinlib-error'
import { isHex, stripHexPrefix } from '@airgap/coinlib-core/utils/hex'
import { SCALEDecodeResult } from '../SCALEDecoder'
import { SCALEEncodeConfig, SCALEType } from './SCALEType'
export class SCALEHash extends SCALEType {
public static empty(bitLength: number = 0): SCALEHash {
const byteLength = Math.ceil(bitLength / 8)
const u8a = new Uint8Array(byteLength)
u8a.fill(0)
return new SCALEHash(Buffer.from(u8a))
}
public static from(bytes: string | Buffer | Uint8Array): SCALEHash {
let buffer: Buffer
if (typeof bytes === 'string' && isHex(bytes)) {
buffer = Buffer.from(stripHexPrefix(bytes), 'hex')
} else if (!(typeof bytes === 'string')) {
buffer = Buffer.from(bytes)
} else {
throw new InvalidValueError(Domain.SUBSTRATE, 'SCALEHash#from: Unknown bytes type.')
}
return new SCALEHash(buffer)
}
public static decode(hex: string, bitLength: number): SCALEDecodeResult<SCALEHash> {
const _hex = stripHexPrefix(hex)
const nibbles = Math.ceil(bitLength / 4)
const hash = _hex.substr(0, nibbles)
return {
bytesDecoded: Math.ceil(nibbles / 2),
decoded: SCALEHash.from(hash)
}
}
public get isEmpty(): boolean {
return this.value.length === 0 || this.value.every((value) => value === 0)
}
private constructor(readonly value: Buffer) {
super()
}
public toString(encoding: BufferEncoding = 'hex'): string {
return this.value.toString(encoding)
}
protected _encode(config?: SCALEEncodeConfig): string {
return this.value.toString('hex')
}
}
|
0336334ae440a7ce7c2299b55ecde392e04c02f8
|
TypeScript
|
shekhar-shubhendu/squid-js
|
/src/utils/WebServiceConnectorProvider.ts
| 2.515625
| 3
|
import WebServiceConnector from "./WebServiceConnector"
export default class WebServiceConnectorProvider {
public static setConnector(connector: WebServiceConnector) {
WebServiceConnectorProvider.instance = connector
}
public static getConnector(): WebServiceConnector {
if (!WebServiceConnectorProvider.instance) {
WebServiceConnectorProvider.instance = new WebServiceConnector()
}
return WebServiceConnectorProvider.instance
}
private static instance: WebServiceConnector = null
}
|
e3260207499de828428133e4f4edd1af82011fec
|
TypeScript
|
rubensworks/rdf-test-suite.js
|
/test/testcase/TestCaseUnsupported-test.ts
| 2.578125
| 3
|
import {TestCaseUnsupported, TestCaseUnsupportedHandler} from "../../lib/testcase/TestCaseUnsupported";
describe('TestCaseUnsupportedHandler', () => {
const handler = new TestCaseUnsupportedHandler('someHandler');
describe('#resourceToTestCase', () => {
it('should produce TestCaseUnsupported', async () => {
const testCase = await handler.resourceToTestCase(null, <any> { a: 'b' });
expect(testCase).toBeInstanceOf(TestCaseUnsupported);
expect(testCase.type).toEqual('unsupported');
expect((<any> testCase).a).toEqual('b');
expect(testCase.testCaseName).toEqual('someHandler');
});
it('should produce TestCaseUnsupported that reject on test', async () => {
const testCase = await handler.resourceToTestCase(null, <any> { a: 'b' });
expect(testCase.test(null)).rejects.toBeTruthy();
});
});
});
|
fadf36b208427198b06ca60a831357eac7313e98
|
TypeScript
|
LaunchMenu/LaunchMenu
|
/packages/core/src/utils/searchExecuter/_types/ISearchPatternFilterConfig.ts
| 3.21875
| 3
|
import {IPatternMatch} from "./IPatternMatch";
/** The config for the search pattern filter */
export type ISearchPatternFilterConfig<I> = {
/**
* The callback for when an item is added
* @param item The item that was found
*/
onAdd: (item: I) => void;
/**
* The callback for when an item is removed
* @param item The item that was removed
*/
onRemove: (item: I) => void;
/**
* Retrieves the pattern match to be used. Can be used to make sure no duplicate patterns are found (E.G. patterns with deep but not reference equality).
* Defaults to a deep equality checker.
*/
getPatternMatch?: (
match: IPatternMatch,
currentMatches: IPatternMatch[]
) => IPatternMatch | undefined;
};
|
72883272018248944a9027c513437fb5e9241f86
|
TypeScript
|
Longwelwind/majority
|
/src/server/Player.ts
| 2.6875
| 3
|
import Game from "./Game";
import {ServerPacket} from "../commons/server-packets";
import * as WebSocket from "ws";
export default class Player {
static lastId: number = 0;
id: number;
name: string;
token: string;
game: Game | null = null;
clients: WebSocket[] = [];
constructor(id: number, nickname: string, token: string) {
this.id = id;
this.name = nickname;
this.token = token;
}
sendPacket(packet: ServerPacket) {
this.clients.forEach(c => {
if (c.readyState == WebSocket.OPEN) {
c.send(JSON.stringify(packet));
}
});
}
}
|
413f593b9edc94fdfd7d851b5f80b32adbc4b0a7
|
TypeScript
|
haniot/mhealth
|
/test/unit/models/sleep.duration.summary.model.spec.ts
| 2.734375
| 3
|
import { DefaultEntityMock } from '../../mocks/models/default.entity.mock'
import { assert } from 'chai'
import { SleepDurationSummary } from '../../../src/application/domain/model/sleep.duration.summary'
describe('MODELS: SleepDurationSummary', () => {
const sleepDurationSummaryJSON: any = DefaultEntityMock.SLEEP_DURATION_SUMMARY
describe('fromJSON()', () => {
context('when a json is passed', () => {
it('should return a SleepDurationSummary from a complete json', () => {
const result: SleepDurationSummary = new SleepDurationSummary().fromJSON(sleepDurationSummaryJSON)
assert.propertyVal(result, 'total', sleepDurationSummaryJSON.total)
})
it('should return an empty SleepDurationSummary from an empty json', () => {
const result: SleepDurationSummary = new SleepDurationSummary().fromJSON({})
assert.isEmpty(result)
})
})
context('when the parameter is undefined', () => {
it('should return an empty SleepDurationSummary from an undefined json', () => {
const result: SleepDurationSummary = new SleepDurationSummary().fromJSON(undefined)
assert.isEmpty(result)
})
})
context('when the json is a string', () => {
it('should return a SleepDurationSummary from a complete json', () => {
const result: SleepDurationSummary = new SleepDurationSummary().fromJSON(JSON.stringify(sleepDurationSummaryJSON))
assert.propertyVal(result, 'total', sleepDurationSummaryJSON.total)
})
it('should return an empty SleepDurationSummary from an empty string', () => {
const result: SleepDurationSummary = new SleepDurationSummary().fromJSON(JSON.stringify(''))
assert.isEmpty(result)
})
it('should return an empty SleepDurationSummary from an invalid string', () => {
const result: SleepDurationSummary = new SleepDurationSummary().fromJSON('d52215d412')
assert.isEmpty(result)
})
})
})
describe('toJSON()', () => {
context('when toJSON() is executed', () => {
it('should return a JSON from a complete SleepDurationSummary', () => {
const sleepDurationSummary: SleepDurationSummary = new SleepDurationSummary().fromJSON(sleepDurationSummaryJSON)
const result: any = sleepDurationSummary.toJSON()
assert.propertyVal(result, 'total', sleepDurationSummaryJSON.total)
})
it('should return a JSON with all attributes equal to undefined from an incomplete SleepDurationSummary', () => {
const result: any = new SleepDurationSummary().toJSON()
assert.isUndefined(result.total)
})
})
})
})
|
f6950a00f414b5fea3d5f2ded1e5d18072c5bfee
|
TypeScript
|
abdelrahman543873/productive-family
|
/src/discount/discount.factory.ts
| 2.609375
| 3
|
import { ObjectID } from 'mongodb';
import * as faker from 'faker';
import { Discount } from './models/discount.schema';
import { providerFactory } from '../provider/provider.factory';
import { DiscountRepo } from '../../test/discount/discount-test-repo';
interface DiscountType {
provider?: ObjectID;
code?: string;
amount?: number;
expiryDate?: Date;
isActive?: boolean;
}
export const buildDiscountParams = async (
obj: DiscountType = {},
): Promise<Discount> => {
return {
provider: obj.provider || (await providerFactory())._id,
code: obj.code || faker.random.word(),
amount: obj.amount || faker.datatype.number(),
expiryDate: obj.expiryDate || faker.date.recent(),
isActive: obj.isActive ?? true,
};
};
export const discountsFactory = async (
count = 10,
obj: DiscountType = {},
): Promise<Discount[]> => {
const discounts: Discount[] = [];
for (let i = 0; i < count; i++) {
discounts.push(await buildDiscountParams(obj));
}
return (await DiscountRepo()).addMany(discounts);
};
export const discountFactory = async (
obj: DiscountType = {},
): Promise<Discount> => {
const params: Discount = await buildDiscountParams(obj);
return (await DiscountRepo()).add(params);
};
|
21619b1a519b025ad1bd5189413b19c16006227c
|
TypeScript
|
rideshare-vinay/rideshare-frontend
|
/src/app/services/log.service.ts
| 3
| 3
|
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class LogService {
/**
* A function that logs a debug message
* @param message
*/
debug(message: string) {
let logEntry = this.createLogStatement('debug', message);
console.info(logEntry);
return logEntry;
}
/**
* A function that logs an error message
* @param message
*/
error(message: string) {
let logEntry = this.createLogStatement('error', message);
console.error(logEntry);
return logEntry;
}
/**
* A function that logs a warn message
* @param message
*/
warn(message: string) {
let logEntry = this.createLogStatement('warning', message);
console.warn(logEntry);
return logEntry;
}
/**
* A function that logs a message as an info
* @param message
*/
info(message: string) {
let logEntry = this.createLogStatement('info', message);
console.info(logEntry);
return logEntry;
}
/**
* This function creates the log statement
* @param level
* @param message
*/
createLogStatement(level, message) {
return "[" + level + "]" + " " + this.getCurrentDate() + " " + message;
}
/**
* This function get the current date.
*/
getCurrentDate() {
let date = new Date();
return "[" + date.toLocaleString() + "]";
}
/**
* A constructor
*/
constructor() { }
}
|
fd1530d374e30ede072d59d19955d2aa61d4f529
|
TypeScript
|
AsterAInpm/katrine
|
/src/meta-annotations.ts
| 2.875
| 3
|
import {
AccessByAuthData,
AccessByRoleData,
AccessRulesType,
AuthStatus,
HTTPRequestType,
KatrineActionInterface
} from './@types';
import KatrineAction from "./metadata/KatrineAction";
import projectMetadata from "./metadata/ProjectMetadata";
/**
* Marks handler(function) in controller as action
*
* @param route - Express compatible router
* @param method - POST/GET that will be bind
*/
export function action(
route: string,
method: HTTPRequestType = HTTPRequestType.GET
) {
return function (controller: any, actionMethod: string, descriptor: PropertyDescriptor) {
const action: KatrineActionInterface = new KatrineAction(
route,
actionMethod,
method,
controller
);
projectMetadata.storeAction(action);
};
}
export function controller(controllerClass: any) {
projectMetadata.addController(controllerClass.name, controllerClass);
}
export const accessByRole = (
roles: string | string[]
) => {
return function (controller: any, actionMethod: string, descriptor: PropertyDescriptor) {
const ruleData: AccessByRoleData = {
type: AccessRulesType.ByRole,
roles
};
projectMetadata.addAccessByRoleRule(ruleData, actionMethod, controller);
};
};
export const accessByAuth = (
auth: AuthStatus = AuthStatus.LOGGED_IN
) => {
return function (controller: any, actionMethod: string, descriptor: PropertyDescriptor) {
const ruleData: AccessByAuthData = {
type: AccessRulesType.ByAuth,
auth
};
projectMetadata.addAccessByRoleRule(ruleData, actionMethod, controller);
};
};
|
5c4a1a8843bdf9fdaf16ca366c1499cd81dfd94f
|
TypeScript
|
azmanabdlh/validasaur
|
/tests/rules/date_after.test.ts
| 2.953125
| 3
|
import type { Validity } from "../../src/types.ts";
import { dateAfter } from "../../src/rules/date_after.ts";
import { invalid } from "../../src/utils.ts";
import { assertInvalid, assertValid, fakeUtils } from "../utils.ts";
Deno.test("rules.dateAfter() type check", () => {
const date = new Date();
assertInvalid(
dateAfter(date)(5, fakeUtils) as Validity,
invalid("dateAfter:typeCheck", { value: 5, date }),
);
assertInvalid(
dateAfter(date)(null, fakeUtils) as Validity,
invalid("dateAfter:typeCheck", { value: null, date }),
);
assertInvalid(
dateAfter(date)(undefined, fakeUtils) as Validity,
invalid("dateAfter:typeCheck", { value: undefined, date }),
);
assertInvalid(
dateAfter(date)([], fakeUtils) as Validity,
invalid("dateAfter:typeCheck", { value: [], date }),
);
assertInvalid(
dateAfter(date)({}, fakeUtils) as Validity,
invalid("dateAfter:typeCheck", { value: {}, date }),
);
});
Deno.test("rules.dateAfter() length check", () => {
const date = new Date();
assertInvalid(
dateAfter(date)("20201002", fakeUtils) as Validity,
invalid("dateAfter:lengthCheck", { value: "20201002", date }),
);
});
Deno.test("rules.dateAfter() date check", () => {
const date = new Date("2020-01-02 10:20:30");
// same date
assertInvalid(
dateAfter(date)("2020-01-02", fakeUtils) as Validity,
invalid("dateAfter", { value: "2020-01-02", date }),
);
assertInvalid(
dateAfter(date)(new Date("2020-01-02"), fakeUtils) as Validity,
invalid("dateAfter", { value: new Date("2020-01-02"), date }),
);
// date before
assertInvalid(
dateAfter(date)("2020-01-01", fakeUtils) as Validity,
invalid("dateAfter", { value: "2020-01-01", date }),
);
assertInvalid(
dateAfter(date)(new Date("2020-01-01"), fakeUtils) as Validity,
invalid("dateAfter", { value: new Date("2020-01-01"), date }),
);
// date After
assertValid(dateAfter(date)("2020-01-03", fakeUtils) as Validity);
assertValid(dateAfter(date)(new Date("2020-01-03"), fakeUtils) as Validity);
});
|
ed6c875edf79480c39763d886ecf564585bc3a8c
|
TypeScript
|
tierratelematics/prettygoat-workflow
|
/scripts/ticks/TickScheduler.ts
| 2.640625
| 3
|
import {injectable, inject} from "inversify";
import {Subject, Observable} from "rxjs";
import Tick from "./Tick";
import {IDateRetriever, Event, IStreamFactory} from "prettygoat";
import * as moment from "moment";
export interface ITickScheduler extends IStreamFactory {
schedule(dueTime: number | Date, state?: string | object);
}
@injectable()
class TickScheduler implements ITickScheduler {
private subject = new Subject<Event>();
constructor(@inject("IDateRetriever") private dateRetriever: IDateRetriever) {
}
schedule(dueTime: number | Date, state?: string | object) {
let dueDate = dueTime instanceof Date ? dueTime : this.calculateDueDate(<number>dueTime);
this.subject.next({
type: "Tick",
payload: new Tick(dueDate, state),
timestamp: dueDate
});
}
from(): Observable<Event> {
return this.subject;
}
private calculateDueDate(dueTime: number): Date {
return moment(this.dateRetriever.getDate()).add(dueTime, "milliseconds").toDate();
}
}
export default TickScheduler
|
bcad77ed3987a8af292df0705aa734c486b8f0b3
|
TypeScript
|
nubiofs/flatgeobuf
|
/src/ts/geojson/geometry.ts
| 3.078125
| 3
|
import { flatbuffers } from 'flatbuffers'
import { GeometryType } from '../header_generated'
import { Feature } from '../feature_generated'
import { IParsedGeometry, flat, pairFlatCoordinates } from '../generic/geometry'
export interface IGeoJsonGeometry {
type: string
coordinates: number[] | number[][] | number[][][] | number[][][][]
}
export function buildGeometry(builder: flatbuffers.Builder, geometry: IGeoJsonGeometry) {
const { coords, ends, endss } = parseGeometry(geometry)
const coordsOffset = Feature.createCoordsVector(builder, coords)
let endsOffset: number = null
let endssOffset: number = null
if (ends)
endsOffset = Feature.createEndsVector(builder, ends)
if (endss)
endssOffset = Feature.createEndssVector(builder, endss)
return function() {
if (endsOffset)
Feature.addEnds(builder, endsOffset)
if (endssOffset)
Feature.addEndss(builder, endssOffset)
Feature.addCoords(builder, coordsOffset)
}
}
function parseGeometry(geometry: IGeoJsonGeometry) {
const cs = geometry.coordinates
let coords: number[] = null
let ends: number[] = null
let endss: number[] = null
switch (geometry.type) {
case 'Point': {
coords = cs as number[]
break
}
case 'MultiPoint':
case 'LineString': {
coords = flat(cs as number[][])
break
}
case 'MultiLineString': {
const css = cs as number[][][]
coords = flat(css)
if (css.length > 1)
ends = css.map(c => c.length * 2)
break
}
case 'Polygon': {
const css = cs as number[][][]
coords = flat(css)
if (css.length > 1)
ends = css.map(c => c.length * 2)
break
}
case 'MultiPolygon': {
const csss = cs as number[][][][]
coords = flat(csss)
if (csss.length > 1) {
endss = csss.map(c => c.length)
ends = flat(csss.map(cc => cc.map(c => c.length * 2)))
} else
if (csss[0].length > 1)
ends = csss[0].map(c => c.length * 2)
break
}
}
return {
coords,
ends,
endss
} as IParsedGeometry
}
function extractParts(coords: Float64Array, ends: Uint32Array) {
if (!ends)
return [pairFlatCoordinates(coords)]
let s = 0
let coordsSlices = Array.from(ends)
.map(e => coords.slice(s, s = s + e))
return coordsSlices
.map(cs => pairFlatCoordinates(cs))
}
function extractPartsParts(
coords: Float64Array,
ends: Uint32Array,
endss: Uint32Array) {
if (!endss)
return [extractParts(coords, ends)]
let s = 0
let coordsSlices = Array.from(ends)
.map(e => coords.slice(s, s = s + e))
s = 0
return Array.from(endss)
.map(e => coordsSlices.slice(s, s = s + e)
.map(cs => pairFlatCoordinates(cs)))
}
function toGeoJsonCoordinates(feature: Feature, type: GeometryType) {
const coords = feature.coordsArray()
switch (type) {
case GeometryType.Point:
return Array.from(coords)
case GeometryType.MultiPoint:
case GeometryType.LineString:
return pairFlatCoordinates(coords)
case GeometryType.MultiLineString:
return extractParts(coords, feature.endsArray())
case GeometryType.Polygon:
return extractParts(coords, feature.endsArray())
case GeometryType.MultiPolygon:
return extractPartsParts(coords,
feature.endsArray(),
feature.endssArray())
}
}
export function fromGeometry(feature: Feature, type: GeometryType) {
const coordinates = toGeoJsonCoordinates(feature, type)
return {
type: GeometryType[type],
coordinates,
} as IGeoJsonGeometry
}
|
47b5bd8afaa24947286c1ee46c8173ac1250ec0c
|
TypeScript
|
Rom1-J/grafibot
|
/test/Bot.test.ts
| 2.703125
| 3
|
import { Message } from 'discord.js'
import Bot from '../src/Bot'
import { expect, chai, fakeMessage } from './helpers'
import { ICommand, IFilter } from '../src/interfaces'
const generateCommand = function (name: string): ICommand {
let command = {
name: name,
description: name,
run (msg: Message, args: string[]): void {
return
}
}
chai.spy.on(command, 'run')
return command
}
const generateFilter = function (content: string): IFilter {
let filter = {
filter (message: Message) {
let triggered = message.content === content
if (triggered) message.channel.send('filtered !')
return triggered
}
}
chai.spy.on(filter, 'filter')
return filter
}
describe('Commands', function () {
let message = fakeMessage('!demo a1 a2')
let bot = new Bot(message.client)
let command = generateCommand('demo')
bot.addCommand(command)
it('should detect command', function () {
message.client.emit('message', message)
expect(command.run).to.be.called.with(message, ['a1', 'a2'])
})
})
describe('Filters', function () {
it('laisse passer les messages', function () {
let message = fakeMessage('c')
let filtera = generateFilter('a')
let filterb = generateFilter('b')
let bot = new Bot(message.client)
bot.addFilter(filtera)
bot.addFilter(filterb)
message.client.emit('message', message)
expect(message.channel.send).to.not.be.called()
})
it('filtre les messages', function () {
let message = fakeMessage('a')
let filtera = generateFilter('a')
let filterb = generateFilter('b')
let bot = new Bot(message.client)
bot.addFilter(filtera)
bot.addFilter(filterb)
message.client.emit('message', message)
expect(message.channel.send).to.be.called()
expect(filtera.filter).to.be.called()
expect(filterb.filter).to.not.be.called()
})
it('ne filtre pas les messages proventant ', function () {
let message = fakeMessage('a')
message.channel.type = 'dm'
let filtera = generateFilter('a')
let bot = new Bot(message.client).addFilter(filtera)
message.client.emit('message', message)
expect(message.channel.send).to.not.be.called()
expect(filtera.filter).to.not.be.called()
})
})
|
feef2de1b60463c31edfafb090c7c4045fc09fb0
|
TypeScript
|
GSA/sam-ui-elements
|
/src/ui-kit/experimental/aria/abstract-grid/abstract-grid.ts
| 2.765625
| 3
|
import { AbstractRow } from './abstract-row';
import { AbstractCell } from './abstract-cell';
import { EventDispatcher } from '../utils/events';
export type AbstractGridEvent = 'keydown' | 'click';
export interface AbstractGridConfig {
skipRows?: number;
useDefaultKeydownEvents?: boolean;
useDefaultClickEvents?: boolean;
disableFocus?: boolean;
}
export class AbstractGrid {
public focused: AbstractCell = undefined;
private _currentRow = 0;
private _currentCol = 0;
private _skipRows = 5;
private _node: Element = undefined;
private _observer: MutationObserver;
private _rows: AbstractRow[] = [];
private _dispatcher: EventDispatcher;
private _keydownListener = this._dispatchKeydown.bind(this);
private _clickListener = this._dispatchClick.bind(this);
private _onClickHandler = [];
private _config: AbstractGridConfig = {};
constructor (host, config?: AbstractGridConfig) {
if (config) {
this._config = config;
}
this._initEventDispatcher();
this._main(host);
this._initMutationObserver(host);
if (this._config) {
this._skipRows = this._config.skipRows || 5;
}
}
public onClick (callback: Function,
context: Object): void {
this._onClickHandler = [callback, context];
const [cb, ctx] = this._onClickHandler;
this._dispatcher.on('click', cb, ctx);
}
public onKeydown (callback: Function,
context: Object): void {
this._dispatcher.on('keydown', callback, context);
}
public getSelected (): AbstractCell {
return this._rows[this._currentRow]
.cells[this._currentCol];
}
public move (direction: string) {
switch (direction) {
case 'up':
this._currentRow =
this._moveUp(this._currentRow);
break;
case 'down':
this._currentRow =
this._moveDown(this._currentRow);
break;
case 'right':
this._currentCol =
this._moveRight(this._currentCol);
break;
case 'left':
this._currentCol =
this._moveLeft(this._currentCol);
break;
default:
break;
}
this._setFocus();
}
private _main (element) {
this._findGrid(element);
this._findRows(element);
this._clearGridEvents();
this._initGridEvents();
if (this._node) {
this._setInitialFocus();
}
}
private _initMutationObserver (element) {
const config: MutationObserverInit = {
attributes: false,
childList: true,
subtree: true,
};
const cb = (mutations) => {
this._rows = [];
this.focused = undefined;
this._main(element);
};
this._observer = new MutationObserver(cb.bind(this));
this._observer.observe(this._node, config);
}
private _initEventDispatcher () {
const keyEvents = ['keydown', 'click'];
this._dispatcher = new EventDispatcher(keyEvents);
}
private _initGridEvents () {
this._rows.forEach(
row => {
row.cells.forEach(
cell => {
cell.onClick(this._clickListener, this);
}
);
}
);
this._node.addEventListener(
'keydown',
this._keydownListener
);
if (this._config.useDefaultKeydownEvents !== false) {
this._dispatcher
.on('keydown', this._handleCellKeydown, this);
}
if (this._config.useDefaultClickEvents !== false) {
this._dispatcher
.on('click', this._handleCellClick, this);
}
const [cb, ctx] = this._onClickHandler;
if (cb) {
this._dispatcher
.on('click', cb, ctx);
}
}
private _clearGridEvents (): void {
this._rows.forEach(
row => {
row.cells.forEach(
cell => {
cell.disconnect('click', this._clickListener);
}
);
}
);
this._node.removeEventListener(
'keydown',
this._keydownListener
);
this._dispatcher
.disconnect('keydown', this._handleCellKeydown);
this._dispatcher
.disconnect('click', this._handleCellClick);
const [cb, ctx] = this._onClickHandler;
if (cb) {
this._dispatcher
.disconnect('click', cb);
}
}
private _dispatchClick (e) {
return this._dispatcher.dispatch('click', e);
}
private _dispatchKeydown (e) {
return this._dispatcher.dispatch('keydown', e);
}
private _handleCellKeydown (e): void {
const code = e.key;
switch (code) {
case 'ArrowDown':
return this.move('down');
case 'ArrowUp':
return this.move('up');
case 'ArrowLeft':
return this.move('left');
case 'ArrowRight':
return this.move('right');
default:
return;
}
}
private _handleCellClick (e): void {
this._setSelectedByElement((<Element> e));
this.focused = this.getSelected();
}
private _setInitialFocus () {
this._currentCol = 0;
this._currentRow = 0;
this.focused = this.getSelected();
if (this.focused && this._config.disableFocus !== true) {
this.focused.addToTabOrder();
}
}
private _findGrid (element: Element) {
const role = element.getAttribute('role');
/**
* querySelector doesn't include the element it is
* called on in the query, so we have to check if the
* element is the grid first before querying for it
*/
if (role === 'grid') {
this._node = element;
} else {
const gridEl = element.querySelector('[role="grid"]');
if (gridEl) {
this._node = gridEl;
} else {
throw new TypeError(
'AbstractGrid must contain element with role grid'
);
}
}
}
private _findRows (element: Element): void {
const rows = element.querySelectorAll('[role="row"]');
for (let i = 0; i < rows.length; i++) {
const rowObj = new AbstractRow(rows[i]);
this._rows.push(rowObj);
}
}
private _setSelectedByElement (target: Element): void {
this._rows.forEach(
(row, i) => {
row.cells.forEach(
(cell, j) => {
if (cell.node === target) {
this._currentRow = i;
this._currentCol = j;
}
}
);
}
);
}
private _setFocus () {
if (this.focused) {
this.focused.removeFromTabOrder();
}
this.focused = this.getSelected();
if (this._config.disableFocus !== true) {
this.focused.addToTabOrder();
this.focused.focus();
}
}
private _moveUp (row: number): number {
const prev = row - 1;
if (prev > 0) {
return prev;
} else {
return 0;
}
}
private _moveDown (row: number): number {
const length = this._rows.length - 1;
const next = row + 1;
if (next > length) {
return length;
} else {
return next;
}
}
private _moveLeft (col: number): number {
const prev = col - 1;
if (prev >= 0) {
return prev;
} else {
return 0;
}
}
private _moveRight (col: number): number {
const length =
this._rows[this._currentRow].cells.length;
const next = col + 1;
if (next < length - 1) {
return next;
} else {
return length - 1;
}
}
}
|
9de2f440e440fba5b2b510c1e8cf23fad0ea088a
|
TypeScript
|
2008-310272/led-2
|
/main.ts
| 2.640625
| 3
|
input.onButtonPressed(Button.A, function () {
basic.clearScreen()
led.setBrightness(0)
})
input.onButtonPressed(Button.AB, function () {
for (let Y = 0; Y <= 4; Y++) {
for (let X = 0; X <= 4; X++) {
led.plot(X, Y)
basic.pause(100)
}
}
for (let Y = 0; Y <= 4; Y++) {
for (let X = 0; X <= 4; X++) {
led.plotBrightness(Y, 4 - X, 255)
basic.pause(100)
}
}
})
input.onButtonPressed(Button.B, function () {
basic.clearScreen()
led.setBrightness(255)
})
basic.forever(function () {
for (let Y = 0; Y <= 4; Y++) {
for (let X = 0; X <= 4; X++) {
led.plotBrightness(4 - X, Y, 30)
basic.pause(100)
}
for (let X = 0; X <= 4; X++) {
led.plot(Y, 4 - X)
basic.pause(100)
}
}
for (let Y = 0; Y <= 4; Y++) {
for (let X = 0; X <= 4; X++) {
led.plotBrightness(X, 4 - Y, 30)
basic.pause(100)
}
for (let X = 0; X <= 4; X++) {
led.plot(4 - Y, X)
basic.pause(100)
}
}
for (let Y = 0; Y <= 4; Y++) {
for (let X = 0; X <= 4; X++) {
led.plotBrightness(4 - Y, X, 30)
basic.pause(100)
}
for (let X = 0; X <= 4; X++) {
led.plot(X, 4 - Y)
basic.pause(100)
}
}
for (let Y = 0; Y <= 4; Y++) {
for (let X = 0; X <= 4; X++) {
led.plotBrightness(Y, 4 - X, 30)
basic.pause(100)
}
for (let X = 0; X <= 4; X++) {
led.plot(4 - X, Y)
basic.pause(100)
}
}
})
|
d7df546fcbb0138cc3d2a5eba0b59e87bb2fafab
|
TypeScript
|
pioner92/todoList
|
/src/api/rest/login.ts
| 2.5625
| 3
|
import {createEffect} from 'effector'
import {makeRequest, statusType} from '../make-request'
import {urls} from '../urls'
import {LocalStorage} from '../../lib/local-storage'
type dataType = {
login:string
password:string
}
type responseType = {
status: statusType,
message:{
token?:string
}
}
export const login = createEffect(async ({login, password}:dataType):Promise<responseType| undefined> =>{
try {
const form = new FormData()
form.append('username', login)
form.append('password', password)
return makeRequest(urls.login, 'POST', form)
} catch (e) {
console.log('Login error ', e)
}
})
login.done.watch(({result})=> {
if (result) {
if (result.message?.token) {
LocalStorage.set('token', result.message.token)
}
}
})
|
e85d002b82bebec6634d12a9b23c090f0ef3120a
|
TypeScript
|
diltai/marker
|
/projects/dilta/web-transport/src/lib/transport.service.ts
| 2.78125
| 3
|
// tslint:disable-next-line: max-line-length
import { ApiFormat, ApiResponse, API_STATUS_CODE, API_STATUS_RESPONSE, BaseResponse, EntityNames, Log, modelActionFormat, ModelOperations } from '@dilta/platform-shared';
import { from, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { v4 } from 'uuid';
/**
* Response Error Interface for the application
*
*/
interface ResponseError extends BaseResponse {
error: string;
}
export abstract class AbstractTransportService {
constructor() {}
/**
* Execute a model Action with the argument parameters
*
*/
modelAction<ResponseData>(
model: EntityNames,
operation: ModelOperations,
...args: any[]
): Observable<ResponseData> {
return this.execute.apply(this, [
modelActionFormat(model, operation),
...args
]);
}
/**
* maps the action to request context sent and returns the
* Observble of responseType throwing error if error exist
*
*/
execute<ResponseData>(action: string, ...args: any[]) {
const id: string = v4();
return from(this.bus<ResponseData>({ action, data: args, id })).pipe(
map(res => {
if (res.error) {
throw new Error(res.error);
}
return res.data;
})
);
}
/**
* sends the JSON query to the main process event
*
*/
abstract bus<ResponseType>(ctx: ApiFormat): Promise<ApiResponse<ResponseType>>;
/**
* Custom error mapped for request if allowed extecution time eluded.
*
*/
timeoutError<T>(ctx: ApiFormat): ResponseError {
return {
reqId: ctx.id,
status: API_STATUS_RESPONSE.Failure,
time: Date.now(),
error: `Api Response Time Out Eludeded`,
code: API_STATUS_CODE.Failure
};
}
/**
* sends the logs across the transport and displays in render console also.
*
*/
log(method: logMethod, log: Log, ...others: any[]) {
}
}
export type logMethod = 'debug' | 'info' | 'error' | 'warn' | 'trace';
|
a25f55a1cd15ebb9a6f17c503fba1d6d014ede29
|
TypeScript
|
baight/baight-ng
|
/response.ts
| 2.625
| 3
|
import { Attribute } from "@angular/core";
export class Response {
error: any;
code: number;
desc: string;
data: any | Object;
static successCode = 200;
isSuccess() : boolean {
if (this.error) {
return false;
}
else if (this.code == Response.successCode){
return true;
}
else {
return false;
}
}
public get list(): any[] {
if (this.data){
return this.data.list
}
else {
return []
}
}
public get totalCount(): number {
if (this.data) {
return this.data.totalElements
}
else {
return 0;
}
}
public get totalPage(): number {
return this.totalCount/10
}
message() : string {
if (this.desc) {
return this.desc
}
else if (this.error) {
if (this.error.status == 0) {
return "发生未知错误"
}
else {
return this.error.message;
}
}
else {
return "发生未知错误"
}
}
hasMore() : boolean {
if (this.data) {
let hasMore = this.data["hasMore"];
return hasMore ? hasMore : false;
}
return false;
}
}
|
44cb1731e7e5e4d46b24ea9783e8272154070519
|
TypeScript
|
sherazahmedse/typescript
|
/features/annotations/objects.ts
| 3.203125
| 3
|
const profile = {
name: 'alex',
age: 20,
coords: {
lat: 100,
long: 122
},
setAge (age : number) : void {
this.age = age;
}
}
// const age = profile.age;
const { age } : {age : number} = profile;
// const coords : {
// latitude : number ;
// longitude : number
// } = {
// latitude: 100,
// longitude: 122
// }
const {
coords : { lat , long }
} : {coords : {lat : number , long : number} } = profile;
|
b5b3f7c9e6109819c2c93d66b2ac0290a09bf850
|
TypeScript
|
hinterlist/cryptomarket
|
/src/reducers/assets.ts
| 2.953125
| 3
|
const initialState = {
error: null,
loading: false,
assets: [],
};
export default (state = initialState, action) => {
switch (action.type) {
// Reset to initia state and turn on loading status
case 'FETCH_ASSETS': {
return { ...initialState, loading: true };
}
// Fetching was successfull, save assets
case 'FETCH_ASSETS_SUCCESS': {
return { ...state, loading: false, data: action.data };
}
// Fetching has failed, save error
case 'FETCH_ASSETS_ERROR': {
return { ...state, loading: false, error: action.error };
}
default: {
return state;
}
}
};
|
65b30ba2272ce2ad80991395edf69fa0e32588af
|
TypeScript
|
sproutt/eussya-eussya-view
|
/client/src/test/util/style.size.test.ts
| 2.703125
| 3
|
import {
Size,
SizeSeparator,
FontSize,
ElementSizeByHeight,
ElementDistanceEachOthers
} from "utils/style/size";
describe("SizeSeparator test", () => {
it("입력이 LARGE 일때 FontSize는 LARGE", () => {
expect(SizeSeparator.asFont(Size.LARGE)).toEqual(FontSize.LARGE);
});
it("입력이 Null 일때 FontSize는 MEDIUM", () => {
expect(SizeSeparator.asFont(null)).toEqual(FontSize.MEDIUM);
});
it("입력이 SMALL 일때 ElementSizeByHeight는 SMALL", () => {
expect(SizeSeparator.asElementHeight(Size.SMALL)).toEqual(
ElementSizeByHeight.SMALL
);
});
it("입력이 Null 일때 ElementSizeByHeight는 MEDIUM", () => {
expect(SizeSeparator.asElementHeight(null)).toEqual(
ElementSizeByHeight.MEDIUM
);
});
it("입력이 MEDIUM 일때 ElementDistanceEachOthers는 MEDIUM", () => {
expect(SizeSeparator.asDistanceEachOthers(Size.SMALL)).toEqual(
ElementDistanceEachOthers.SMALL
);
});
it("입력이 Null 일때 ElementDistanceEachOthers는 MEDIUM", () => {
expect(SizeSeparator.asDistanceEachOthers(null)).toEqual(
ElementDistanceEachOthers.MEDIUM
);
});
});
|
9d95157a11df835352959db7f10cd29403d65aa2
|
TypeScript
|
kyiimn/actapublisher
|
/src/js/pageobject/color/colormgr.ts
| 2.875
| 3
|
import ActaColor from './color';
class ActaColorManager {
private static _instance: ActaColorManager;
static getInstance() {
if (!ActaColorManager._instance) ActaColorManager._instance = new ActaColorManager();
return ActaColorManager._instance;
}
static get in() {
return ActaColorManager.getInstance();
}
private _list: ActaColor[];
private constructor() {
this._list = [];
}
add(data: {
id: number, name: string, colorType: string, code: string, rgbCode: string
}) {
this._list.push(new ActaColor(data));
}
get(name: number | string) {
if (typeof name === 'number') {
for (const color of this._list) {
if (color.id === name) return color;
}
} else {
for (const color of this._list) {
if (color.name === name) return color;
}
}
return false;
}
getRGBCode(name: number | string) {
let retColor;
if (typeof name === 'number') {
for (const color of this._list) {
if (color.id !== name) continue;
retColor = color;
break;
}
} else {
for (const color of this._list) {
if (color.name !== name) continue;
retColor = color;
break;
}
}
return retColor ? retColor.rgbCode : '#000000';
}
clear() {
for (let i = 0; i < this._list.length; i++) {
delete this._list[i];
}
this._list = [];
}
list(colorType?: string) {
const retList: ActaColor[] = [];
for (const color of this._list) {
if (colorType && color.colorType !== colorType) continue;
retList.push(color);
}
return retList;
}
length(colorType?: string) {
return this.list(colorType).length;
}
};
export default ActaColorManager.in;
|
66ec549158bc20838854b36c3ff55fd11d5540d5
|
TypeScript
|
lderrickable/daffodil
|
/libs/checkout/src/shipping/reducers/shipping.reducer.spec.ts
| 2.609375
| 3
|
import { TestBed, async } from '@angular/core/testing';
import { DaffAddress } from '@daffodil/core';
import { DaffAddressFactory } from '@daffodil/core/testing';
import { UpdateShippingAddress, SelectShippingOption } from '../actions/shipping.actions';
import { initialState, reducer, getShippingAddress, getSelectedShippingOptionIndex, isShippingAddressValid, State } from '../reducers/shipping.reducer';
describe('Shipping | Shipping Reducer', () => {
let addressFactory: DaffAddressFactory;
let shippingAddress: DaffAddress;
let selectedShippingOptionId: string;
beforeEach(async(() => {
TestBed.configureTestingModule({});
addressFactory = TestBed.get(DaffAddressFactory);
shippingAddress = addressFactory.create();
selectedShippingOptionId = '0';
}));
describe('when an unknown action is triggered', () => {
it('should return the current state', () => {
const action = {} as any;
const result = reducer(initialState, action);
expect(result).toBe(initialState);
});
});
describe('when UpdateShippingAddress action is triggered', () => {
let result;
beforeEach(() => {
const updateShippingAddressAction = new UpdateShippingAddress(shippingAddress);
result = reducer(initialState, updateShippingAddressAction);
});
it('sets shippingAddress from action.payload', () => {
expect(result.shippingAddress).toEqual(shippingAddress)
});
});
describe('when SelectShippingOption action is triggered', () => {
let result;
beforeEach(() => {
const selectShippingOptionAction = new SelectShippingOption(selectedShippingOptionId);
result = reducer(initialState, selectShippingOptionAction);
});
it('sets selectedShippingOptionId from action.payload', () => {
expect(result.selectedShippingOptionId).toEqual(selectedShippingOptionId)
});
});
describe('getShippingAddress', () => {
it('returns shippingAddress state', () => {
expect(getShippingAddress(initialState)).toEqual(initialState.shippingAddress);
});
});
describe('getSelectedShippingOptionIndex', () => {
it('returns selectedShippingOptionId state', () => {
expect(getSelectedShippingOptionIndex(initialState)).toEqual(initialState.selectedShippingOptionId);
});
});
describe('isShippingAddressValid', () => {
describe('when shippingAddress is defined', () => {
let result: State;
beforeEach(() => {
const updateShippingAddressAction = new UpdateShippingAddress(shippingAddress);
result = reducer(initialState, updateShippingAddressAction);
});
it('should return true', () => {
expect(isShippingAddressValid(result.shippingAddress)).toBeTruthy();
});
});
describe('when shippingAddress is null', () => {
let result: State;
beforeEach(() => {
const updateShippingAddressAction = new UpdateShippingAddress(null);
result = reducer(initialState, updateShippingAddressAction);
});
it('should return false', () => {
expect(isShippingAddressValid(result.shippingAddress)).toBeFalsy();
});
});
});
});
|
64829fa174a38e1d1e7e6c76188acb367d427a6b
|
TypeScript
|
KyleMyers001/Todo
|
/src/app/classes/Cookie.ts
| 2.9375
| 3
|
class Cookie {
name: string;
data: string;
expirationDays: number;
constructor(name, data, expirationDays) {
this.name = name;
this.data = data;
this.expirationDays = expirationDays;
this.setCookie();
}
static getCookie(name): string {
name = `${name}=`;
const decodedCookie = decodeURIComponent(document.cookie);
const ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return '';
}
setCookie(): void {
const date = new Date();
date.setTime(date.getTime() + (this.expirationDays*24*60*60*1000));
const expires = 'expires='+ date.toUTCString();
document.cookie = this.name + '=' + this.data + ';' + expires + ';path=/';
}
}
export default Cookie;
|
db31e194028eac8f1f374fec7c32106d8bf1c9d0
|
TypeScript
|
wilsonshakespeare/next-js-template
|
/core/server/router/RouteModule.ts
| 2.609375
| 3
|
import { Express } from 'express';
import { RouteModel, RouteAsyncModel } from './index';
export class RouteModule {
public static addRoute(server: Express, route: RouteAsyncModel | RouteModel) {
switch (route.method) {
case 'PUT':
server.put(route.path, route.renderFunction);
break;
case 'GET':
server.get(route.path, route.renderFunction);
break;
case 'POST':
server.post(route.path, route.renderFunction);
break;
case 'DELETE':
server.delete(route.path, route.renderFunction);
break;
}
}
private routeMap: RouteModel[] = [];
private routeAsyncMap: RouteAsyncModel[] = [];
public addRoute(routeModel: RouteModel) {
this.routeMap.push(routeModel);
}
public addRouteAsync(routeModel: RouteAsyncModel) {
this.routeAsyncMap.push(routeModel);
}
public setupServer(server: Express) {
this.routeMap.forEach(route => RouteModule.addRoute(server, route));
this.routeAsyncMap.forEach(route => RouteModule.addRoute(server, route));
}
}
export default RouteModule;
|
399b1087a9b41fb816c2c4c39de654707861a7e4
|
TypeScript
|
brizjose/JBCodingDojo
|
/MEAN/Angular/udemy/courseProject/src/app/shared/ingredient.model.ts
| 3.609375
| 4
|
export class Ingredient {
constructor(public name: string, public amount: number) {}
}
// the above code does exactly what we usually do with OOP, but it is so common that Typescript provides a short way of doing it, as shown.
// export class Ingredient {
// public name: string;
// public amount: number;
// constructor(name: string, amount: number) {
// this.name = name;
// this.amount = amount;
// }
// }
|
a843bedc2ecd8b4efe64331429a4fdc949ec018d
|
TypeScript
|
jazzmanweb/observables
|
/src/app/common/single-state.interface.ts
| 2.5625
| 3
|
export interface SingleStateInterface<T> {
index?: number | string;
value?: T;
}
|
6db73ad8d235cc7fa74fc8cdd26ce679aa4c1bf3
|
TypeScript
|
clenemt/bontouch-assignment
|
/src/utils/generic.ts
| 3.203125
| 3
|
// Capitalize first letter of string passed
export const capitalize = (str: string) => {
if (typeof str !== 'string') return '';
return `${str.charAt(0).toUpperCase()}${str.slice(1)}`;
};
|
625f05c0d9a920c44ad9e643734228bbd087bb59
|
TypeScript
|
asurance/webgl-demos
|
/src/GLHanlderManager.ts
| 2.6875
| 3
|
import { ProceduralTexture } from './ProceduralTexture/ProceduralTexture'
import { ClearColor } from './ClearColor/ClearColor'
import { Mask } from './Mask/Mask'
import { Model } from './Model/Model'
import { RenderTexture } from './RenderTexture/RenderTexture'
import type { GLHandler } from './GLHandler'
export class GLHandlerManager {
private handlers: GLHandler[]
private titles: HTMLButtonElement[]
private gl: WebGLRenderingContext
private curIndex = -1
constructor(titleContainer: HTMLDivElement, private canvas: HTMLCanvasElement) {
const gl = canvas.getContext('webgl', { stencil: true })
if (gl) {
this.gl = gl
} else {
throw new Error('无法获取到webgl上下文')
}
this.handlers = [
new ClearColor(),
new ProceduralTexture(),
new Mask(),
new Model(),
new RenderTexture(),
]
this.titles = this.handlers.map((h, i) => {
const title = document.createElement('button')
if (h.test && !h.test(gl)) {
title.disabled = true
} else {
if (h.load) {
title.disabled = true
h.load().then(() => {
title.disabled = false
})
} else {
title.disabled = false
}
}
title.innerText = h.title
title.onclick = (): void => {
this.setActiveIndex(i)
}
titleContainer.appendChild(title)
return title
})
this.setActiveIndex(0)
}
private setActiveIndex(index: number): void {
if (this.curIndex !== index) {
if (this.curIndex >= 0) {
this.handlers[this.curIndex].leave()
this.titles[this.curIndex].removeAttribute('select')
this.canvas.onmousemove = null
this.canvas.onmousedown = null
this.canvas.onmouseup = null
this.canvas.onmouseover = null
this.canvas.onmouseout = null
}
this.titles[index].setAttribute('select', '')
const handler = this.handlers[index]
handler.onmousemove && (this.canvas.onmousemove = (ev): void => {
handler.onmousemove!(ev.offsetX, ev.offsetY)
})
handler.onmousedown && (this.canvas.onmousedown = (ev): void => {
handler.onmousedown!(ev.offsetX, ev.offsetY)
})
handler.onmouseup && (this.canvas.onmouseup = (ev): void => {
handler.onmouseup!(ev.offsetX, ev.offsetY)
})
handler.onmouseover && (this.canvas.onmouseover = (ev): void => {
handler.onmouseover!(ev.offsetX, ev.offsetY)
})
handler.onmouseout && (this.canvas.onmouseout = (ev): void => {
handler.onmouseout!(ev.offsetX, ev.offsetY)
})
handler.enter(this.gl)
this.curIndex = index
}
}
}
|
fb7da1408fd0e3e4cea04459589c972b7417376b
|
TypeScript
|
farhat97/TaskManagementApp
|
/src/app/shared/task.model.ts
| 2.890625
| 3
|
// TODO: for the moment, I am using this as opposed to the ITask interface in order to
// follow this approach: https://florimond.dev/blog/articles/2018/09/consuming-apis-in-angular-the-model-adapter-pattern/
import { Injectable } from '@angular/core';
import { Adapter } from './adapter';
export class Task {
taskId: number;
taskType: string;
contactPerson: string;
dueDate: string; // TODO: change to date type
userId: number;
taskName: string;
taskDescription: string;
constructor() { }
}
@Injectable({
providedIn: 'root'
})
export class TaskAdapter implements Adapter<Task> {
adapt(item: any): Task {
let newTask = new Task();
newTask.taskId = item.taskId;
newTask.taskType = item.taskType;
newTask.contactPerson = item.contactPerson;
newTask.dueDate = item.dueDate;
newTask.userId = item.userId;
newTask.taskName = item.taskName;
newTask.taskDescription = item.taskDescription;
return newTask;
}
}
|
b204d84b77d25d4c67d5ce8edd4fcd52c0f939e6
|
TypeScript
|
johannes-z/office-fabric
|
/packages/utilities/src/assertNever.ts
| 3.015625
| 3
|
/**
* AssertNever is a utility function that can be used for exhaustiveness checks in switch statements.
*
* @public
*/
export function assertNever (x: never): never {
throw new Error('Unexpected object: ' + x)
}
|
babdd6fde6be5b18a4559208d658718206ec25a1
|
TypeScript
|
MayurNegi/Rocket.Chat.Fuselage
|
/packages/message-parser/src/utils.ts
| 2.921875
| 3
|
import {
BigEmoji,
Code,
Color,
Heading,
Markup,
Paragraph,
Types,
Task,
} from './definitions';
const generate =
<Type extends keyof Types>(type: Type) =>
(value: Types[Type]['value']): Types[Type] =>
({ type, value } as any);
export const paragraph = generate('PARAGRAPH');
export const bold = generate('BOLD');
export const color = (r: number, g: number, b: number, a = 255): Color => ({
type: 'COLOR',
value: { r, g, b, a },
});
export const heading = (
value: Heading['value'],
level: Heading['level'] = 1
): Heading => ({
type: 'HEADING',
level,
value,
});
export const code = (
value: Code['value'],
language?: Code['language']
): Code => ({
type: 'CODE',
language: language || 'none',
value,
});
export const bigEmoji = (value: BigEmoji['value']): BigEmoji => ({
type: 'BIG_EMOJI',
value,
});
export const task = (value: Task['value'], status: boolean): Task => ({
type: 'TASK',
status,
value,
});
export const inlineCode = generate('INLINE_CODE');
export const tasks = generate('TASKS');
export const italic = generate('ITALIC');
export const plain = generate('PLAIN_TEXT');
export const strike = generate('STRIKE');
export const codeLine = generate('CODE_LINE');
export const link = (() => {
const fn = generate('LINK');
return (src: string, label?: Markup) =>
fn({ src: plain(src), label: label || plain(src) });
})();
export const quote = generate('QUOTE');
export const mentionChannel = (() => {
const fn = generate('MENTION_CHANNEL');
return (value: string) => fn(plain(value));
})();
export const orderedList = generate('ORDERED_LIST');
export const unorderedList = generate('UNORDERED_LIST');
export const listItem = generate('LIST_ITEM');
export const list = generate('ORDERED_LIST');
export const mentionUser = (() => {
const fn = generate('MENTION_USER');
return (value: string) => fn(plain(value));
})();
export const emoji = (() => {
const fn = generate('EMOJI');
return (value: string) => fn(plain(value));
})();
export const reducePlainTexts = (
values: Paragraph['value']
): Paragraph['value'] =>
values.reduce((result, item, index) => {
if (index > 0) {
const previous = result[result.length - 1];
if (item.type === 'PLAIN_TEXT' && item.type === previous.type) {
previous.value += item.value;
return result;
}
}
return [...result, item];
}, [] as Paragraph['value']);
|
68affe9dd59c092ad698c7c678af9e013a59320a
|
TypeScript
|
goulartdev/rentalx
|
/src/modules/cars/usecases/create-specification/create-specification.ts
| 2.515625
| 3
|
import { inject, injectable } from "tsyringe";
import SpecificationsRepository, {
CreateSpecificationParams,
} from "@modules/cars/repositories/port/specifications.repository";
import AppError from "@shared/errors/app-error";
@injectable()
class CreateSpecification {
constructor(
@inject("SpecificationsRepository")
private specificationRepository: SpecificationsRepository
) {
//
}
async execute({ name, description }: CreateSpecificationParams): Promise<void> {
const existingSpecification = await this.specificationRepository.findByName(name);
if (existingSpecification) {
throw new AppError(`A specification whit the name ${name} already exists`, 400);
}
await this.specificationRepository.create({ name, description });
}
}
export default CreateSpecification;
|
7f0147aaa9088217dddf5b14d6e5e53c7433bdd8
|
TypeScript
|
shaunluttin/design-patterns
|
/LaTeX/src/good-vs-bad/reason-to-change-02.ts
| 3.328125
| 3
|
interface GeometricRectangle {
calculateArea(): number;
}
interface Rectangle {
draw();
}
function computationalApp(rectangle: GeometricRectangle) {
rectangle.calculateArea();
}
function graphicalApp(rectangle: Rectangle) {
rectangle.draw();
}
|
c92670b20194e7ce6ab329d614857daab225d4db
|
TypeScript
|
ofoer/baike-zhanzhan-web
|
/constant/MOCK.ts
| 2.578125
| 3
|
interface MOCKTYPE {
id: string,
short_name: string,
full_name: string,
bn: string,
desc: string,
coordinates: {
lng: number,
lat: number
},
open: Array<{start: number, end: number}>
openText: Array<string>,
addressText: string
}
const MOCK:Array<MOCKTYPE> = [
{
id: 'sasa',
short_name: "核聚变",
full_name: "大型电子游戏嘉年华",
bn: "http://www.bjeiecc.com/userfiles/image/20210319/20210319165152_81795.png",
desc: '多年来,核聚变电子游戏嘉年华一直以“Tour”为目标,希望通过“旅行”般的松弛,在游戏中给人与人传递快乐。本次核聚变广州站设置了数个游戏挑战环节,并且每一个环节都经过严格的设计与测试,既保证拥有极高的可玩性,又保证关卡的难度。对于热爱游戏热爱挑战的你是不可多得的良机哦!',
coordinates: {
lng: 116.261833,
lat: 39.907132
},
openText: ["05/21 - 05/30"],
open: [
{
start: 1621094400000,
end: 1621267200000
}
],
addressText: "上海市 上海市 徐汇区 光大会展中心"
}
]
export default MOCK
|
7f57a63d18b329fa0b59eefa5cef411a6bb9187f
|
TypeScript
|
ISyangk/transport-report
|
/src/utils/appFn.ts
| 2.625
| 3
|
import { applicationList } from "@/models/global";
/**
* 验证当前操作是否符合用户权限
* return Boolen
*/
export function checkApplication(applicationList: applicationList, code: string) {
// 判断是否包含传入的项目权限
if (applicationList && applicationList.length) {
return applicationList.some((item) => {
return item.applicationCode === code;
})
}
return false
}
|
84e21797a272ca6d1c7e62a568972fbc88a8d3f2
|
TypeScript
|
rossdowthwaite/weather-forecast-app
|
/src/app/store/forecast/forecast.action.ts
| 2.59375
| 3
|
import { Action } from '@ngrx/store';
import { Forecast } from '../../interfaces/forecast';
export const ADD_FORECAST = '[forecast] ADD_FORECAST';
export const ADD_FORECAST_SUCCESS = '[forecast] ADD_FORECAST_SUCCESS';
export const ADD_FORECAST_FAIL = '[forecast] ADD_FORECAST_FAIL';
export const UPDATE_FORECAST = '[forecast] UPDATE_FORECAST';
export const UPDATE_FORECAST_SUCCESS = '[forecast] UPDATE_FORECAST_SUCCESS';
export const UPDATE_FORECAST_FAIL = '[forecast] UPDATE_FORECAST_FAIL';
export const REMOVE_FORECAST = '[forecast] REMOVE_FORECAST';
export const REMOVE_FORECAST_SUCCESS = '[forecast] REMOVE_FORECAST_SUCCESS';
export const REMOVE_FORECAST_FAIL = '[forecast] REMOVE_FORECAST_FAIL';
export const ADD_TIMES = '[forecast] ADD_TIME';
export const ADD_TIMES_DONE = '[forecast] ADD_TIMES_SUCCESS';
export const CLEAR_TIMES = '[forecast] CLEAR_TIMES';
export const OUT_OF_DATE = '[forecast] OUT_OF_DATE';
export const UP_TO_DATE = '[forecast] UP_TO_DATE';
/**
* Add Forecast actions
*/
export class AddForecastAction implements Action {
readonly type = ADD_FORECAST;
constructor(public payload: string) {
console.log('ADD_FORECAST');
}
}
export class AddForecastSuccessAction implements Action {
readonly type = ADD_FORECAST_SUCCESS;
constructor(public payload: Forecast) {
console.log('ADD_FORECAST_SUCCESS');
}
}
export class AddForecastFailAction implements Action {
readonly type = ADD_FORECAST_FAIL;
constructor() {
console.log('ADD_FORECAST_FAIL');
}
}
export class UpdateForecastAction implements Action {
readonly type = UPDATE_FORECAST;
constructor(public payload: string) {
console.log('UPDATE_FORECAST');
}
}
export class UpdateForecastSuccessAction implements Action {
readonly type = UPDATE_FORECAST_SUCCESS;
constructor(public payload: Forecast) {
console.log('UPDATE_FORECAST_SUCCESS');
}
}
export class UpdateForecastFailAction implements Action {
readonly type = UPDATE_FORECAST_FAIL;
constructor() {
console.log('UPDATE_FORECAST_FAIL');
}
}
/**
* Remove Forecast actions
*/
export class RemoveForecastAction implements Action {
readonly type = REMOVE_FORECAST;
constructor(public payload: Forecast) {
console.log('REMOVE_FORECAST');
}
}
/**
* Add Times actions
*/
export class AddTimesAction implements Action {
readonly type = ADD_TIMES;
constructor() {
console.log('ADD_TIMES');
}
}
export class AddTimesDoneAction implements Action {
readonly type = ADD_TIMES_DONE;
constructor() {
console.log('ADD_TIMES_DONE');
}
}
export class ClearTimesAction implements Action {
readonly type = CLEAR_TIMES;
constructor() {
console.log('CLEAR_TIMES');
}
}
/**
* Up to date actions
*/
export class OutOfDateAction implements Action {
readonly type = OUT_OF_DATE;
constructor() {
console.log('OUT_OF_DATE');
}
}
export class UpToDateAction implements Action {
readonly type = UP_TO_DATE;
constructor() {
console.log('UP_TO_DATE');
}
}
export type Actions
= AddForecastAction
| AddForecastSuccessAction
| AddForecastFailAction
| UpdateForecastAction
| UpdateForecastSuccessAction
| UpdateForecastFailAction
| RemoveForecastAction
| AddTimesAction
| AddTimesDoneAction
| ClearTimesAction
| OutOfDateAction
| UpToDateAction;
|
aeacaad2dff0893409ae478d831edddaa2c251bb
|
TypeScript
|
nakajimakotaro/dungeon
|
/src/gameMap.ts
| 2.71875
| 3
|
import "pixi.js";
import { Game } from "./game";
import { Character } from "./character";
import { Cell } from "./cell";
import { TurnManager } from "./turnManager";
export class GameMap {
turnManager: TurnManager;
charaList:Map<Character, Character> = new Map();
removeQueqeList:Character[] = [];
get gridSizeX(){
return this.grid.length;
}
get gridSizeY(){
return this.grid[0].length;
}
get cellSize(){
return this.grid[0][0].size;
}
constructor(public game:Game, public grid:Cell[][]) {
this.turnManager = new TurnManager();
}
draw(render: PIXI.Graphics) {
for (let yGrid of this.grid) {
for (let cell of yGrid) {
cell.draw(render);
}
}
this.charaList.forEach(e=>e.draw(render));
}
update(){
for(let chara of this.removeQueqeList){
this.charaList.delete(chara);
}
this.removeQueqeList = [];
this.charaList.forEach(e=>e.update());
this.turnManager.update();
}
isGridRange(x:number, y:number){
return x >= 0 && y >= 0 && x < this.grid.length && y < this.grid[0].length;
}
addChara(chara:Character){
this.charaList.set(chara, chara);
}
removeChara(chara:Character){
this.removeQueqeList.push(chara);
}
}
|
a23f730e989331d66b6faa1a566cd68297ee858a
|
TypeScript
|
PenpenLi/gameModel
|
/assets/Script/common/BaseComponent.ts
| 2.59375
| 3
|
// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
import utils from '../utils/utils';
const { ccclass, property } = cc._decorator;
/**
* @class BaseComponent
* @extends cc.Component
* @classdesc 基类
*/
@ccclass
export default class BaseComponent extends cc.Component {
/**
* @property {Array | null} _eventList -- 监听对象列表
* @memberof BaseComponent
*/
_eventList = null;
/**
* @property {Object} _create -- 对象创建列表
* @memberof BaseComponent
*/
_create = {};
// LIFE-CYCLE CALLBACKS:
onLoad() {
this.loadResource();
}
start() {}
/**
*
* @function loadResource
* @description 加载资源
* @date: 2021-01-29 18:01:00
*/
loadResource() {
// cc.log(this.node.getComponent(cc.Sprite))
// this._registerAllBtnClickEvent(this.node);
this._initWidget();
}
/**
*
* @function _initWidget
* @description 初始化组件操作 -- 子类继承重写
* @date: 2021-01-29 18:01:55
*/
_initWidget() {}
/**
*
* @function _registerAllBtnClickEvent
* @description 注册指定节点下所有按钮点击事件
*
* @param {cc.Node} node -- 指定节点对象
* @date: 2021-01-29 18:03:32
*/
_registerAllBtnClickEvent(node?: cc.Node) {
if (!node) {
return;
}
let btn = node.getComponent(cc.Button);
if (btn) {
btn.node.on('click', this._onBtnClickCallback, this);
}
let arrayRootChidden = node.children;
for (let i = 0; i < arrayRootChidden.length; i++) {
this._registerAllBtnClickEvent(arrayRootChidden[i]);
}
}
/**
*
* @function _onBtnClickCallback
* @description 按钮点击事件回调
* @param {*} sender -- 点击事件
* @return {}
* @date: 2021-01-29 18:04:41
*/
_onBtnClickCallback(sender) {
this._onJsonBtnClickEvent(sender);
}
/**
*
* @function _onJsonBtnClickEvent
* @description 子控件重写此方法获取回调
* @param {*} sender -- 点击事件
* @date: 2021-01-29 18:05:37
*/
_onJsonBtnClickEvent(sender) {}
/**
*
* @function registerAllCustomEvents
* @description 注册所有自定义事件
* @param {array} array -- 注册事件列表
* @date: 2021-01-29 18:06:41
*/
registerAllCustomEvents(array: any[]) {
this._eventList = this._eventList || [];
// return;
for (let i = 0; i < array.length; i++) {
if (!array[i][0] || !array[i][1] || typeof array[i][1] !== 'function') {
continue;
}
if (typeof array[i][0] !== 'string') {
array[i][0] = String(array[i][0]);
}
this._eventList.push(array[i]);
this.node.on(array[i][0], array[i][1], this);
}
}
/**
*
* @function unregisterAllCustomEvents
* @description 注销所有自定义事件
* @date: 2021-01-29 18:12:54
*/
unregisterAllCustomEvents() {
if (!this._eventList) {
return;
}
this._eventList.forEach((element) => {
this.node.off(element[0], element[1], this);
});
this._eventList = null;
}
/**
*
* @function dispatchEvent
* @description 触发监听事件
* @param {string} name -- 注册监听事件的名字
* @param {any} data -- 传送的数据
* @param {boolean} isBubbling -- 是否向上冒泡
* @return {}
* @date: 2021-01-29 18:14:27
*
* @example
*```
*this.dispatchEvent('show-layer')
*```
*/
dispatchEvent(name: string, data?: any, isBubbling = true) {
const event = new cc.Event.EventCustom(name, isBubbling);
if (data) {
event.setUserData(data);
}
this.node.dispatchEvent(event);
}
//
/**
*
* @function show
* @description 显示(隐藏)节点
* @param {cc.Node} node -- 节点
* @param {boolean} isShow -- 显示/消失
* @param {Function} callBack -- 回调函数
* @param {boolean} isFree -- 是否释放资源
* @return {}
* @date: 2021-01-29 18:16:30
*
* @example
*```
*
*```
*/
show(
node: cc.Node,
isShow: boolean = true,
callBack?: Function,
isFree: boolean = false
) {
if (!node) {
return;
}
isShow ? utils.node.fade_in(node) : utils.node.fade_out(node, 0.3, isFree);
if (callBack) callBack();
}
/**
*
* @function inistantiantPrefab
* @description 创建节点
* @param {cc.Node} node -- 添加节点对象
* @param {string} path -- 创建对象的路径
* @param {number} zIndex -- 层级
* @param {Function} callback -- 回调函数
* @memberof BaseComponent
* @date: 2021-01-29 18:18:13
*/
inistantiantPrefab(
node: cc.Node,
path: string,
zIndex: number = 0,
callback?: Function
) {
// console.log(this);
if (this._create[path]) {
cc.log('防止重复创建');
return;
}
this._create[path] = true;
utils.res.load(path, (prefab) => {
if (prefab) {
const com = cc.instantiate(prefab);
node.addChild(com, zIndex);
this.show(com, true);
this._create[path] = null;
callback && callback(com);
}
});
}
onDisable() {}
onDestroy() {
this.unregisterAllCustomEvents();
}
update(dt) {}
}
|
a535a3f80604e4e2f51fac6e66d2648a093e0c61
|
TypeScript
|
srukshan98/SocialShare
|
/api/src/functions/hashing.ts
| 3.359375
| 3
|
import md5 from 'md5';
export function hash(rawPassword, options: any = {}) {
/**
* salt is optional, if not provided it will be set to current timestamp
*/
const salt = options.salt ? options.salt : new Date().getTime();
/**
* rounds is optional, if not provided it will be set to 10
*/
const rounds = options.rounds ? options.rounds : 10;
let hashed = md5(rawPassword + salt);
for (let i = 0; i <= rounds; i++) {
hashed = md5(hashed);
}
return `${salt}$${rounds}$${hashed}`;
}
/**
*
*
* @param {string} rawPassword - the raw password
* @param { string } hashedPassword - the hashed password
* @returns
*/
export function compare(rawPassword, hashedPassword) {
try {
const [salt, rounds] = hashedPassword.split('$');
const hashedRawPassword = this.hash(rawPassword, { salt, rounds });
return hashedPassword === hashedRawPassword;
} catch (error) {
throw Error(error.message);
}
}
|
66e4d1a88e0dd11aa579c97352f7aab7939e8615
|
TypeScript
|
borisenki/SpaceShooterGame
|
/assets/Game/Enemy/Enemy.ts
| 2.734375
| 3
|
import { GameEvents } from "../GameEvents";
const { ccclass, property } = cc._decorator;
@ccclass
export default class Enemy extends cc.Component {
@property
speed: number = 300;
_direction: cc.Vec2 = null;
set direction(value: cc.Vec2) {
this._direction = value;
this.node.angle = Math.atan2(this._direction.y, this._direction.x) * (180 / Math.PI) - 90
}
get direction() {
return this._direction;
}
onCollisionEnter(other) {
let node: cc.Node = other.node;
if (node.name === 'Bullet') {
this.node.emit(GameEvents.ENEMY_DESTROYED, { enemy: this, needAnimation: true });
} else if (node.name === 'Borders') {
this.node.emit(GameEvents.ENEMY_DESTROYED, { enemy: this });
}
}
update(dt) {
this.node.y += this.speed * dt * this.direction.y;
this.node.x += this.speed * dt * this.direction.x;
}
}
|
0c4929863ceda689a53e56d4ad0f62f866215b85
|
TypeScript
|
epiclabs-io/hyperjump
|
/backend/Protocol.ts
| 2.828125
| 3
|
export interface IFunctionDefinition {
args: string[];
body: string;
}
export const ROOT_FUNCTION_GET_TYPE = 1;
export const ROOT_FUNCTION_GET_OBJECT = 2;
export enum RefType {
VALUE, // type is passed by value
REFVALUE, //type is passed by reference, alongside a snapshot of properties
REFONLY // type is passed by reference without properties
}
export interface ISerializationInfo {
serialize: (obj: any) => any;
deserialize: (obj: any) => any;
serializerDef?: IFunctionDefinition;
deserializerDef?: IFunctionDefinition;
}
export type IPropertyInfo = { [propertyName: string]: string };
export type ISerializeMetadata = IPropertyInfo;
export interface Type extends Function {
serializeMetadata?: ISerializeMetadata;
typeMetadata?: ITypeMetadata;
}
export interface ITypeInfo {
name: string,
methods: { [methodName: string]: number };
properties: IPropertyInfo;
clientMethods: { [methodName: string]: IFunctionDefinition };
serializationInfo?: ISerializationInfo;
referenceType: RefType;
}
export type IPropertyMetadata = string;
export interface ITypeMetadata {
name?: string;
referenceType?: RefType;
methods?: string[];
clientMethods?: { [methodName: string]: Function };
properties?: { [propertyName: string]: IPropertyMetadata };
serialize?: (obj: any) => any;
deserialize?: (obj: any) => any;
}
export interface IByRef {
_construct?: ITypeInfo,
_byRef: number
}
export interface ICommand {
command: string,
debugInfo?: string
}
export interface IRoot {
getType(typeName: string): Promise<ITypeInfo>;
pingObjects(obj: any[]): Promise<void>;
getObject(nameOrId: string | number): Promise<any>;
listen(obj: any, eventName: string): Promise<void>;
unlisten(obj: any, eventName: string): Promise<void>;
}
export interface IInvokeCommand extends ICommand {
functionId: number,
callId: number,
thisArg: any,
args: any[]
}
export interface IInvokeResultCommand extends ICommand {
callId: number,
result: any,
status: number,
message?: string
}
export interface IEventFiredCommand extends ICommand {
sourceObjectId: any,
eventName: string,
args: any[]
}
export interface IBinaryDataHeaderCommand extends ICommand {
id: number,
length: number
}
export var DateTypeInfo: ITypeInfo = {
name: "Date",
methods: null,
clientMethods: null,
properties: {},
referenceType: RefType.VALUE,
serializationInfo: {
serialize: (obj: any): any => {
return { time: (obj as Date).getTime() };
},
deserialize: (obj: any): any => {
return new Date(obj.time);
},
serializerDef: null,
deserializerDef: null
}
}
export var MapTypeInfo: ITypeInfo = {
name: "Map",
methods: null,
clientMethods: null,
properties: {},
referenceType: RefType.VALUE,
serializationInfo: {
serialize: (obj: any): any => {
let m = {};
let map = obj as Map<string | number, any>;
map.forEach((value, key) => {
m[key] = value;
});
return m;
},
deserialize: (obj: any): any => {
let map = new Map<any, any>();
Object.keys(obj).forEach(key => {
map.set(key, obj[key]);
});
return map;
},
serializerDef: null,
deserializerDef: null
}
}
|
f28d85af9e1e52bac0530787b9923229613e6df2
|
TypeScript
|
OntimizeWeb/ontimize-web-ngx-playground
|
/src/app/main/inputs/02.date/input-date.component.ts
| 2.609375
| 3
|
import { Component, ViewEncapsulation } from '@angular/core';
import moment, { Moment } from 'moment';
const DATE_HTML_DATA = `
<o-form editable-detail="no" show-header="no" layout-direction="column">
<o-date-input attr="date" label="Date" [data]="getValue()"></o-date-input>
<o-date-input attr="date2" label="Date" [data]="getValue()" read-only="no" format="LL" required="yes"
min="01/01/1980" max="01/01/2020" text-input-enabled="no"></o-date-input>
<o-date-input attr="date3" label="Date" enabled="no" [data]="getValue()"></o-date-input>
</o-form>
`;
const DATE_HTML_DATA_TYPES = `
<o-form editable-detail="no" show-header="no" layout-direction="column">
<o-date-input value-type="timestamp" attr="valueTypeInput" label="Date" [data]="getValue('timestamp')"
read-only="no" required="yes"></o-date-input>
<o-date-input value-type="string" attr="valueTypeInput2" label="Date" [data]="getValue('string')"
read-only="no" required="yes"></o-date-input>
<o-date-input value-type="date" attr="valueTypeInput3" label="Date" [data]="getValue('date')" read-only="no"
required="yes"></o-date-input>
<o-date-input value-type="iso-8601" attr="valueTypeInput4" label="Date" [data]="getValue('ISO-8601')"
read-only="no" required="yes"></o-date-input>
</o-form>
`;
const DATE_HTML_MIN_MAX = `
<o-form editable-detail="no" show-header="no" layout-direction="column">
<o-date-input value-type="timestamp" attr="minMaxInput" label="Date" [data]="getValue('timestamp')"
read-only="no" required="yes" [min]="getMinValue('timestamp')" [max]="getMaxValue('timestamp')"></o-date-input>
<o-date-input value-type="string" attr="minMaxInput2" label="Date" [data]="getValue('string')"
read-only="no" required="yes" [min]="getMinValue('string')" [max]="getMaxValue('string')"></o-date-input>
<o-date-input value-type="date" attr="minMaxInput3" label="Date" [data]="getValue('date')" read-only="no"
required="yes" [min]="getMinValue('date')" [max]="getMaxValue('date')"></o-date-input>
<o-date-input value-type="iso-8601" attr="minMaxInput4" label="Date" [data]="getValue('ISO-8601')"
read-only="no" required="yes" [min]="getMinValue('ISO-8601')" [max]="getMaxValue('ISO-8601')"></o-date-input>
</o-form>
`;
const DATE_TS_DATA = `
@Component({
selector: 'input-date',
templateUrl: 'input-date.component.html'
})
export class InputDateComponent {
private strDateValue = '05/30/2018'
private dateValue: Moment;
constructor() {
this.dateValue = moment(this.strDateValue, 'MM/DD/YYYY')
this.minDateValue = moment(this.strMinDateValue, 'MM/DD/YYYY')
this.maxDateValue = moment(this.strMaxDateValue, 'MM/DD/YYYY')
}
public getValue(type: string = 'timestamp'): any {
let result: any;
switch (type) {
case 'string':
result = this.strDateValue;
break;
case 'date':
result = this.dateValue.toDate();
break;
case 'ISO-8601':
result = this.dateValue.toISOString();
break;
case 'timestamp':
result = this.dateValue.valueOf();
break;
default:
break;
}
return result;
}
}
`;
const DATE_TS_DATA_MIN_MAX = `
@Component({
selector: 'input-date',
templateUrl: 'input-date.component.html'
})
export class InputDateComponent {
private strDateValue = '05/30/2018'
private strMinDateValue = '05/28/2018'
private strMaxDateValue = '05/31/2018'
private dateValue: Moment;
private minDateValue: Moment;
private maxDateValue: Moment;
constructor() {
this.dateValue = moment(this.strDateValue, 'MM/DD/YYYY')
this.minDateValue = moment(this.strMinDateValue, 'MM/DD/YYYY')
this.maxDateValue = moment(this.strMaxDateValue, 'MM/DD/YYYY')
}
public getValue(type: string = 'timestamp'): any {
let result: any;
switch (type) {
case 'string':
result = this.strDateValue;
break;
case 'date':
result = this.dateValue.toDate();
break;
case 'ISO-8601':
result = this.dateValue.toISOString();
break;
case 'timestamp':
result = this.dateValue.valueOf();
break;
default:
break;
}
return result;
}
public getMinValue(type: string = 'timestamp'): any {
let result: any;
switch (type) {
case 'string':
result = this.strMinDateValue;
break;
case 'date':
result = this.minDateValue.toDate();
break;
case 'ISO-8601':
result = this.minDateValue.toISOString();
break;
case 'timestamp':
result = this.minDateValue.valueOf();
break;
default:
break;
}
return result;
}
public getMaxValue(type: string = 'timestamp'): any {
let result: any;
switch (type) {
case 'string':
result = this.strMaxDateValue;
break;
case 'date':
result = this.maxDateValue.toDate();
break;
case 'ISO-8601':
result = this.maxDateValue.toISOString();
break;
case 'timestamp':
result = this.maxDateValue.valueOf();
break;
default:
break;
}
return result;
}
}
`;
const DATE_HTML_CUSTOM_CLASS = `
<o-form editable-detail="no" show-header="no" layout-direction="column">
<o-date-input attr="customDateClass" label="Date" read-only="no" required="yes" [date-class]="customDateClass">
</o-date-input>
</o-form>
`;
const DATE_TS_CUSTOM_CLASS = `
import { Component, ViewEncapsulation } from '@angular/core';
import { Moment } from 'moment';
@Component({
selector: 'input-date',
templateUrl: 'input-date.component.html'
})
export class InputDateComponent {
customDateClass = (m: Moment) => {
const date = m.date();
// Highlight the 1st of each month.
return (date === 1) ? 'example-custom-date-class' : undefined;
}
}
`;
const DATE_SCSS_CUSTOM_CLASS = `
.example-custom-date-class {
background: orange;
border-radius: 100%;
}
`;
@Component({
selector: 'input-date',
templateUrl: 'input-date.component.html',
styleUrls: ['input-date.component.scss'],
encapsulation: ViewEncapsulation.None,
})
export class InputDateComponent {
public files = {
html: {
data: DATE_HTML_DATA
},
scss: {
data: undefined
},
typescript: {
data: DATE_TS_DATA
}
};
public valueTypeFiles = {
html: {
data: DATE_HTML_DATA_TYPES
},
scss: {
data: undefined
},
typescript: {
data: DATE_TS_DATA
}
};
public valueTypeFilesMinMax = {
html: {
data: DATE_HTML_MIN_MAX
},
scss: {
data: undefined
},
typescript: {
data: DATE_TS_DATA_MIN_MAX
}
};
public customDateClassFiles = {
html: {
data: DATE_HTML_CUSTOM_CLASS
},
scss: {
data: DATE_SCSS_CUSTOM_CLASS
},
typescript: {
data: DATE_TS_CUSTOM_CLASS
}
}
private strDateValue = '05/30/2018'
private strMinDateValue = '05/28/2018'
private strMaxDateValue = '05/31/2018'
private dateValue: Moment;
private minDateValue: Moment;
private maxDateValue: Moment;
constructor() {
this.dateValue = moment(this.strDateValue, 'MM/DD/YYYY')
this.minDateValue = moment(this.strMinDateValue, 'MM/DD/YYYY')
this.maxDateValue = moment(this.strMaxDateValue, 'MM/DD/YYYY')
}
public getValue(type: string = 'timestamp'): any {
let result: any;
switch (type) {
case 'string':
result = this.strDateValue;
break;
case 'date':
result = this.dateValue.toDate();
break;
case 'ISO-8601':
result = this.dateValue.toISOString();
break;
case 'timestamp':
result = this.dateValue.valueOf();
break;
default:
break;
}
return result;
}
public getMinValue(type: string = 'timestamp'): any {
let result: any;
switch (type) {
case 'string':
result = this.strMinDateValue;
break;
case 'date':
result = this.minDateValue.toDate();
break;
case 'ISO-8601':
result = this.minDateValue.toISOString();
break;
case 'timestamp':
result = this.minDateValue.valueOf();
break;
default:
break;
}
return result;
}
public getMaxValue(type: string = 'timestamp'): any {
let result: any;
switch (type) {
case 'string':
result = this.strMaxDateValue;
break;
case 'date':
result = this.maxDateValue.toDate();
break;
case 'ISO-8601':
result = this.maxDateValue.toISOString();
break;
case 'timestamp':
result = this.maxDateValue.valueOf();
break;
default:
break;
}
return result;
}
customDateClass = (m: Moment) => {
const date = m.date();
// Highlight the 1st of each month.
return (date === 1) ? 'example-custom-date-class' : undefined;
}
}
|
967e2b3afa40e6f7c4d8ee8a73d221035f54556f
|
TypeScript
|
tajpouria/GOF-design-pattenrs
|
/SOLID_Principles/liskov_subsections_principle/Rect.ts
| 3.40625
| 3
|
namespace react2 {
class Shape {
private shouldSyncHeightAndWidth = false;
constructor(private _width: number, private _height: number) {
if (_height === _width) this.shouldSyncHeightAndWidth = true;
}
get width(): number {
return this._width;
}
set width(value: number) {
this._width = value;
if (this.shouldSyncHeightAndWidth) {
this._height = value;
}
}
get height(): number {
return this._height;
}
set height(value: number) {
this._height = value;
if (this.shouldSyncHeightAndWidth) {
this._width = value;
}
}
get toStr(): string {
return `Width: ${this._width}, Height: ${this._height}`;
}
}
class RectAngle extends Shape {}
class Square extends Shape {}
function areaCalculator(rect: RectAngle): number {
return rect.height * rect.width;
}
const rect = new RectAngle(10, 5);
rect.height = 10;
rect.width = 5;
const sq = new RectAngle(2, 2);
sq.width = 10;
/*
LSP::
if Square is instance of RectAngel then you should be able to use :
ReactAngle whenever you used Square
*/
console.info(rect.toStr, "--->", areaCalculator(rect));
console.info(sq.toStr, "--->", areaCalculator(sq));
}
|
b975b6ad600d9ed80aa4063c54b7f928f06169ff
|
TypeScript
|
869288142/micro-code
|
/src/type-util/Push.ts
| 3.046875
| 3
|
type Push<T extends any[], V> = [...T, V]// 你的实现代码
// 测试用例
type Arr0 = Push<[], 1> // [1]
type Arr1 = Push<[1, 2, 3], 4> // [1, 2, 3, 4]
|
308184e06fcc9800cce4717e406cab3f7684a859
|
TypeScript
|
hayes/beemo
|
/packages/driver-eslint/tests/ESLintDriver.test.ts
| 2.625
| 3
|
import fs from 'fs';
import DriverContext from '../../core/src/contexts/DriverContext';
import ESLintDriver from '../src/ESLintDriver';
import { createDriverContext, createTestTool } from '../../../tests/helpers';
describe('ESLintDriver', () => {
let driver: ESLintDriver;
let context: DriverContext;
let spy: jest.SpyInstance;
beforeEach(() => {
driver = new ESLintDriver();
driver.tool = createTestTool();
driver.bootstrap();
context = createDriverContext(driver);
spy = jest.spyOn(fs, 'writeFileSync').mockImplementation(() => true);
});
afterEach(() => {
spy.mockRestore();
});
it('sets options from constructor', () => {
driver = new ESLintDriver({
args: ['--foo', '--bar=1'],
dependencies: ['babel'],
env: { DEV: 'true' },
});
expect(driver.options).toEqual({
args: ['--foo', '--bar=1'],
dependencies: ['babel'],
env: { DEV: 'true' },
strategy: 'native',
});
});
it('sets correct metadata', () => {
expect(driver.metadata).toEqual(
expect.objectContaining({
bin: 'eslint',
configName: '.eslintrc.js',
configOption: '--config',
dependencies: [],
description: 'Lint files with ESLint',
filterOptions: true,
helpOption: '--help',
title: 'ESLint',
useConfigOption: false,
}),
);
});
describe('mergeConfig()', () => {
it('merges using eslint engine', () => {
expect(
driver.mergeConfig(
{
env: {
node: true,
},
rules: {
foo: 'error',
},
},
{
rules: {
foo: ['error', 'always'],
},
},
),
).toEqual({
env: {
node: true,
},
rules: {
foo: ['error', 'always'],
},
});
});
});
describe('handleCreateIgnoreFile()', () => {
it('does nothing if no ignore field', () => {
const config = { parser: 'babel' };
driver.handleCreateIgnoreFile(context, '/some/path/.eslintrc.js', config);
expect(config).toEqual({ parser: 'babel' });
});
it('errors if not an array', () => {
expect(() => {
driver.handleCreateIgnoreFile(context, '/some/path/.eslintrc.js', {
// @ts-ignore
ignore: 'foo',
});
}).toThrowErrorMatchingSnapshot();
});
it('creates ignore file and updates references', () => {
const config = {
parser: 'babel',
ignore: ['foo', 'bar', 'baz'],
};
driver.handleCreateIgnoreFile(context, '/some/path/.eslintrc.js', config);
expect(spy).toHaveBeenCalledWith('/some/path/.eslintignore', 'foo\nbar\nbaz');
expect(context.configPaths).toEqual([{ driver: 'eslint', path: '/some/path/.eslintignore' }]);
expect(config).toEqual({ parser: 'babel' });
});
});
});
|
a809c1ca3568ec6b6447c94544421eeafa436204
|
TypeScript
|
hakudev/nitro-emu
|
/src/app/messages/outgoing/user/inventory/badge/UserBadgesComposerUtilities.ts
| 2.59375
| 3
|
import { UserBadge } from '../../../../../../core';
export class UserBadgesComposerUtilities
{
public static composeCurrentBadges(badges: UserBadge[]): any[]
{
let totalBadges = 0;
const data: any[] = [];
if(badges)
{
for(let badge of badges)
{
if(!badge) continue;
data.push(badge.slot, badge.code);
totalBadges++;
}
}
return [ totalBadges, ...data ];
}
}
|
4c8125e389942b2b60dcf317ea7e13b1e4b2121a
|
TypeScript
|
leeanngrapes/task-app-angular
|
/src/app/services/ui.service.ts
| 2.578125
| 3
|
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UiService {
//define
private showAddTask: boolean = false;
//define subject
private Subject = new Subject<any>();
constructor() { }
//Service: call first one when the button is clicked
// second one is called wherever we want to change something
//function to toggle the value
toggleAddTask(): void {
this.showAddTask = !this.showAddTask;
//pass in the new value
this.Subject.next(this.showAddTask);
}
//fire off when we toggle
onToggle(): Observable<any> {
return this.Subject.asObservable();
}
}
|
fe5c9f2ebf8bd1e3359ba9953a6615bde4699520
|
TypeScript
|
ydubinskyi/my-wallet
|
/apps/api/src/app/account/account.service.ts
| 2.515625
| 3
|
import {
Injectable,
Inject,
BadRequestException,
NotFoundException,
} from '@nestjs/common';
import * as Knex from 'knex';
import { TABLES } from '../db/constants';
import { Account } from './entities/account.entity';
import { CreateAccountDto } from './dto/create-account.dto';
import { UpdateAccountDto } from './dto/update-account.dto';
@Injectable()
export class AccountService {
constructor(@Inject('KnexConnection') private readonly connection: Knex) {}
private get table() {
return this.connection.table<Account>(TABLES.ACCOUNT);
}
async create(user_id: number, createAccountDto: CreateAccountDto) {
try {
const {
name,
type,
start_amount,
description = '',
accent_color = '#000000',
user_currency_id,
} = createAccountDto;
return await this.table.insert({
name,
type,
start_amount,
description,
balance: start_amount,
accent_color,
user_currency_id,
user_id,
});
} catch (error) {
throw new BadRequestException(error);
}
}
async findAll(user_id: number) {
return await this.table.select('*').where({ user_id });
}
async findOne(user_id: number, id: number) {
try {
const item = await this.table.select('*').where({ id, user_id }).first();
if (!item) {
throw new NotFoundException();
}
return item;
} catch (error) {
throw new BadRequestException(error);
}
}
async update(
user_id: number,
id: number,
updateAccountDto: UpdateAccountDto
) {
try {
const item = await this.table.where({ id, user_id }).first();
if (!item) {
throw new NotFoundException();
}
const updatedAccount = {
...updateAccountDto,
balance:
updateAccountDto.start_amount === item.start_amount
? item.balance
: item.balance - item.start_amount + updateAccountDto.start_amount,
};
await this.table.where({ id, user_id }).update(updatedAccount);
return this.table.where({ id, user_id }).select('*').first();
} catch (error) {
throw new BadRequestException(error);
}
}
async remove(user_id: number, id: number) {
try {
const item = await this.table.where({ id, user_id }).first();
if (!item) {
throw new NotFoundException();
}
return this.table.where({ id, user_id }).del();
} catch (error) {
throw new BadRequestException(error);
}
}
}
|
007f75c24e5ec831173ac214316311d0524be6d7
|
TypeScript
|
Houfeng/noka
|
/packages/noka/src/IoCLoader/Inject.ts
| 2.921875
| 3
|
import { IInjectInfo } from "./IInjectInfo";
import { IInjectOptions } from "./IInjectOptions";
import { IOC_PROP_INJECT } from "./constants";
/**
* 注入一个类成员,通过名称在容器中查找类型并实例化后注入
* @param name 名称
*/
export function Inject(name?: string | symbol, options: IInjectOptions = {}) {
return (target: any, member: string | symbol) => {
if (!name) name = member;
const injectInfo: IInjectInfo = { name, member, options };
const injectList: IInjectInfo[] =
Reflect.getMetadata(IOC_PROP_INJECT, target) || [];
injectList.push(injectInfo);
Reflect.metadata(IOC_PROP_INJECT, injectList)(target);
};
}
/**
* 获取属性注入信息
* @param target 类型
*/
export function getPropInjectInfos(target: any) {
const list = Reflect.getMetadata(IOC_PROP_INJECT, target) || [];
return list as IInjectInfo[];
}
|
e4313b425071cd74e05b6e5cb66eb865f8a53391
|
TypeScript
|
HannahWWD/drag_and_drop
|
/src/utility/validation.ts
| 3.5625
| 4
|
// interface for validation
export interface ValidateObj {
value: string | number;
required?: boolean;
minLength?: number;
maxLength?: number;
min?: number;
max?: number;
}
export function validate(validateInput: ValidateObj) {
let isValid = true;
if (validateInput.required) {
isValid = isValid && validateInput.value.toString().trim().length !== 0;
}
if (
validateInput.minLength != null &&
typeof validateInput.value === "string"
) {
// if need to be very secured, set validateInput.minLength != null
// to avoid validateInput.minLength is set to 0 (false)
// use != instead of !== is to make undefined value counts as null as well
isValid = isValid && validateInput.value.length >= validateInput.minLength;
}
if (
validateInput.maxLength != null &&
typeof validateInput.value === "string"
) {
isValid = isValid && validateInput.value.length <= validateInput.maxLength;
}
if (validateInput.min != null && typeof validateInput.value === "number") {
isValid = isValid && validateInput.value >= validateInput.min;
}
if (validateInput.max != null && typeof validateInput.value === "number") {
isValid = isValid && validateInput.value <= validateInput.max;
}
return isValid;
}
|
086d2aad48184f20a0cf79223f0c5407c9cb9f86
|
TypeScript
|
LaughingThroll/react-calendar
|
/src/utils/date/getCountDays/index.ts
| 2.796875
| 3
|
const getCountDays = (firstDate: string, secondDate: string): number => {
const SECONDS_IN_DAY: number = 1000 * 60 * 60 * 24
return Math.floor((Date.parse(secondDate) - Date.parse(firstDate)) / SECONDS_IN_DAY)
}
export default getCountDays
|
a2324b3b99b500b912bdcbcc0f2484fe767948e0
|
TypeScript
|
cindyjh/study-typescript
|
/study-12-project/src/components/page/items/image.ts
| 2.703125
| 3
|
// import { PageComponent } from "./page.js";
import { BaseComponent } from "../../component.js";
export class ImageComponent extends BaseComponent<HTMLImageElement> {
constructor(readonly title: string, readonly url: string) {
super(`<section class="image">
<div class="image__holder"><img class="image__thumbnail"></div>
<p class="page-item__title image__title"></p>
</section>`)
const imageElement = this.element.querySelector('.image__thumbnail')! as HTMLImageElement;
imageElement.src = url;
imageElement.alt = title;
const titleElement = this.element.querySelector('.image__title')! as HTMLParagraphElement;
titleElement.textContent = title;
}
}
|
ee739a102aa60387b2f6a76062e5a81298334cdc
|
TypeScript
|
shogonir/mandelbrot-map
|
/src/engine/object/geometry/TexturePlaneGeometry.ts
| 2.890625
| 3
|
import Geometry from './Geometry'
export default class TexturePlaneGeometry implements Geometry {
vertices: number[]
indices: number[]
constructor(width: number) {
const halfWidth = width / 2
this.vertices = [
-halfWidth, halfWidth, 0.0,
0.0, 0.0,
-halfWidth, -halfWidth, 0.0,
0.0, 1.0,
halfWidth, halfWidth, 0.0,
1.0, 0.0,
halfWidth, -halfWidth, 0.0,
1.0, 1.0
]
this.indices = [
0, 1, 2,
1, 3, 2
]
}
}
|
99cef6d82014e5edc8f75338426bc0722ed29bb2
|
TypeScript
|
gato/streamloots
|
/src/adapters/repository/mongodbCardRepository.ts
| 2.75
| 3
|
import Card from '../../core/entities/Card';
import Rarity from '../../core/entities/Rarity';
import { CardRepository } from '../../core/repositories/cardRepository';
import MongoClient from 'mongodb';
interface MongoCard {
id: string;
owner: string;
name: string;
image: string;
limit: number;
rarity: Rarity;
published: boolean;
}
export class MongoCardRepository implements CardRepository {
hostname: string;
port: number;
client: any;
constructor(hostname: string, port: number) {
this.hostname = hostname;
this.port = port;
this.client = null;
}
private async getDB() {
// const url = `mongodb://localhost:27017`;
const url = `mongodb://${this.hostname}:${this.port}`;
if (this.client === null) {
this.client = await MongoClient.connect(url, {
useUnifiedTopology: true,
});
}
return this.client.db('streamloots');
}
private mongoCard2Card(card: MongoCard, used: number, owned: number): Card {
const c: Card = {
id: card.id,
image: card.image,
owner: card.owner,
limit: card.limit,
name: card.name,
rarity: card.rarity,
published: card.published,
used: used,
owned: owned,
};
return c;
}
private card2MongoCard(card: Card): MongoCard {
const c: MongoCard = {
id: card.id,
image: card.image,
owner: card.owner,
limit: card.limit,
name: card.name,
rarity: card.rarity,
published: card.published,
};
return c;
}
public async get(user: string, id: string): Promise<Card> {
const db = await this.getDB();
const card: MongoCard = await db.collection('cards').findOne({ id });
if (card === null) {
return null;
}
// TODO: calculate owned and used
const used = 0;
const owned = 0;
return this.mongoCard2Card(card, used, owned);
}
public async getAll(user: string): Promise<Card[]> {
const db = await this.getDB();
const cards: MongoCard[] = await db
.collection('cards')
.find({
$or: [
{
owner: user,
},
{
published: true,
},
],
})
.toArray();
return cards.map((c) => {
// TODO: calculate owned and used
const used = 0;
const owned = 0;
return this.mongoCard2Card(c, used, owned);
});
}
public async create(user: string, card: Card): Promise<Card> {
const db = await this.getDB();
const c: MongoCard = this.card2MongoCard(card);
await db.collection('cards').insertOne(c);
return this.mongoCard2Card(c, 0, 0);
}
public async save(user: string, card: Card): Promise<Card> {
const db = await this.getDB();
const c: MongoCard = this.card2MongoCard(card);
await db.collection('cards').updateOne({ id: c.id }, { $set: c });
// TODO: calculate owned and used
const used = 0;
const owned = 0;
return this.mongoCard2Card(card, used, owned);
}
}
|
37d228867478d501fca351e92cd7d3c6ddaf14de
|
TypeScript
|
MelkdeSousa/nlw-value
|
/src/controllers/User/Create.ts
| 2.625
| 3
|
import { Request as ExpressRequest, Response as ExpressResponse } from 'express'
import CreateUserService from '../../services/User/Create'
interface ICreateUserController {
handle(
request: ExpressRequest,
response: ExpressResponse
): Promise<ExpressResponse>
}
class CreateUserController implements ICreateUserController {
async handle(request: ExpressRequest, response: ExpressResponse) {
const { name, email, password,admin } = request.body
const createUserService = new CreateUserService()
const user = await createUserService.execute({ name, email, password, admin })
return response.json(user)
}
}
export default CreateUserController
|
468cb0258bac795c948d77a30f48d1d0d34d6f02
|
TypeScript
|
muratkeremozcan/books
|
/Angular_with_Typescript/angular-unit-testing-with-Spectator-Jest/src/app/dashboard/dashboard-hero.component.spec.ts
| 2.984375
| 3
|
import { Hero } from '../model/hero';
import { Spectator, createComponentFactory, byText } from '@ngneat/spectator/jest';
import { DashboardHeroComponent } from './dashboard-hero.component';
// [1].2 unit testing components with @Input and @Output properties
// setup the component much less overhead with spectator (1.1)
// access the TS with spectator.component (1.2)
// use spectator.detectChanges() to trigger the change detection (1.3),
// use DOM testing library convenience methods: https://github.com/ngneat/spectator#queries' (1.4)
// to test @Output subscribe to the event emitter and setup what will be emitted (1.5.1),
// trigger the event using spectator events api https://github.com/ngneat/spectator#events-api (1.5.2) and verify what is emitted (1.5.3)
describe('[1] Testing Components with Spectator: unit testing components with @Input and @Output properties', () => {
let comp: DashboardHeroComponent;
// (1.1) setup the component
let spectator: Spectator<DashboardHeroComponent>;
const createComponent = createComponentFactory({
component: DashboardHeroComponent,
detectChanges: false // KEY: no waitForAsync necessary, and we should explicitly set detectChanges as false
});
beforeEach(() => {
spectator = createComponent(); // (1.1) setup the component.. TestBed.configureTestingModule({..})
comp = spectator.component; // (1.2) access the TS... comp = fixture.debugElement.componentInstance
});
it('(1.1) setup the component, (1.2) access the TS with spectator.component, (1.4) access the DOM with spectator.element', () => {
expect(comp).toBeTruthy();
});
describe('(1.3) spectator.detectChanges() to trigger change detection', () => {
let mockHeroInput: Hero;
beforeEach(() => {
// this component has an @Input property. So, simulate the @Input hero property being set by the parent
// note: when the component has @Input(s), in the tests you need to set the initial input, or emit a hero on your subscription, or your dom will never render
mockHeroInput = comp.hero = { id: 42, name: 'new Hero Name' };
// (1.3) detectChanges() : to update the bindings / trigger change detection
spectator.detectChanges();
});
it('Testing @Input: , (1.4) use DOM testing library convenience methods https://github.com/ngneat/spectator#queries', () => {
// (1.4) access the DOM...
expect(spectator.query('.hero')).toHaveText(mockHeroInput.name.toUpperCase());
expect(spectator.query(byText(mockHeroInput.name.toUpperCase(), { selector: '.hero' }))).toBeTruthy(); // extra check
});
it('Testing the @Output: (1.5.1) subscribe to the event emitter and set up what will be emitted, (1.5.2) use spectator events api (https://github.com/ngneat/spectator#events-api) to trigger click ' , () => {
let emittedHero: Hero;
// (1.5.1) subscribe to the event emitter @Output and set up what will be emitted (this.hero will be emitted which we emulate as emittedHero)
comp.selected.subscribe((hero: Hero) => emittedHero = hero );
// (1.5.2) trigger the event using spectator events api https://github.com/ngneat/spectator#events-api
spectator.click('.hero');
// (1.5.3) verify that what is emitted
expect(emittedHero).toBe(mockHeroInput);
});
});
});
|
2b703f17982d1776cfdd8739d578b97137fd92df
|
TypeScript
|
foltz/gulp-babel-test
|
/src/api/auth/AppUser.ts
| 2.703125
| 3
|
//eval('var Slacktravel = (this.Slacktravel || (this.Slacktravel = {}))');
import Firebase = require('firebase');
interface IAppUser {
firstName?:string;
lastName?:string;
email?:string;
}
class AppUserDoc implements IAppUser {
firstName:string;
lastName:string;
email:string;
}
class AppUserForm {
id:string;
firstName:string;
lastName:string;
email:string;
another:string;
}
export class AppUserCommands {
runTest(val:string) { return `yo baby?! ${val}`}
saveRec (form:AppUserForm) : Command {
var cmd = new Command();
var FB_URL = "https://slacktravel-test.firebaseio.com/AppUsers/";
var fBase = new Firebase(FB_URL);
if (form.id) {
// - check to see if the user exists....
let userRef = fBase.child(form.id);
userRef.once('value', function(result) {
var user = result.val();
if (user == null) {
console.log("No user found");
return;
}
user.firstName = form.firstName;
user.lastName = form.lastName;
user.email = form.email;
userRef.set(user);
var x = "";
});
} else {
let user = new AppUserDoc();
user.firstName = form.firstName;
user.lastName = form.lastName;
user.email = form.email;
let userRef = fBase.push();
userRef.set(user);
}
fBase.off();
return cmd.setSuccess(null);
}
}
class Command {
public success: boolean;
public error: string;
public data: any;
public setError(msg) {
this.success = false;
this.error = msg;
return this;
}
public setSuccess(data) {
this.success = true;
this.data = data;
return this;
}
}
|
245e1053473b98398a658f4265bd8f8fc9af5077
|
TypeScript
|
johanneslumpe/styled-props
|
/src/utils/backgrounds-and-borders/borderLeftStyle.ts
| 2.703125
| 3
|
import { BorderLeftStylePropertyCombined } from '@johanneslumpe/css-types';
import { style } from '../../style';
import { StyleOptions } from '../../types';
export interface BorderLeftStyleProps<T> {
/**
* The **`border-left-style`** CSS property sets the line style of an element's left `border`.
*
* @see https://developer.mozilla.org/docs/Web/CSS/border-left-style
*/
style$BorderLeftStyle: T;
}
export const borderLeftStyle = <
T = BorderLeftStylePropertyCombined,
Theme = never,
Breakpoints = never
>({
themeProp,
}: Partial<StyleOptions<BorderLeftStyleProps<T>, Theme>> = {}) =>
style<BorderLeftStyleProps<T>, Theme, Breakpoints>({
cssProp: 'borderLeftStyle',
prop: 'style$BorderLeftStyle',
themeProp,
});
|
0c1efd2317fe53dcee7f005ce271eea4b6815dda
|
TypeScript
|
palantir/plottable
|
/src/memoize/memoizeProjectors.ts
| 3.046875
| 3
|
import type { MapCache } from "lodash";
import memoize from "lodash-es/memoize";
import { Dataset } from "../core/dataset";
import { AttributeToProjector, Projector } from "../core/interfaces";
interface IIndexMapRecord {
[key: number]: any;
}
/**
* An index that stores values by numeric key.
*
* Internally this uses prototype-less objects as key lookups are marginally
* faster than `{}`s.
*/
class IndexMap<T> {
private map: IIndexMapRecord = Object.create(null);
private exists: IIndexMapRecord = Object.create(null);
public delete(key: number): boolean {
delete this.map[key];
delete this.exists[key];
return true;
}
public get(key: number): T {
return this.map[key];
}
public has(key: number): boolean {
return !!this.exists[key];
}
public set(key: number, value: T) {
this.map[key] = value;
this.exists[key] = true;
return this;
}
}
/**
* A lodash-style `MapCache` that utilizes a [number, number] key to create a
* fast-lookup 2D index. This is much faster than stringifying the key.
*/
class DatasetIndexCache implements MapCache {
public static resolver = (d: any, i: number, dataset: Dataset) => [dataset.updateId(), i];
private map: IndexMap<IndexMap<any>> = new IndexMap<IndexMap<any>>();
public get(key: any): any {
return this.map.get(key[0]).get(key[1]);
}
public has(key: any): boolean {
return this.map.has(key[0]) && this.map.get(key[0]).has(key[1]);
}
public set(key: any, value: any) {
this.map.has(key[0]) || this.map.set(key[0], new IndexMap<any>());
this.map.get(key[0]).set(key[1], value);
return this;
}
public delete(key: any): boolean {
// NOTE: this can potentially leave dangling `IndexMap`s if we delete
// all the keys from the index instead of using `clear`. The overhead is
// minimal, so this is fine.
this.map.has(key[0]) && this.map.get(key[0]).delete(key[1]);
return true;
}
public clear(): void {
this.map = new IndexMap<IndexMap<any>>();
}
}
export function memoizeProjector(projector: Projector): Projector {
const memo = memoize(projector, DatasetIndexCache.resolver);
(memo as any).cache = new DatasetIndexCache();
return memo;
}
export function memoizeProjectors(attrToProjector: AttributeToProjector) {
Object.keys(attrToProjector).forEach((key) => {
attrToProjector[key] = memoizeProjector(attrToProjector[key]);
});
return attrToProjector;
}
|
c895845435386562d28f109ed19a143c91f2358e
|
TypeScript
|
awslabs/amazon-eks-irsa-cfn
|
/lib/util.ts
| 3.046875
| 3
|
import { DefaultTokenResolver, IConstruct, Lazy, StringConcat, Tokenization } from '@aws-cdk/core';
import { IPolicy } from '@aws-cdk/aws-iam';
const MAX_POLICY_NAME_LEN = 128;
export function undefinedIfEmpty(f: () => string[]): string[] {
return Lazy.listValue({ produce: () => {
const array = f();
return (array && array.length > 0) ? array : undefined;
}});
}
/**
* Used to generate a unique policy name based on the policy resource construct.
* The logical ID of the resource is a great candidate as long as it doesn't exceed
* 128 characters, so we take the last 128 characters (in order to make sure the hash
* is there).
*/
export function generatePolicyName(scope: IConstruct, logicalId: string): string {
// as logicalId is itself a Token, resolve it first
const resolvedLogicalId = Tokenization.resolve(logicalId, {
scope,
resolver: new DefaultTokenResolver(new StringConcat()),
});
return lastNCharacters(resolvedLogicalId, MAX_POLICY_NAME_LEN);
}
/**
* Returns a string composed of the last n characters of str.
* If str is shorter than n, returns str.
*
* @param str the string to return the last n characters of
* @param n how many characters to return
*/
function lastNCharacters(str: string, n: number) {
const startIndex = Math.max(str.length - n, 0);
return str.substring(startIndex, str.length);
}
/**
* Helper class that maintains the set of attached policies for a principal.
*/
export class AttachedPolicies {
private policies = new Array<IPolicy>();
/**
* Adds a policy to the list of attached policies.
*
* If this policy is already, attached, returns false.
* If there is another policy attached with the same name, throws an exception.
*/
public attach(policy: IPolicy) {
if (this.policies.find(p => p === policy)) {
return; // already attached
}
if (this.policies.find(p => p.policyName === policy.policyName)) {
throw new Error(`A policy named "${policy.policyName}" is already attached`);
}
this.policies.push(policy);
}
}
/**
* Merge two dictionaries that represent IAM principals
*/
export function mergePrincipal(target: { [key: string]: string[] }, source: { [key: string]: string[] }) {
for (const key of Object.keys(source)) {
target[key] = target[key] || [];
let value = source[key];
if (!Array.isArray(value)) {
value = [ value ];
}
target[key].push(...value);
}
return target;
}
|
d26ec449ed0cde80dcb86658e31b9580626b5261
|
TypeScript
|
wi101/swagger2-angular2-materialize
|
/src/app/modules/main/left-menu/left-menu.ts
| 2.546875
| 3
|
import {Component} from '@angular/core';
import {ApiDocService} from '../../../services/apidoc.service';
import {ApiDefinition} from '../../../model/api-definition';
import {PathsObject} from '../../../model/apidoc';
import {Router} from "@angular/router";
@Component({
selector:'left-menu',
template:require('./left-menu.html'),
})
export class LeftMenu {
private apiDoc:ApiDefinition;
constructor(private apiDocService:ApiDocService, private router:Router) {
this.apiDoc = new ApiDefinition();
apiDocService.getApi().subscribe((apiDoc:ApiDefinition) => {
this.apiDoc = apiDoc;
});
}
onSelectApi(event:Event,apiPath:PathsObject):void {
event.preventDefault();
let index:number = 0;
// This would also work (in most cases):
// console.log(`index of clicked path ${apiPath.name} is ${this.apiDoc.paths.indexOf(apiPath)}`);
this.apiDoc.paths.forEach( (path:PathsObject,idx:number) => {
if(path.name === apiPath.name) {
index = idx;
}
});
// console.log(`calculated index is: ${index}`)
this.markApiPathSelected(apiPath);
this.router.navigate(['apis', index+1]);
}
markApiPathSelected (path: PathsObject) {
this.apiDoc.paths.forEach((path: PathsObject) => path.selected = false);
path.selected = true;
}
}
|
f169dddef8ffde94af08f428e6fea9582306a06f
|
TypeScript
|
ai-labs-team/casium-devtools
|
/src/injected-script.ts
| 2.78125
| 3
|
/**
* This script is injected and executed in the context of the inspected page via
* the Content Script. It initializes an Instrumenter backend that uses
* `window.postMessage` to relay messages to the Content Script.
*/
import { Instrumenter } from './instrumenter';
import { fromMatches } from './util';
const isAllowedSender = fromMatches([
'CasiumDevToolsBackgroundScript',
'CasiumDevToolsPanel'
]);
new Instrumenter().addBackend('WebExtension', ({ connect, disconnect, send }) => {
window.addEventListener('message', ({ data }) => {
if (!isAllowedSender(data)) {
return;
}
/**
* Sent from the Panel UI once it is initialized, ensures that the backend
* queue is not flushed until it is ready to receive and display messages.
*/
if (data.state === 'initialized') {
return connect();
}
/**
* Sent from the Background Script when the Panel is closed or reloaded;
* ensures that messages are queued until the Panel is ready again.
*/
if (data.state === 'disconnected') {
return disconnect();
}
/**
* Forward all other messages directly to the Instrumenter
*/
send(data);
});
return message => {
window.postMessage(message, '*');
}
})
|
6eb9bf7e65277f15c0c1da1efdd2ad3a2f2afad5
|
TypeScript
|
Noronha1612/GatitoBook-Angular
|
/front/src/app/autenticacao/models/usuarioToken.ts
| 2.578125
| 3
|
interface Token {
exp: number;
iat: number;
email: string;
name: string;
id: number;
}
export type UsuarioToken = {
[Key in keyof Token]?: Token[Key];
}
|
47b52d934fc24f2a8dcf0e369a4fe068b5f78504
|
TypeScript
|
WilliamRADFunk/chess
|
/front-end/src/app/utils/get-piece-point-value.ts
| 3.25
| 3
|
export function getPiecePointValue(piece: number): number {
switch (piece) {
case 1: { // Pawn
return 10;
}
case 2: { // Rook
return 50;
}
case 3: { // Knight
return 30;
}
case 4: { // Bishop
return 30;
}
case 5: { // Queen
return 90;
}
case 6: { // King
return 900;
}
default: {
return 0;
}
}
}
|
cec2c1b2039e0c1a11b71adbafedbe8981728dfc
|
TypeScript
|
libin1991/landlord
|
/html/js/src/component/area/player-area/SidePlayerArea.ts
| 2.75
| 3
|
import Container from "../../../render/Container";
import Avatar from "../../player/avatar";
import Name from "../../player/name";
import SideHandPukes from "../../pukes/SideHandPukes";
import User from "../../../user/User";
import { i_DisplayObjectOptions } from "../../../render/DisplayObject";
import Desktop from "../../desktop/Desktop";
import App from "../../../App";
export type i_SidePlayerAreaOptions = i_DisplayObjectOptions & {
user: User;
};
class SidePlayerArea extends Container {
protected _app: App;
// 头像
protected _avatar!: Avatar;
// 名称
protected _name!: Name;
// 手牌
protected _handPukes!: SideHandPukes;
// 出去的牌
protected _desktop!: Desktop;
// 用户id
protected _userId: string;
constructor(app: App, options: i_SidePlayerAreaOptions) {
super(options);
this._app = app;
this._userId = options.user.uid;
}
get userId() {
return this._userId;
}
/**
* 重置
*/
reset() {
// 桌面隐藏
this._desktop.hide();
// 手牌隐藏
this._handPukes.hide();
}
/**
* 准备
* @param isReady
*/
ready(isReady: boolean) {
this._handPukes.hide();
if (isReady) {
// 桌面展示,并且显示准备
this._desktop.show();
this._desktop.ready(isReady);
} else {
this._desktop.hide();
}
console.log(`${this._userId} ${isReady?'准备':'取消准备'}`);
}
/**
* @override
* 初始化手牌
* @param amount
*/
initPukes(amount: number) {
this._desktop.hide();
this._handPukes.postPukes(amount);
this._handPukes.show();
}
/**
* @override
* 初始化手牌
* @param amount
*/
getPukes(amount: number) {
this._handPukes.postPukes(amount);
}
/**
* 进行叫地主
*/
enterAskLandlord() {
this._desktop.hide();
console.log(`${this._userId} 进入叫地主状态`);
}
/**
* 进行抢地主
*/
enterGrabLandlord() {
this._desktop.hide();
console.log(`${this._userId} 进入抢地主状态`);
}
/**
* 游戏开始
*/
gameStart(isLandlord: boolean) {
if (isLandlord) {
this._avatar.beLandlord();
}
this._desktop.hide();
}
/**
* 叫地主
* @param isAsk
*/
askLandlord(isAsk: boolean) {
this._desktop.show();
this._desktop.askLandlord(isAsk);
console.log(`${this._userId} ${isAsk?'叫地主':'不叫地主'}`);
}
/**
* 抢地主
* @param isGrab
*/
grabLandlord(isGrab: boolean) {
this._desktop.show();
this._desktop.grabLandlord(isGrab);
console.log(`${this._userId} ${isGrab?'抢地主':'不抢地主'}`);
}
/**
* 出牌
* @param pukes
*/
shotPukes(pukes: string[]) {
console.log(`${this._userId} 出牌 ${pukes}`);
// 手牌出掉
this._handPukes.shotPukes(pukes.length);
// 桌面牌安排下
this._desktop.shotPukes(pukes);
this._desktop.show();
}
/**
* 进入出牌阶段
*/
enterShotPukes() {
console.log(`${this.userId} 进入出牌阶段`);
this._desktop.reset();
this._desktop.hide();
}
/**
* 游戏重置
*/
gameReset() {
this._avatar.beNormal();
this._handPukes.reset();
this._handPukes.hide();
this._desktop.reset();
this._desktop.hide();
}
}
export default SidePlayerArea;
|
b029147a46113885932fa5e3a50722fb25858fb5
|
TypeScript
|
theednaffattack/instagram-clone
|
/packages/client/src/lib/logoutAllTabs.ts
| 2.75
| 3
|
export const LOGOUT_KEY = "logout";
/**
* Update localStorage 'logout' key to sign out from all windows
* The 'logout' key expects a stringified Date object "Date.now().toString()"
*/
export function logoutAllTabs(): void {
window.localStorage.setItem(LOGOUT_KEY, Date.now().toString());
}
export function clearLogout(): void {
window.localStorage.removeItem(LOGOUT_KEY);
}
|
5b548ef1cf6f55a9daa69d9725967c149232838a
|
TypeScript
|
gin-lsl/zzti-zhihu
|
/src/entities/Admin.ts
| 2.53125
| 3
|
import { SchemaDefinition } from "mongoose";
export interface IAdmin {
email: string;
username: string;
password: string;
}
export class Admin implements IAdmin {
id: string;
email: string;
username: string;
password: string;
static createSchemaDefinition(): SchemaDefinition {
return {
id: String,
email: String,
username: String,
password: String,
};
}
}
|
9c1c3a845afc95b36e21dfcb35221c75991d2da8
|
TypeScript
|
zenatureza/franq-api
|
/src/shared/infra/providers/LogProvider/implementations/WinstonLogProvider.ts
| 2.875
| 3
|
import winston from 'winston';
import ILogProvider from '../interfaces/ILogProvider';
import loggerConfig from '@config/logger';
class WinstonLogProvider implements ILogProvider {
private logger: winston.Logger;
constructor() {
this.setup();
}
private setup() {
// Only shows warns and errors in production, in dev show all
const level = () => {
const env = process.env.NODE_ENV || 'development';
const isDevelopment = env === 'development';
return isDevelopment ? 'debug' : 'warn';
};
winston.addColors(loggerConfig.colors);
const format = winston.format.combine(
winston.format.timestamp({ format: loggerConfig.format.timestamp }),
winston.format.colorize({ all: true }),
winston.format.printf(
info => `${info.timestamp} ${info.level}: ${info.message}`,
),
);
const transports = [
new winston.transports.Console(),
new winston.transports.File({
filename: loggerConfig.files.error,
level: 'error',
}),
new winston.transports.File({ filename: loggerConfig.files.all }),
];
this.logger = winston.createLogger({
level: level(),
levels: loggerConfig.levels,
format,
transports,
});
}
error(message: string): void {
this.logger.error(message);
}
warn(message: string): void {
this.logger.warn(message);
}
info(message: string): void {
this.logger.info(message);
}
debug(message: string): void {
this.logger.debug(message);
}
http(message: string): void {
this.logger.http(message);
}
}
export default WinstonLogProvider;
|
0b7ebbe66bd1be8e17aee63510c4c1d01a64df6c
|
TypeScript
|
david8zhang/battle-engine
|
/src/models/MultiSwitchTurn.ts
| 2.890625
| 3
|
import { IAbstractTurn } from "../interface/IAbstractTurn";
import { LooseObject } from "../interface/LooseObject";
import { ITeamManager } from "../interface/ITeamManager";
import { IArenaManager } from "../interface/IArenaManager";
import { TurnQueue } from "../managers/TurnManager";
import { Hero } from "./Hero";
export class MultiSwitchTurn implements IAbstractTurn {
public priority = -1;
private newActiveTeam : string[];
private side : string;
constructor(config : LooseObject) {
this.newActiveTeam = config.newActiveTeam;
this.side = config.side;
}
public _getNewActiveTeam() : string[] {
return this.newActiveTeam;
}
public _getSide() : string {
return this.side;
}
// All attacks directed at the hero squad to be switched out will effectively be nullified
// by this switch. Multi-attacks work on a timeout system to prevent from abusing squad-switching
public _nullifyAttacks(turnQueue : TurnQueue, currentTeamIds : string[]) : void {
let ctr = 0;
while (ctr <= turnQueue.size()) {
const turn : LooseObject = turnQueue.dequeueTurn();
if (!turn.targetHeroIds || currentTeamIds.indexOf(turn.targetHeroIds[0]) === -1) {
turnQueue.enqueueTurn(turn as IAbstractTurn);
}
ctr++;
}
}
private _generateSwitchMessage(newActiveHeroes : Hero[], oldActiveHeroes : Hero[]) {
let heroesToSwitch = '';
let hasInvalid = false;
const oldActiveHeroIds = oldActiveHeroes.map((h : Hero) => h.getHeroId());
newActiveHeroes.forEach((hero : Hero, index : number) => {
if (hero.getHealth() <= 0) {
hasInvalid = true;
} else {
if (oldActiveHeroIds.indexOf(hero.getHeroId()) === -1) {
if (index === newActiveHeroes.length - 1) {
heroesToSwitch += `${hero.getName()} switched out!`
} else {
heroesToSwitch += `${hero.getName()}, `
}
}
}
})
if (hasInvalid) {
console.error('Invalid hero! One of your switch out heroes is already dead');
return;
}
return heroesToSwitch;
}
public processTurn (teamManager : ITeamManager, arenaManager : IArenaManager, turnQueue : TurnQueue) : LooseObject[] {
const actionLog : LooseObject[] = [];
const newHeroes = teamManager.getHeroes(this.newActiveTeam);
let hasInvalid = false;
if (hasInvalid) {
console.error('Switched out heroes invalid! One or more are dead!');
} else {
if (this.side === 'player') {
const oldActiveHeroTeam : Hero[] = teamManager.getActivePlayerTeam();
const message = this._generateSwitchMessage(newHeroes, oldActiveHeroTeam);
this._nullifyAttacks(turnQueue, oldActiveHeroTeam.map((h : Hero) => h.getHeroId()));
teamManager.setActivePlayerTeam(this.newActiveTeam);
actionLog.push({
type: 'MultiSwitch',
message,
result: {
side: this.side,
oldActiveHeroTeam,
newActiveHeroTeam: teamManager.getActivePlayerTeam()
}
});
} else {
const oldActiveHeroTeam : Hero[] = teamManager.getActiveEnemyTeam();
const message = this._generateSwitchMessage(newHeroes, oldActiveHeroTeam);
this._nullifyAttacks(turnQueue, oldActiveHeroTeam.map((h : Hero) => h.getHeroId()));
teamManager.setActiveEnemyTeam(this.newActiveTeam);
actionLog.push({
type: 'MultiSwitch',
message,
result: {
side: this.side,
oldActiveHeroTeam,
newActiveHeroTeam: teamManager.getActiveEnemyTeam()
}
})
}
}
return actionLog;
}
}
|
dbc28087880151d1a0c6ca023c8338ec073d557c
|
TypeScript
|
Jhon-Idrovo/apiculture
|
/client/store/entities/expenses.ts
| 2.515625
| 3
|
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import axiosInstance from '../../config/axiosInstance';
import { EXPENSES_ENDPOINT } from '../../config/config';
import { compareRows, errorToMessage, IField, Order, translate } from '../../utils/utils';
import { RootState } from '../configureStore';
import { AppThunk } from '../middleware/thunkMiddleware';
import { IHive } from './hives';
export declare interface IExpense {
_id: string;
hive?: Pick<IHive, "_id" | "name">;
amount: number;
description: string;
date: string; // yy/mm/dd
}
export declare type EntityStateType =
| "init"
| "loading"
| "loaded"
| "load-failed"
| "saving"
| "saved"
| "save-failed";
const expensesInitialState = {
state: "init" as EntityStateType,
error: "",
sortBy: "" as keyof IExpense,
order: "asc" as Order,
list: [] as IExpense[],
};
const expensesSlice = createSlice({
name: "expenses",
initialState: expensesInitialState,
reducers: {
expensesLoading: (expenses, action: PayloadAction<EntityStateType>) => {
expenses.error = "";
expenses.state = action.payload;
},
expensesLoaded: (expenses, action: PayloadAction<IExpense[]>) => {
expenses.list = action.payload;
expenses.state = "loaded";
expenses.error = "";
},
expensesLoadFailed: (expenses, action: PayloadAction<string>) => {
expenses.error = action.payload;
expenses.state = "load-failed";
},
expensesSort: (
expenses,
action: PayloadAction<{ sortBy: keyof IExpense; order: Order }>
) => {
const { sortBy, order } = action.payload;
expenses.list.sort(compareRows<IExpense>(sortBy, order));
expenses.sortBy = sortBy;
expenses.order = order;
expenses.state = "init";
},
expenseSaved: (expenses, action: PayloadAction<IExpense>) => {
expenses.list.push(action.payload);
expenses.error = "";
expenses.state = "saved";
},
expensesReestart: (expenses) => {
expenses.error = "";
expenses.state = "init";
},
},
});
const {
expensesLoading,
expensesLoaded,
expensesLoadFailed,
expensesSort,
expenseSaved,
expensesReestart,
} = expensesSlice.actions;
export default expensesSlice.reducer;
// GET FUNCTIONS
export const getExpenes = (state: RootState) => state.entities.expenses;
// ACTION FUNCTIONS
export const loadExpenses = (): AppThunk => async (dispatch) => {
try {
// set loading
dispatch(expensesLoading("loading"));
// call to api
const res = await axiosInstance.get(EXPENSES_ENDPOINT);
// set the state
dispatch(expensesLoaded(res.data.expenses));
dispatch(sortExpenses("date"));
} catch (error) {
dispatch(expensesLoadFailed(errorToMessage(error)));
}
};
export const sortExpenses =
(sortBy: keyof IExpense): AppThunk =>
(dispatch, getState) => {
dispatch(expensesLoading("loading"));
const state = getState();
const expenses = state.entities.expenses;
// If we have the colum already sorted we only need to change the order.
// Otherwise, start with ascendent
const o: Order =
expenses.sortBy === sortBy
? expenses.order === "asc"
? "desc"
: "asc"
: // start ascendent if sortBy is different
"asc";
dispatch(expensesSort({ order: o, sortBy }));
};
export const saveExpense =
(
amount: number | "",
description: string,
date: string | number,
hive: string
): AppThunk =>
async (dispatch) => {
dispatch(expensesLoading("saving"));
try {
if (!(amount && description && date && hive)) throw new Error("errMsg01");
const r = await axiosInstance.post(EXPENSES_ENDPOINT + "/create", {
amount,
description,
date: new Date(date).getTime(),
hive: hive === "N/A" ? null : hive,
});
dispatch(expenseSaved(r.data.expense));
} catch (error) {
console.log(error);
dispatch(expensesLoadFailed(errorToMessage(error)));
}
};
export const expensesToDefault = (): AppThunk => (dispatch) => {
dispatch(expensesReestart());
};
// UTILS
export declare type ExpensesMappingType = Record<
keyof Omit<IExpense, "_id">,
IField
>;
export const expensesKeyMapping: ExpensesMappingType = {
amount: {
header: translate("cantidad"),
transform: (t: string) => "$ " + t,
} as IField,
description: {
header: translate("descripcion"),
transform: (t: string) => t,
} as IField,
date: {
header: translate("fecha"),
transform: (d: number) => new Date(d).toLocaleDateString(),
} as IField,
hive: {
header: translate("colmena"),
transform: (hive: IExpense["hive"]) => (hive ? hive._id : "N/A"),
} as unknown as IField,
};
|
408fa70d0b024fe2bef804b25cc60985e5abcffa
|
TypeScript
|
Mahmudulazamshohan/project_management
|
/src/redux/reducers/postReducers.ts
| 2.859375
| 3
|
import { PostInterface } from "../interfaces/postInterface";
import {
GET_POSTS,
GetPostsStateType,
PostActionTypes,
REMOVE_POST,
} from "../types/postTypes";
const initialStateGetPosts: GetPostsStateType = {
posts: [],
};
type ActionTypes = {
type: string;
payload: any;
};
export const getPostsReducer = (
state = initialStateGetPosts,
action: ActionTypes
): GetPostsStateType => {
switch (action.type) {
case GET_POSTS:
return {
...state,
posts: action.payload,
};
case REMOVE_POST:
return {
...state,
posts: state.posts.filter((p) => {
return p.id !== action.payload;
}),
};
default:
return state;
}
};
|
a0e2d760833d0fbaf7a40c66841fe3262168711b
|
TypeScript
|
guardian/facia-tool
|
/fronts-client/src/util/__tests__/clipboardUtils.spec.ts
| 2.578125
| 3
|
import { liveArticle, articleWithSupporting } from 'fixtures/shared';
import { stateWithClipboard } from 'fixtures/clipboard';
import { normaliseClipboard, denormaliseClipboard } from '../clipboardUtils';
describe('Clipboard utilities', () => {
describe('normaliseClipboard', () => {
it('should normalise a clipboard with articles', () => {
const result = normaliseClipboard({
articles: [liveArticle, articleWithSupporting],
});
const { cards } = result;
const clipboardArticles = result.clipboard.articles;
const supportingArticle = cards[clipboardArticles[1]].meta.supporting![0];
expect(clipboardArticles.length).toEqual(2);
expect(Object.keys(cards).length).toEqual(4);
expect(cards[clipboardArticles[0]].id).toBe('article/live/0');
expect(cards[clipboardArticles[1]].id).toBe('a/long/path/1');
expect(cards[supportingArticle].id).toBe('article/draft/2');
});
});
describe('denormaliseClipboard', () => {
it('should denormalise a clipboard from the application state', () => {
const result = denormaliseClipboard(stateWithClipboard as any);
expect(result.articles[0].id).toEqual('article/live/0');
expect(result.articles[1].id).toEqual('article/live/1');
expect(result.articles[1].meta.supporting![0].id).toEqual(
'article/live/3'
);
});
});
});
|