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
|
|---|---|---|---|---|---|---|
83efc8eae0d8f2bab58652403937bb9d4fbc7991
|
TypeScript
|
kazuhideoki/salon-tablet
|
/src/util/db/checkIsGeneratePubulicPage.ts
| 2.5625
| 3
|
import { UserInfo, UserInfoFromDB } from '../interface/Interface';
import { db } from './db';
import { userInfoParamsFromSql } from './userInfoParamsFromSql';
export const checkIsGeneratePubulicPage = async (
slug: string
): Promise<UserInfo | null> => {
try {
const data = (await db(`SELECT * FROM user_info`)) as UserInfoFromDB[];
const target = data.filter((value) => {
return value.public_page_slug === slug && value.is_generate_public_page;
});
if (target.length) {
return userInfoParamsFromSql(target[0]) as UserInfo;
} else {
return null;
}
} catch (err) {
throw `checkIsGeneratePubulicPage: ${err}`;
}
};
|
c41905d0597731abfff22a682fc6939d1fd2c031
|
TypeScript
|
Antiplusists/Cardsetta
|
/Core/ClientApp/src/patchHelpers/DeckPatcher.ts
| 2.921875
| 3
|
export default class DeckPatcher {
private _name: string | null;
private _description: string | null;
constructor() {
this._name = null;
this._description = null;
}
public patchName(newName: string): DeckPatcher {
this._name = newName;
return this;
}
public patchDescription(newDescription: string): DeckPatcher {
this._description = newDescription;
return this;
}
public build(): object[] {
let result = new Array<object>();
if (this._name) {
result.push({
op: "replace",
path: "/name",
value: this._name
});
}
if (this._description !== null) {
result.push({
op: "replace",
path: "/description",
value: this._description
});
}
return result;
}
}
|
2a07263ada6834c9b8c77523100b3602e7dd3c75
|
TypeScript
|
icon-project/icon-sdk-js
|
/lib/builder/call/Call.ts
| 2.84375
| 3
|
/*
* Copyright 2021 ICON Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { createPrivate } from "../../data/Util";
import { Hash } from "../../types/hash";
/**
* Class for calling the SCORE API.
*/
export class Call {
to: Hash;
from: Hash;
dataType: "call";
data: unknown;
height?: Hash;
constructor(to: Hash, from: Hash, data: unknown, height?: Hash) {
this.to = to;
this.dataType = "call";
this.data = data;
if (from) {
this.from = from;
}
if (height) {
this.height = height;
}
}
}
/**
* Builder class for a 'Call' object.
*/
export class CallBuilder {
private private: any;
/**
* Creates an instance of CallBuilder.
*/
constructor() {
this.private = createPrivate();
this.private(this).to = undefined;
this.private(this).from = undefined;
this.private(this).height = undefined;
this.private(this).data = {};
}
/**
* Set 'to' property
* @param {string} to - The SCORE address.
* @return {CallBuilder} this.
*/
to(to: string): CallBuilder {
this.private(this).to = to;
return this;
}
/**
* Set 'from' property
* @param {string} from - The EOA address.
* @return {CallBuilder} this.
*/
from(from: string): CallBuilder {
this.private(this).from = from;
return this;
}
/**
* Set 'method' property
* @param {string} method - The method name of SCORE API
* @return {CallBuilder} this.
*/
method(method: string): CallBuilder {
this.private(this).data.method = method;
return this;
}
/**
* Set 'params' property
* @param {object} params - The input params for method
* @return {CallBuilder} this.
*/
params(params: any): CallBuilder {
if (params) {
this.private(this).data.params = params;
}
return this;
}
/**
* Set 'height' property
* @param {Hash} [height] block height.
* @return {CallBuilder} this.
*/
height(height: Hash): CallBuilder {
this.private(this).height = height;
return this;
}
/**
* Build 'Call' object
* @return {Call} 'Call' instance exported by 'CallBuilder'.
*/
build(): Call {
return new Call(
this.private(this).to,
this.private(this).from,
this.private(this).data,
this.private(this).height
);
}
}
|
aa1504c2b025d70e4017c4b03375400c5ccd0294
|
TypeScript
|
RichieAHB/normal-distribution
|
/src/__tests__/NormalDistribution.spec.ts
| 3.21875
| 3
|
import NormalDistribution from "../NormalDistribution";
describe("NormalDistribution", () => {
describe("#cdf", () => {
it("should return 0.5 for a z-score of 0", () => {
const nd = new NormalDistribution();
expect(nd.cdf(0)).toEqual(0.5);
});
it("should return 0 for a z-score less than -3.5", () => {
const nd = new NormalDistribution();
expect(nd.cdf(-4)).toEqual(0);
});
it("should return 1 for a z-score more than 3.5", () => {
const nd = new NormalDistribution();
expect(nd.cdf(4)).toEqual(1);
});
});
describe("#pdf", () => {
it("should return 0.3989422804014327 for x = 0 on a standard normal distribution", () => {
const nd = new NormalDistribution();
expect(nd.pdf(0)).toEqual(0.3989422804014327);
});
it("should return 0.00013383022576488545 for a z-score of -4", () => {
const nd = new NormalDistribution();
expect(nd.pdf(-4)).toEqual(0.00013383022576488545);
});
it("should return 0.00013383022576488542 for a z-score of 4", () => {
const nd = new NormalDistribution();
expect(nd.pdf(4)).toEqual(0.00013383022576488545);
});
});
describe("#probabilityBetween", () => {
it("should return 1 between -4 and 4 for a standard normal distribution", () => {
const nd = new NormalDistribution();
expect(nd.probabilityBetween(-4, 4)).toEqual(1);
});
});
});
|
a3b71fcbd3e82cfe57bcb256888dc1c0bb6a8104
|
TypeScript
|
tacthgin/MagicTower
|
/MagicTower/assets/GameFramework/Script/NodePool/NodeObject.ts
| 2.65625
| 3
|
import { ReferencePool } from "../Base/ReferencePool/ReferencePool";
import { ObjectBase } from "../ObjectPool/ObjectBase";
import { INodeHelper } from "./INodeHelper";
/**
* 节点对象
*/
export class NodeObject extends ObjectBase {
private _nodeHelper: INodeHelper = null!;
static create(name: string, node: object, nodeHelper: INodeHelper): NodeObject {
let nodeObejct = ReferencePool.acquire(NodeObject);
nodeObejct.initialize(name, node);
nodeObejct._nodeHelper = nodeHelper;
return nodeObejct;
}
onUnspawn(): void {
this._nodeHelper.releaseNode(this.target);
}
clear(): void {
super.clear();
this._nodeHelper.releaseNode(this.target);
this._nodeHelper = null!;
}
}
|
f8babef68c452d7186011aa0ad7d0682bf159693
|
TypeScript
|
QPC-database/jacdac-docs
|
/src/components/widgets/svg.ts
| 2.90625
| 3
|
/* eslint-disable @typescript-eslint/no-explicit-any */
function mkTitle(txt: string): SVGTitleElement {
const t = <SVGTitleElement>elt("title")
t.textContent = txt
return t
}
export function title(el: SVGElement, txt: string): SVGTitleElement {
const t = mkTitle(txt)
el.appendChild(t)
return t
}
export function hydrate(el: SVGElement, props: any) {
for (const k in props) {
if (k == "title") {
title(el, props[k])
} else el.setAttributeNS(null, k, props[k])
}
}
export function elt(name: string, props?: any): SVGElement {
const el = document.createElementNS("http://www.w3.org/2000/svg", name)
if (props) hydrate(el, props)
return el
}
export function child(parent: Element, name: string, props?: any): SVGElement {
const el = elt(name, props)
parent.appendChild(el)
return el
}
|
75fb325c0bab27dd590b597a13321b219413f34e
|
TypeScript
|
andrew-oxenburgh/hospitalrun-frontend
|
/src/clients/db/PatientRepository.ts
| 2.765625
| 3
|
import Patient from '../../model/Patient'
import Repository from './Repository'
import { patients } from '../../config/pouchdb'
const formatFriendlyId = (prefix: string, sequenceNumber: string) => `${prefix}${sequenceNumber}`
const generateSequenceNumber = (currentNumber: number): string => {
const newNumber = currentNumber + 1
if (newNumber < 10000) {
return newNumber.toString().padStart(5, '0')
}
return newNumber.toString()
}
export class PatientRepository extends Repository<Patient> {
constructor() {
super(patients)
}
async search(text: string): Promise<Patient[]> {
return super.search({
selector: {
$or: [
{
fullName: {
$regex: RegExp(text, 'i'),
},
},
{
friendlyId: text,
},
],
},
})
}
async getFriendlyId(): Promise<string> {
const storedPatients = await this.findAll()
if (storedPatients.length === 0) {
return formatFriendlyId('P', generateSequenceNumber(0))
}
const maxPatient = storedPatients[storedPatients.length - 1]
const { friendlyId } = maxPatient
const currentSequenceNumber = friendlyId.slice(1, friendlyId.length)
return formatFriendlyId('P', generateSequenceNumber(parseInt(currentSequenceNumber, 10)))
}
async save(entity: Patient): Promise<Patient> {
const friendlyId = await this.getFriendlyId()
entity.friendlyId = friendlyId
return super.save(entity)
}
}
export default new PatientRepository()
|
45256b8b791f348f6fd72d0cf2654b320c4aa656
|
TypeScript
|
peraltapam/dracarys
|
/src/app/dragon/dragon-edit/dragon-edit.component.ts
| 2.546875
| 3
|
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { Dragon } from '../dragon.model';
import { DragonService } from '../dragon.service';
@Component({
selector: 'app-dragon-edit',
templateUrl: './dragon-edit.component.html',
styleUrls: ['./dragon-edit.component.sass']
})
export class DragonEditComponent implements OnInit {
selectedDragon: Dragon;
selectedId: string;
// using template driven approach as exercise
formData: NgForm;
alert = null;
isError = null;
isNotEdited = null;
isLoading = false;
constructor(private dragonService: DragonService, private route: ActivatedRoute) { }
ngOnInit() {
this.isLoading = true;
this.alert = null;
// retrieve dragon id from url and load data
this.selectedId = this.route.snapshot.params['id'];
this.getDragonDetails(this.selectedId);
}
// request dragon detail from api
getDragonDetails(id: string) {
this.dragonService.getDragonDetails(id).subscribe(
response => {
this.selectedDragon = response;
this.isError = false;
this.isLoading = false;
},
error => {
this.alert = 'Unable to fetch dragon details!';
this.isError = true;
this.isLoading = false;
}
)
}
// handle form information
editDragonHandler(form: NgForm) {
this.isLoading = true;
this.isNotEdited = false;
this.alert = null;
this.formData = form;
const newData = form.value
// Check if data inserted is different than original data
if(this.isDataEqual(newData, this.selectedDragon)) {
this.isNotEdited = true;
this.resetForm();
return;
}
// format data to be sent to api
const dragonData = {
name: newData.name,
type: newData.type
}
this.sendEditRequest(form, dragonData);
}
// send edit dragon request
sendEditRequest(form: NgForm, data: Dragon) {
this.dragonService.editDragon(this.selectedId, JSON.stringify(data)).subscribe(
(response) => {
if(response && response.id) {
this.editRequestSuccessHandler(response);
} else {
this.alert = 'Invalid response';
}
this.resetForm();
},
error => {
this.alert = 'Unable to edit Dragon!';
this.isError = true;
this.resetForm();
}
);
}
// return boolean to indicate if new data is equal to the old one
isDataEqual(newData: Dragon, oldData: Dragon) {
return newData.name === oldData.name && newData.type === oldData.type;
}
// update selected dragon data
editRequestSuccessHandler(response: Dragon) {
this.alert = 'Dragon successfully edited!';
this.selectedDragon = {
name: response.name,
type: response.type
}
}
// update form with most current dragon data values
resetForm(form?: NgForm) {
let currentName: string = this.selectedDragon.name,
currentType: string = this.selectedDragon.type;
// form object does not exist before saving for the first time
// todo: implement form with reactive approach
if(!this.formData && form) {
this.formData = form;
currentName = form.value.name;
currentType = form.value.type;
};
this.formData.reset({
name: currentName,
type: currentType
});
this.isLoading = false;
}
// clear alert message
resetAlert() {
this.alert = null;
}
}
|
6aab4fb74487843b5f8a7956934702b4d24c9adb
|
TypeScript
|
daxingyou/Mafia
|
/client20689/client514/PalaceWar/src/game/model/config/prison/PrisonCfg.ts
| 2.546875
| 3
|
namespace Config
{
/**
* 牢房配置类
*/
export namespace PrisonCfg
{
let prisonItemList: Object = {};
export function formatData(data: any): void
{
for (var key in data)
{
let prisonItemCfg: PrisonItemCfg;
if (!prisonItemList.hasOwnProperty(String(key)))
{
prisonItemList[String(key)] = new PrisonItemCfg();
}
prisonItemCfg = prisonItemList[String(key)];
prisonItemCfg.initData(data[key]);
this.prisonItemCfg = prisonItemCfg;
}
}
export function getPrisonItemCfgList():Array<PrisonItemCfg>
{
let arr:Array<PrisonItemCfg> = new Array();
for(let key in prisonItemList)
{
arr.push(prisonItemList[key]);
}
return arr;
}
//根据ID 返回当前配置
export function getIndexPrisonItemCfg(index:number=0):any
{
for(let key in prisonItemList)
{
if(key==""+index)
{
return prisonItemList[key]
}
}
return null
}
export class PrisonItemCfg extends BaseItemCfg
{
// -unlock 解锁条件 通关某一关卡
// --cost 每次惩罚所需声望
// --num 该囚犯的可惩罚次数 num为空时,囚犯可无限惩罚
// --base 资源基础值 在获得银两、粮草、士兵时,用 base + 属性 * 倍率
// --drop 每次惩罚可能获得的奖励 其中有资源_倍率的情况
public unlock:number =0;
public cost:number =0;
public num:number =0;
public drop:Array<any> =[];
public sheetType: number;
}
}
}
|
3915937ec8ebbea0ec4aae6cde14fbd8b1b4d009
|
TypeScript
|
pozterz/nestjs-jwt
|
/src/controllers/auth.controller.ts
| 2.640625
| 3
|
import { Controller, Post, Body, Res, HttpStatus } from '@nestjs/common'
import { AuthService } from '../services/auth.service'
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService){ }
@Post()
async authenticate(@Body() req, @Res() res) {
const token = await this.authService.auth(req)
if(token){
res.status(HttpStatus.OK).json(token)
} else {
res.status(HttpStatus.UNAUTHORIZED).json('Invalid username or password')
}
}
}
|
5233d97cafc40bb74b13e441ad3e6a5c8298ce51
|
TypeScript
|
theorye/oandats
|
/src/definitions/Transaction/CreateTransaction.interface.ts
| 3.09375
| 3
|
import { Transaction, TransactionType } from ".";
import { Integer, Currency } from "../Primitives";
// A CreateTransaction represents the creation of an Account
export interface CreateTransaction extends Transaction {
//
// The Type of the Transaction. Always set to “CREATE” in a
// CreateTransaction.
//
type: TransactionType; //, default=CREATE),
//
// The ID of the Division that the Account is in
//
divisionID: Integer;
//
// The ID of the Site that the Account was created at
//
siteID: Integer;
//
// The ID of the user that the Account was created for
//
accountUserID: Integer;
//
// The number of the Account within the site/division/user
//
accountNumber: Integer;
//
// The home currency of the Account
//
homeCurrency: Currency;
}
|
324d3a1df6dcd24f6c3d5efeb8a818db1fd469a6
|
TypeScript
|
dmc1985/ExerciseTimer
|
/src/common/typings.ts
| 2.890625
| 3
|
export type NumericDictionary<T> = {
[index: number]: T;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type Dictionary<T = any> = {
[index: string]: T;
};
export type Nullable<T> = T | null;
export type Optional<T> = T | undefined;
export type Nillable<T> = T | null | undefined;
|
c0523417c2742dd7c3ff56a87bb0689660655f17
|
TypeScript
|
infojav/initReactAppTemplate
|
/packages/remoteFile/sagas.ts
| 2.546875
| 3
|
import { takeLatest, put } from "redux-saga/effects"
import { ActionTypes, actions } from "./actions"
function* fetchData(action: any) {
const url = `github/Remotefile?url=${action.payload}`
try {
const data = yield fetch(url).then(r => r.json())
if (data.statusCode && data.statusCode > 299) {
yield put(actions.loadErrorRemoteFile(new Error(`Error code: ${data.statusCode}, message: ${data.message}`)))
} else {
yield put(actions.loadSuccessRemoteFile(data))
}
} catch(err) {
yield put({ type: ActionTypes.LOAD_ERROR_REMOTE_FILE, payload: err })
}
}
export function* sagas() {
yield takeLatest(ActionTypes.LOADING_REMOTE_FILE as any, fetchData)
}
// export default sagas;
|
3e4e5002a179352569f54994af4c757e9d443065
|
TypeScript
|
Hermanoid/RaidArea51
|
/src/app/Player.ts
| 2.59375
| 3
|
//let bountyHunter = new BountyHunter(null, null, null, null, null, null, null, null);
//let money = 0;
//let bhOffenseTotal = 0;
//let bhDefenseTotal = 0;
//let damage = 0;
//name: string;
//weight: number;
//cost: number;
//description: string;
//function PlayerCharacter(firstName, lastName, age, combatOffense, combatDefense, luck, hack, health) {
// let _this = this;
// this.firstName = firstName;
// this.lastName = lastName;
// this.age = age;
// this.combatOffense = combatOffense;
// this.combatDefense = combatDefense;
// this.luck = luck;
// this.hack = hack;
// this.health = health;
//}
export class Player {
constructor(
public firstName: string =null,
public lastName: string = null,
public age: number = null,
public combatOffense: number = null,
public combatDefense: number = null,
public luck: number = null,
public hack: number = null,
public health: number = null,
public image: string = null
) {}
}
export class PlayerWeapon {
//name, range, minDamage, maxDamage, weight, toHitModifier, rateOfFire, cost
constructor(
public name: string = null,
public range: string = null,
public minDamage: number = null,
public maxDamage: number = null,
public weight: number = null,
public toHitModifier: number = null,
public rateOfFire: number = null,
public cost: number = null
) {}
}
//Points between hack, luck, health, combat offense, combat defense. Spend 40 skill points.
//export class Combat {
//}
//let getBountyHunterData = () => {
// createBountyHunter();
// getBountyHunterWeaponInfo(bountyHunter.equipWeapon);
// damage = getRandomInt(bountyHunterWeapon.minDamage, bountyHunterWeapon.maxDamage);
// let toHitMod = getRandomInt(1, 10);
// bhOffenseTotal = bountyHunter.combatOffense + toHitMod + bountyHunterWeapon.toHitModifier - rehalRodian["combatDefense"];
// bhDefenseTotal = bountyHunter.combatDefense - rehalRodian["combatOffense"] - getRandomInt(1, 20);
// document.getElementById("bhHitChance").innerHTML = bhOffenseTotal.toString();
// document.getElementById("bhGetHitChance").innerHTML = bhDefenseTotal.toString();
// document.getElementById("bhFirstName").innerHTML = bountyHunter.firstName;
// document.getElementById("bhLastName").innerHTML = bountyHunter.lastName;
// document.getElementById("bhHealth").innerHTML = bountyHunter.health.toString();
//};
//let attack = () => {
// if (bhDefenseTotal <= 0) {
// bountyHunter.health += bhDefenseTotal;
// }
// document.getElementById("bhHealth").innerHTML = bountyHunter.health;
// document.getElementById("health").innerHTML = rehalRodian["health"];
// if (bountyHunter.health < 0) {
// window.location.href = "gameOver.html"
// }
// if (rehalRodian["health"] < 0 && bountyHunter.health >= 0) {
// window.location.href = "bar1.html";
// money = parseInt(sessionStorage.getItem("money"));
// money = money + 800;
// sessionStorage.setItem("money", money.toString());
// }
// if (bhOffenseTotal > 0) {
// rehalRodian["health"] -= damage;
// let toHitMod = getRandomInt(1, 10);
// bhOffenseTotal = bountyHunter.combatOffense + toHitMod + bountyHunterWeapon.toHitModifier - rehalRodian["combatDefense"];
// document.getElementById("bhHitChance").innerHTML = bhOffenseTotal.toString();
// return bhOffenseTotal;
// }
//}
|
ec3ef203722bd925dbbfc9f08750a73451249680
|
TypeScript
|
Lionkka/AngularFlow
|
/HomeWork/myron.kurus/hw-2/jQueryCookie/task#4/app.ts
| 2.765625
| 3
|
function setPromise(delay: number): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => resolve("DONE"), delay*1000);
});
}
let prom1 = setPromise(1);
let prom2 = setPromise(2);
let prom3 = setPromise(1);
Promise.all([prom1, prom2, prom3]).then(values => {
console.log(values);
});
|
16e7e619d09cefda1a88fa8ce584d0f364d540e5
|
TypeScript
|
AlCalzone/shared-utils
|
/src/typeguards/typeguards.test.ts
| 3.171875
| 3
|
import { assert, expect } from "chai";
import { isArray, isObject } from ".";
import type { Equals } from "../types";
// tslint:disable:no-unused-expression
// Used to tests types
function assertTrue<T extends true>() {
return undefined!;
}
type UnspecifiedObject = Record<string | number | symbol, unknown>;
describe("lib/typeguards =>", () => {
describe("isObject() => ", () => {
it("should return true for object literals", () => {
isObject({}).should.be.true;
isObject({ a: "b" }).should.be.true;
});
it("should return true for Object instances", () => {
isObject(new Object()).should.be.true;
});
it("should return false for Arrays", () => {
isObject([]).should.be.false;
isObject(new Array()).should.be.false;
});
it("should return false for everything else", () => {
[null, undefined, 1, 2, 3, "1", "2", "3", true, false].forEach(
(val) => isObject(val).should.be.false,
);
});
it("should allow sub-indexing objects", () => {
const foo = { a: { b: "c" } } as unknown;
isObject(foo) && isObject(foo.a) && isObject(foo.a.b);
});
it("inferred types are correct", () => {
const _any = undefined as any;
const _unknown = undefined as unknown;
const _unknownArray = _unknown as unknown[];
const _number = _unknown as number;
const _numberArray = _unknown as number[];
const _readonlyNumberArray = _unknown as readonly number[];
const _nonNullish = _unknown as {};
const _specificObjectNullable = _unknown as
| { a: number }
| undefined;
const _objectOrArray = _unknown as { a: number } | string[];
if (isObject(_any)) {
assertTrue<Equals<typeof _any, any>>();
_any;
// ^?
}
if (isObject(_unknown)) {
assertTrue<Equals<typeof _unknown, UnspecifiedObject>>();
_unknown;
// ^?
}
if (isObject(_unknownArray)) {
assertTrue<Equals<typeof _unknownArray, never>>();
_unknownArray;
// ^?
}
if (isObject(_number)) {
assertTrue<Equals<typeof _number, never>>();
_number;
// ^?
}
if (isObject(_numberArray)) {
assertTrue<Equals<typeof _numberArray, never>>();
_numberArray;
// ^?
}
if (isObject(_readonlyNumberArray)) {
assertTrue<Equals<typeof _readonlyNumberArray, never>>();
_readonlyNumberArray;
// ^?
}
if (isObject(_nonNullish)) {
assertTrue<Equals<typeof _nonNullish, UnspecifiedObject>>();
_nonNullish;
// ^?
}
if (isObject(_specificObjectNullable)) {
assertTrue<
Equals<
typeof _specificObjectNullable,
NonNullable<typeof _specificObjectNullable>
>
>();
_specificObjectNullable;
// ^?
}
if (isObject(_objectOrArray)) {
assertTrue<Equals<typeof _objectOrArray, { a: number }>>();
_objectOrArray;
// ^?
}
});
});
describe("isArray() => ", () => {
function doTest() {
it("should return true for array literals", () => {
isArray([]).should.be.true;
isArray([1, 2, 3]).should.be.true;
});
it("should return true for Array instances", () => {
isArray(new Array()).should.be.true;
});
it("should return false for everything else", () => {
[
{},
new Object(),
new Buffer(0),
null,
undefined,
1,
2,
3,
"1",
"2",
"3",
true,
false,
].forEach((val) => isArray(val).should.be.false);
});
}
describe(`with native support for "Array.isArray"`, () => {
doTest();
});
describe(`without native support for "Array.isArray"`, () => {
const originalIsArray = Array.isArray;
before(() => ((Array.isArray as any) = undefined));
doTest();
after(() => (Array.isArray = originalIsArray));
});
it("should allow working with the narrowed array", () => {
const foo = ["a", "b", "c"] as string | string[];
isArray(foo) && foo[0];
});
it("inferred types are correct", () => {
const _any = undefined as any;
const _unknown = undefined as unknown;
const _unknownArray = _unknown as unknown[];
const _number = _unknown as number;
const _numberArray = _unknown as number[];
const _readonlyNumberArray = _unknown as readonly number[];
const _nonNullish = _unknown as {};
if (isArray(_any)) {
assertTrue<Equals<typeof _any, any>>();
_any;
// ^?
}
if (isArray(_unknown)) {
assertTrue<Equals<typeof _unknown, unknown[]>>();
_unknown;
// ^?
}
if (isArray(_unknownArray)) {
assertTrue<Equals<typeof _unknownArray, unknown[]>>();
_unknownArray;
// ^?
}
if (isArray(_number)) {
assertTrue<Equals<typeof _number, never>>();
_number;
// ^?
}
if (isArray(_numberArray)) {
assertTrue<Equals<typeof _numberArray, number[]>>();
_numberArray;
// ^?
}
if (isArray(_readonlyNumberArray)) {
assertTrue<
Equals<typeof _readonlyNumberArray, readonly number[]>
>();
_readonlyNumberArray;
// ^?
}
if (isArray(_nonNullish)) {
assertTrue<Equals<typeof _nonNullish, unknown[]>>();
_nonNullish;
// ^?
}
});
});
});
|
aa034a53a77f352b2e27ccc9077298185fb17c95
|
TypeScript
|
dwtcourses/immunity-booster
|
/functions/src/Database/foodsAndCategories.ts
| 3.046875
| 3
|
export const categories = [
"Vitamin B6",
"Vitamin C",
"Vitamin E",
"Prebiotic",
"Probiotic",
];
const b6Foods = ["Chicken", "Salmon", "Tuna", "Trout", "Chickpeas"];
const cFoods = [
"Oranges",
"Grapefruits",
"Tangerines",
"Strawberries",
"Kiwifruit",
"Red bell peppers",
"Brussel sprouts",
"Cauliflower",
];
const eFoods = [
"Almonds",
"Peanuts",
"Hazelnuts",
"Avocado",
"Sunflower seeds",
"Spinach",
"Kale",
"Broccoli",
];
const preFoods = ["Flaxseeds", "Asparagus", "Garlic", "Onion", "Artichokes"];
const proFoods = ["Sauerkraut", "Kimchi", "Yogurt", "Kefir"];
const foods = [b6Foods, cFoods, eFoods, preFoods, proFoods];
export declare interface FoodObject {
label: string;
category: string;
}
export const getRandomItem = (category: string) => {
const categoryLower = category.toLowerCase();
if (categoryLower.includes("vitamin b6")) {
return b6Foods[Math.floor(Math.random() * b6Foods.length)];
} else if (categoryLower.includes("vitamin c")) {
return cFoods[Math.floor(Math.random() * cFoods.length)];
} else if (categoryLower.includes("vitamin e")) {
return eFoods[Math.floor(Math.random() * eFoods.length)];
} else if (categoryLower.includes("prebiotic")) {
return preFoods[Math.floor(Math.random() * preFoods.length)];
} else if (categoryLower.includes("probiotic")) {
return proFoods[Math.floor(Math.random() * proFoods.length)];
} else {
throw new Error("Category Not Found!");
}
};
export const foodToCategory = (foodParam: string) => {
for (let i = 0; i < foods.length; i++) {
for (const food of foods[i]) {
if (food.toLowerCase().includes(foodParam.toLowerCase())) {
return categories[i];
}
}
}
throw new Error("That food does not appear in a category!");
};
|
b0fe8bac4509696662ee2f6be9c62f84ad30ab20
|
TypeScript
|
CrimSol/ajv-formats
|
/tests/issues/617_full_format_leap_year.spec.ts
| 2.609375
| 3
|
import Ajv from "ajv"
import addFormats from "../../dist"
describe("PR #617, full date format validation should understand leap years", () => {
let ajv: Ajv
beforeAll(() => {
ajv = new Ajv({strictTypes: false})
addFormats(ajv)
})
test("should handle non leap year affected dates with date-time", () => {
const schema = {format: "date-time"}
const validDateTime = "2016-01-31T00:00:00Z"
expect(ajv.validate(schema, validDateTime)).toBe(true)
})
test("should handle non leap year affected dates with date", () => {
const schema = {format: "date"}
const validDate = "2016-11-30"
expect(ajv.validate(schema, validDate)).toBe(true)
})
test("should handle year leaps as date-time", () => {
const schema = {format: "date-time"}
const validDateTime = "2016-02-29T00:00:00Z"
const invalidDateTime = "2017-02-29T00:00:00Z"
expect(ajv.validate(schema, validDateTime)).toBe(true)
expect(ajv.validate(schema, invalidDateTime)).toBe(false)
})
test("should handle year leaps as date", () => {
const schema = {format: "date"}
const validDate = "2016-02-29"
const invalidDate = "2017-02-29"
expect(ajv.validate(schema, validDate)).toBe(true)
expect(ajv.validate(schema, invalidDate)).toBe(false)
})
})
|
431ac593133320faf54b2b46b44ec2c8cdfc330a
|
TypeScript
|
duyoji/design_pattern_with_typescript
|
/app/js/Singleton/RegisterNote.ts
| 2.546875
| 3
|
/**
* Created by Tsuyoshi on 2014/09/19.
*/
module Singleton {
export class RegisterNote {
private static instance : RegisterNote;
static getInstance() : RegisterNote {
if (!this.instance) {
this.instance = new RegisterNote();
console.log("new create instance");
} else {
console.log("created instance");
}
return this.instance;
}
constructor() {
}
}
}
|
e43b2d96c343f840d59cf0712ddbdc6b16f8fa94
|
TypeScript
|
DefinitelyTyped/DefinitelyTyped
|
/types/three/src/math/Vector3.d.ts
| 3.078125
| 3
|
import { Euler } from './Euler.js';
import { Matrix3 } from './Matrix3.js';
import { Matrix4 } from './Matrix4.js';
import { Quaternion } from './Quaternion.js';
import { Camera } from '../cameras/Camera.js';
import { Spherical } from './Spherical.js';
import { Cylindrical } from './Cylindrical.js';
import { BufferAttribute } from '../core/BufferAttribute.js';
import { InterleavedBufferAttribute } from '../core/InterleavedBufferAttribute.js';
import { Vector } from './Vector2.js';
import { Color } from './Color.js';
export type Vector3Tuple = [number, number, number];
/**
* 3D vector. ( class Vector3 implements Vector<Vector3> )
*
* see {@link https://github.com/mrdoob/three.js/blob/master/src/math/Vector3.js}
*
* @example
* const a = new THREE.Vector3( 1, 0, 0 );
* const b = new THREE.Vector3( 0, 1, 0 );
* const c = new THREE.Vector3();
* c.crossVectors( a, b );
*/
export class Vector3 implements Vector {
constructor(x?: number, y?: number, z?: number);
/**
* @default 0
*/
x: number;
/**
* @default 0
*/
y: number;
/**
* @default 0
*/
z: number;
readonly isVector3: true;
/**
* Sets value of this vector.
*/
set(x: number, y: number, z: number): this;
/**
* Sets all values of this vector.
*/
setScalar(scalar: number): this;
/**
* Sets x value of this vector.
*/
setX(x: number): Vector3;
/**
* Sets y value of this vector.
*/
setY(y: number): Vector3;
/**
* Sets z value of this vector.
*/
setZ(z: number): Vector3;
setComponent(index: number, value: number): this;
/**
* Sets this vector's {@link x}, {@link y} and {@link z} components from the r, g, and b components of the specified
* {@link Color | color}.
*/
setFromColor(color: Color): this;
getComponent(index: number): number;
/**
* Clones this vector.
*/
clone(): this;
/**
* Copies value of v to this vector.
*/
copy(v: Vector3): this;
/**
* Adds v to this vector.
*/
add(v: Vector3): this;
addScalar(s: number): this;
addScaledVector(v: Vector3, s: number): this;
/**
* Sets this vector to a + b.
*/
addVectors(a: Vector3, b: Vector3): this;
/**
* Subtracts v from this vector.
*/
sub(a: Vector3): this;
subScalar(s: number): this;
/**
* Sets this vector to a - b.
*/
subVectors(a: Vector3, b: Vector3): this;
multiply(v: Vector3): this;
/**
* Multiplies this vector by scalar s.
*/
multiplyScalar(s: number): this;
multiplyVectors(a: Vector3, b: Vector3): this;
applyEuler(euler: Euler): this;
applyAxisAngle(axis: Vector3, angle: number): this;
applyMatrix3(m: Matrix3): this;
applyNormalMatrix(m: Matrix3): this;
applyMatrix4(m: Matrix4): this;
applyQuaternion(q: Quaternion): this;
project(camera: Camera): this;
unproject(camera: Camera): this;
transformDirection(m: Matrix4): this;
divide(v: Vector3): this;
/**
* Divides this vector by scalar s.
* Set vector to ( 0, 0, 0 ) if s == 0.
*/
divideScalar(s: number): this;
min(v: Vector3): this;
max(v: Vector3): this;
clamp(min: Vector3, max: Vector3): this;
clampScalar(min: number, max: number): this;
clampLength(min: number, max: number): this;
floor(): this;
ceil(): this;
round(): this;
roundToZero(): this;
/**
* Inverts this vector.
*/
negate(): this;
/**
* Computes dot product of this vector and v.
*/
dot(v: Vector3): number;
/**
* Computes squared length of this vector.
*/
lengthSq(): number;
/**
* Computes length of this vector.
*/
length(): number;
/**
* Computes Manhattan length of this vector.
* http://en.wikipedia.org/wiki/Taxicab_geometry
*
* @deprecated Use {@link Vector3#manhattanLength .manhattanLength()} instead.
*/
lengthManhattan(): number;
/**
* Computes the Manhattan length of this vector.
*
* see {@link http://en.wikipedia.org/wiki/Taxicab_geometry|Wikipedia: Taxicab Geometry}
*/
manhattanLength(): number;
/**
* Computes the Manhattan length (distance) from this vector to the given vector v
*
* see {@link http://en.wikipedia.org/wiki/Taxicab_geometry|Wikipedia: Taxicab Geometry}
*/
manhattanDistanceTo(v: Vector3): number;
/**
* Normalizes this vector.
*/
normalize(): this;
/**
* Normalizes this vector and multiplies it by l.
*/
setLength(l: number): this;
lerp(v: Vector3, alpha: number): this;
lerpVectors(v1: Vector3, v2: Vector3, alpha: number): this;
/**
* Sets this vector to cross product of itself and v.
*/
cross(a: Vector3): this;
/**
* Sets this vector to cross product of a and b.
*/
crossVectors(a: Vector3, b: Vector3): this;
projectOnVector(v: Vector3): this;
projectOnPlane(planeNormal: Vector3): this;
reflect(vector: Vector3): this;
angleTo(v: Vector3): number;
/**
* Computes distance of this vector to v.
*/
distanceTo(v: Vector3): number;
/**
* Computes squared distance of this vector to v.
*/
distanceToSquared(v: Vector3): number;
/**
* @deprecated Use {@link Vector3#manhattanDistanceTo .manhattanDistanceTo()} instead.
*/
distanceToManhattan(v: Vector3): number;
setFromSpherical(s: Spherical): this;
setFromSphericalCoords(r: number, phi: number, theta: number): this;
setFromCylindrical(s: Cylindrical): this;
setFromCylindricalCoords(radius: number, theta: number, y: number): this;
setFromMatrixPosition(m: Matrix4): this;
setFromMatrixScale(m: Matrix4): this;
setFromMatrixColumn(matrix: Matrix4, index: number): this;
setFromMatrix3Column(matrix: Matrix3, index: number): this;
/**
* Sets this vector's {@link x}, {@link y} and {@link z} components from the x, y, and z components of the specified {@link Euler Euler Angle}.
*/
setFromEuler(e: Euler): this;
/**
* Checks for strict equality of this vector and v.
*/
equals(v: Vector3): boolean;
/**
* Sets this vector's x, y and z value from the provided array or array-like.
* @param array the source array or array-like.
* @param offset (optional) offset into the array. Default is 0.
*/
fromArray(array: number[] | ArrayLike<number>, offset?: number): this;
/**
* Returns an array [x, y, z], or copies x, y and z into the provided array.
* @param array (optional) array to store the vector to. If this is not provided, a new array will be created.
* @param offset (optional) optional offset into the array.
* @return The created or provided array.
*/
toArray(array?: number[], offset?: number): number[];
toArray(array?: Vector3Tuple, offset?: 0): Vector3Tuple;
/**
* Copies x, y and z into the provided array-like.
* @param array array-like to store the vector to.
* @param offset (optional) optional offset into the array-like.
* @return The provided array-like.
*/
toArray(array: ArrayLike<number>, offset?: number): ArrayLike<number>;
fromBufferAttribute(attribute: BufferAttribute | InterleavedBufferAttribute, index: number): this;
/**
* Sets this vector's x, y and z from Math.random
*/
random(): this;
randomDirection(): this;
/**
* Iterating through a Vector3 instance will yield its components (x, y, z) in the corresponding order.
*/
[Symbol.iterator](): Iterator<number>;
}
|
7467c4f61a1463436b7e54fb43e5e57ce954ce3c
|
TypeScript
|
miguelyoobic95/ngIfModalBug
|
/design-system/stencil/src/utils/pipes/currency/currency.pipe.ts
| 2.6875
| 3
|
import { Pipe } from '../base';
export class CurrencyPipe extends Pipe<number, string> {
transform(value: number, options: string = 'EUR'): string {
return value.toString() + ' ' + options;
}
}
|
b938fb59b5e920b5b5d4f25376b25dd8fb93681d
|
TypeScript
|
trangtt-1054/ts-web
|
/src/index.ts
| 2.890625
| 3
|
/* import { User } from "./models/User";
const user = User.buildUser({ id: 1 });
//set up event listener
user.on("change", () => {
console.log(user);
});
user.fetch();
import { User } from "./models/User";
// const collection = new Collection<User, UserProps>(
// "http://localhost:3000/users",
// (json: UserProps) => User.buildUser(json)
// ); ko nên initialize collection ở đây
const collection = User.buildUserCollection();
collection.on("change", () => {
console.log(collection);
});
collection.fetch(); */
/* import { UserEdit } from "./views/UserEdit";
import { User } from "./models/User";
//pass vào 1 cái element mà muốn render cái form ra cái element đấy
const user = User.buildUser({ name: "Jumong", age: 45 });
const root = document.getElementById("root");
if (root) {
//type guard vì strictNullCheck on
const userEdit = new UserEdit(root, user);
userEdit.render(); //chạy lại parcel.html
console.log(userEdit);
} else {
throw new Error("Root element not found");
}
*/
import { UserList } from "./views/UserList";
import { UserEdit } from "./views/UserEdit";
import { Collection } from "./models/Collection";
import { UserProps, User } from "./models/User";
const users = new Collection(
"http://localhost:3000/users",
(json: UserProps) => {
return User.buildUser(json);
}
);
//fetch all the users from json server and trigger 'change' event (mỗi lần fetch mới là render lại)
users.on("change", () => {
const root = document.getElementById("root");
if (root) {
new UserList(root, users).render();
}
});
users.fetch();
const singleUser = User.buildUser({ id: 1 });
const sub = document.getElementById("sub");
if (sub) {
new UserEdit(sub, singleUser).render();
}
|
d69a93c038ff06678e60177d9e617785bb3f14d1
|
TypeScript
|
scrum-gang/jobhub-web
|
/src/api/userAPI.ts
| 2.671875
| 3
|
import { AxiosPromise } from "axios";
import UserType from "../config/types/accountTypes";
import ILoginResponse from "../config/types/loginResponse";
import IUser from "../config/types/user";
import API from "./api";
enum UserEndpoints {
USERS = "/users",
SELF = "/users/self",
LOGIN = "/login",
LOGOUT = "/logout",
REGISTER = "/signup",
RESEND_EMAIL = "/resend"
}
class UserAPI {
private api: API;
constructor() {
this.api = new API("https://jobhub-authentication-staging.herokuapp.com");
this.api.createEntities(Object.values(UserEndpoints));
}
public setJWT = (token: string) => {
this.api.setJWT(token);
};
public clearJWT = () => {
this.api.clearJWT();
};
public login = (payload: { email: string; password: string }) => {
return this.api.endpoints[UserEndpoints.LOGIN]
.create(payload)
.then(({ data }) => {
this.api.setJWT(data.token);
return data as ILoginResponse;
});
};
public logout = () => {
return this.api.endpoints[UserEndpoints.LOGOUT].create({});
};
public register = (payload: {
email: string;
password: string;
type: UserType;
}) => {
return this.api.endpoints[UserEndpoints.REGISTER].create(payload);
};
public update = (payload: {
email: string;
password: string;
type: UserType;
}) => {
return this.api.endpoints[UserEndpoints.SELF].updateNoId(payload);
};
public delete = () => {
return this.api.endpoints[UserEndpoints.SELF].deleteNoId();
};
public getSelf = () => {
return this.api.endpoints[UserEndpoints.SELF].getAll() as AxiosPromise<
IUser
>;
};
public resendVerification = (payload: { email: string }) => {
return this.api.endpoints[UserEndpoints.RESEND_EMAIL].create(payload);
};
}
export default new UserAPI();
|
285c0929e0cef220ff4adeca759fa6bcf6797201
|
TypeScript
|
SingularityF/PixivWallpaper
|
/Client/PWF_Desktop/app/reducers/appInitializedReducer.ts
| 2.8125
| 3
|
interface ActionType {
type: string;
}
export default function appInitializedReducer(
state: Boolean = false,
action: ActionType
) {
switch (action.type) {
case 'INIT_DONE':
return true;
default:
return state;
}
}
|
994a91bf4822db8dcdbe259cb7f0146c9101740e
|
TypeScript
|
katiaRomanova/curso-angular
|
/ej-typescript/modulos/mascota.ts
| 3.046875
| 3
|
//export default Mascota;
// se puede hacer export delante de la clase,
class Mascota {
nombre: string;
tipo: string;
constructor(nombre: string, tipo: string = 'gato') {
this.nombre = nombre;
this.tipo = tipo;
}
}
let roky = new Mascota('Roky', 'perro');
//si vamos a exportar solo una cosa,
export default Mascota;
|
26c78b1a1bf5660f2f0bb0996eb2ee989078649b
|
TypeScript
|
koyadovic/dia-mobile
|
/src/components/food-selected/food-selected.ts
| 2.5625
| 3
|
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { FoodSelected, selection_kcal, weight, FoodDetailable } from '../../models/food-model';
import { style, state, animate, transition, trigger } from '@angular/animations';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'food-selected',
templateUrl: 'food-selected.html',
animations: [
trigger('fadeInOut', [
transition(':enter', [ // :enter is alias to 'void => *'
style({opacity: 0}),
animate(300, style({opacity: 1}))
]),
transition(':leave', [ // :leave is alias to '* => void'
animate(300, style({opacity: 0}))
])
])
]
})
export class FoodSelectedComponent {
/*
This component is for food selected, to show kcal, grams of carbs, proteins, etc. This also
allow users to modify the selection
*/
@Input() foodSelected: FoodSelected
@Input() showCarbs:boolean = false;
@Input() showProteins:boolean = false;
@Input() showFats:boolean = false;
@Input() showFiber:boolean = false;
@Input() showAlcohol:boolean = false;
@Input() showKCal:boolean = false;
@Output() foodChanges = new EventEmitter<any>();
@Output() foodMessage = new EventEmitter<string>();
@Output() unselectFood = new EventEmitter<any>();
@Output() selectingFood = new EventEmitter<boolean>();
selectionMode:boolean = false;
selectionModeFood: FoodSelected = null;
constructor(private translate: TranslateService,) {}
doClick(){ // selection
if(!this.selectionMode) {
this.openSelection();
}
}
openSelection() {
this.selectingFood.emit(true);
this.selectionModeFood = {
food: <FoodDetailable>this.foodSelected.food,
carb_g: 0,
protein_g: 0,
fat_g: 0,
fiber_g: 0,
alcohol_g: 0,
selection: "",
}
this.selectionMode = true;
}
selectionFinishedCallback(foodSelected: FoodSelected) {
this.translate.get('Modified the selected food').subscribe(
(message) => {
// food here it's a copy, not a reference
if(foodSelected !== null) {
this.foodMessage.emit(message);
this.foodChanges.emit();
}
setTimeout(() => { this.selectionMode = false; this.selectionModeFood = null; }, 100);
this.selectingFood.emit(false);
}
);
}
// useful for templates. Maybe we can code a pipe for this
round(n: number){ return Math.round(n * 10.) / 10.; }
selection(){
if(this.foodSelected.food.g_or_ml_per_unit > 0.0) {
return `${this.foodSelected.selection}u`;
} else {
return `${this.foodSelected.selection}g`;
}
}
kcal(){
return selection_kcal(this.foodSelected);
}
weight() {
return weight(this.foodSelected);
}
unselect(item){
item.close();
this.unselectFood.emit();
}
}
|
b29e37394f06a8ae5bb90b1b13ec745a44496ad6
|
TypeScript
|
pro-react233/fullStack01
|
/src/libs/rd-url-utils/api.ts
| 3.140625
| 3
|
export interface NoMatch {
isMatched: false;
}
export interface Match<TParams, TQueryString> {
isMatched: true;
params: TParams;
query?: TQueryString & { [key: string]: string };
}
export interface LocationDescriptor {
search?: string;
pathname: string;
}
export interface UrlPath<TParams, TQueryString> {
urlTemplate: string;
paramType: TParams;
queryType: TQueryString;
/**
* Checks if URL matches pattern specified on creating URL and extracts parameters and query if matched.
* @param url An URL to check
* @param exact If true method would check if pattern matched full URL, if false - only start of URL would be checked.
*/
match(url: string | LocationDescriptor, exact: boolean): NoMatch | Match<TParams, TQueryString>;
format(params: TParams, query?: any): string;
}
|
e0d616ccca4540dfc62cd8b7d7e426e03fe3a795
|
TypeScript
|
MRazvan/lib-workers
|
/src/pool/serialization.ts
| 2.640625
| 3
|
import { isNil, isString } from 'lodash';
import { isArray, isBoolean, isNumber } from 'util';
import { GetSerializers, ISerializer, SerializationHandlerKey } from './attributes/serializer';
import { SerializationError } from './errors/serialization.error';
import { getLog, Logger } from './logging';
export class Serializer {
private static readonly _log: Logger = getLog(`[${Serializer.name}]`);
public static serialize(obj: any): any {
if (isNil(obj) || isString(obj) || isNumber(obj) || isBoolean(obj)) return obj;
if (isArray(obj)) {
// TODO: Circular references, make this smarter
return obj.map(item => Serializer.serialize(item));
}
if (!obj.___WorkerMessageKey) {
Serializer._log(`Message not decorated with @Serialize. ${JSON.stringify(obj)}`);
return obj;
}
// Check to see if we have a serialization decorator
const cd = GetSerializers().find(wm => wm.name === obj.___WorkerMessageKey);
if (cd && cd.tags[SerializationHandlerKey]) {
try {
const handler = cd.tags[SerializationHandlerKey] as ISerializer;
const serializedData: any = handler.serialize(obj);
serializedData.___WorkerMessageKey = obj.___WorkerMessageKey;
serializedData.id = obj.id;
return serializedData;
} catch (err) {
Serializer._log(`Error serializing object '${obj.___WorkerMessageKey}'.`, err);
throw new SerializationError();
}
}
// Fallback
return {
...obj,
___WorkerMessageKey: obj.___WorkerMessageKey
};
}
public static deserialize(obj: any): any {
if (isNil(obj) || isString(obj) || isNumber(obj) || isBoolean(obj)) return obj;
if (isArray(obj)) {
// TODO: Circular references, make this smarter
return obj.map(item => Serializer.deserialize(item));
}
if (!obj.___WorkerMessageKey) {
return obj;
}
// Try and instantiate our object
const cd = GetSerializers().find(cd => cd.name === obj.___WorkerMessageKey);
if (!cd) {
Serializer._log(`Deserialization. ClassData Not found for '${obj.___WorkerMessageKey}'`);
throw new Error(`Deserialization. ClassData Not found for '${obj.___WorkerMessageKey}'`);
}
if (cd.tags[SerializationHandlerKey]) {
const handler = cd.tags[SerializationHandlerKey] as ISerializer;
return handler.deserialize(obj);
}
// Fallback construct the object
const instance = Reflect.construct(cd.target, []);
Object.assign(instance, obj);
return instance;
}
}
|
b0b4a39915045c1e0fc2807edad8fabe17ff5454
|
TypeScript
|
chrto/sandbox-composition-monad
|
/src/factory/functor.ts
| 3.328125
| 3
|
export interface IFunctor<T> {
lift: <I, O>(fcn: (v: I) => O) => IFunctor<O>;
done: () => T;
}
const Functor = <T>(value: T): IFunctor<T> => ({
lift: <I, O>(func: (v: I) => O): IFunctor<O> => Functor(func.apply(null, [value])),
done: (): T => value
});
export default Functor;
|
1b105019be6393fee20c66d8f73ff340eea1961b
|
TypeScript
|
ducnguyen96/ducnguyen96-apis-microservices
|
/api-gateway/src/graphql/types/common.interface.entity.ts
| 3.0625
| 3
|
import { InterfaceType, Field, ID, ObjectType, Int } from '@nestjs/graphql';
import { Type } from '@nestjs/common';
@InterfaceType({
description: 'Node',
})
export abstract class Node {
@Field(() => ID)
id: string;
}
@InterfaceType()
export abstract class Edge {
cursor?: string;
}
@ObjectType()
export class PageInfo {
startCursor?: string;
endCursor?: string;
hasPrevPage: boolean;
hasNextPage: boolean;
}
@ObjectType()
export class PaginationMeta {
@Field(() => Int)
itemCount: number;
@Field(() => Int)
totalItems: number;
@Field(() => Int)
itemsPerPage: number;
/**
* the total amount of pages in this paginator
*/
@Field(() => Int)
totalPages: number;
/**
* the current page this paginator "points" to
*/
@Field(() => Int)
currentPage: number;
next?: string;
previous?: string;
}
@ObjectType()
export class PaginationLinks {
/**
* a link to the "first" page
*/
@Field(() => String, { nullable: true })
first?: string;
/**
* a link to the "previous" page
*/
@Field(() => String, { nullable: true })
previous?: string;
/**
* a link to the "next" page
*/
@Field(() => String, { nullable: true })
next?: string;
/**
* a link to the "last" page
*/
@Field(() => String, { nullable: true })
last?: string;
}
@InterfaceType()
export abstract class Connection {
meta: PaginationMeta;
links: PaginationLinks;
}
@InterfaceType()
export abstract class CursorConnection {
@Field(() => Int)
totalCount: number;
pageInfo: PageInfo;
}
export function PaginationBase<T>(classRef: Type<T>): any {
@ObjectType({ isAbstract: true })
abstract class ConnectioneTypeType {
@Field((type) => PaginationMeta)
meta: PaginationMeta;
@Field((type) => PaginationLinks)
links: PaginationLinks;
@Field((type) => [classRef])
items: T[];
}
return ConnectioneTypeType;
}
export function PaginationCursor<T>(classRef: Type<T>): any {
@ObjectType(`${classRef.name}Edge`)
abstract class EdgeType {
@Field((type) => String)
cursor: string;
@Field((type) => classRef)
node: T;
}
@ObjectType({ isAbstract: true })
abstract class PaginatedType {
@Field((type) => [EdgeType], { nullable: true })
edges: EdgeType[];
@Field((type) => Int)
totalCount: number;
@Field((type) => PageInfo)
pageInfo: PageInfo;
}
return PaginatedType;
}
|
55e3ea5feee5042348240c69916fc580bf0159c5
|
TypeScript
|
wuerstle/EIA2
|
/Abschlussaufgabe/js/main.ts
| 3.09375
| 3
|
/*
Aufgabe: Abschlussaufgabe
Name: Lisa Würstle
Matrikel: 254072
Datum: 20.07.2017
Hiermit versichere ich, dass ich diesen Code selbst geschrieben habe. Er wurde nicht kopiert und auch nicht diktiert.
*/
namespace Abschlussaufgabe {
window.addEventListener("load", init);
export let context: CanvasRenderingContext2D;
//variable um Hintergrund zu speichern
let imgData: ImageData;
let click: number = 10;
let z: number = 0;
//Bubbles Class
let bubbles: Bubble[] = [];
//Animal Superclass with Subclasses for StarFish and LittleFish
export let animals: Animal[] = [];
//Parasite Class
let parasites: Parasite[] = [];
function init(): void {
let x: number = 0;
let y: number = 0;
let canvas: HTMLCanvasElement = document.getElementsByTagName("canvas")[0];
context = canvas.getContext("2d");
//background canvas
context.fillStyle = "#00BFFF";
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
//loop for bubbles
for (let i: number = 0; i < 20; i++) {
new Bubble(Math.random() * canvas.width, Math.random() * canvas.height).drawBubble();
}
//loop for starfish
for (let i: number = 0; i < 10; i++) {
let sf: StarFish = new StarFish(x, y);
sf.setRandomPosition();
sf.draw();
}
//loop for fish
for (let i: number = 0; i < 10; i++) {
let lf: LittleFish = new LittleFish(x, y);
lf.setRandomPosition();
lf.draw();
}
//save background
imgData = context.getImageData(0, 0, canvas.width, canvas.height);
//250 bubbles on random positions
createBubbles(250);
//Loop for Parasites
for (let i: number = 0; i <= 50; i++) {
let p: Parasite = new Parasite(750, 225); //start
parasites.push(p);
}
//EventListener for bubbles
canvas.addEventListener("click", addBubble);
//Smartphone and Tablet
canvas.addEventListener("touchstart", addBubble);
//EventListener for starFish
let seeStern: HTMLElement = document.getElementById("seestern");
seeStern.addEventListener("click", showInfoSeestern);
//Smartphone and Tablet
seeStern.addEventListener("touchstart", showInfoSeestern);
//EventListener for littleFish
let kleinerFisch: HTMLElement = document.getElementById("kleinerfisch");
kleinerFisch.addEventListener("click", showInfoFisch);
//Smartphone and Tablet
kleinerFisch.addEventListener("touchstart", showInfoFisch);
//EventListener for parasites
let parasite: HTMLElement = document.getElementById("parasite");
parasite.addEventListener("click", showInfoParasite);
//Smartphone and Tablet
parasite.addEventListener("touchstart", showInfoParasite);
//Animation
window.setTimeout(animate, 100);
}
function animate(): void {
context.putImageData(imgData, 0, 0);
//animation for bubbles
for (let i: number = 0; i < bubbles.length; i++) {
let b: Bubble = bubbles[i];
b.updateBubble();
}
//animation for animals
for (let i: number = 0; i < animals.length; i++) {
let a: Animal = animals[i];
a.updateAnimal();
}
//animation for parasites
for (let i: number = 0; i < parasites.length; i++) {
let p: Parasite = parasites[i];
p.updateParasite();
}
//Timeout
window.setTimeout(animate, 100);
}
//create bubbles
function createBubbles(_amount: number): void {
for (let i: number = 0; i < _amount; i++) {
let x: number = random(0, context.canvas.width);
let y: number = random(0, context.canvas.height);
createBubble(x, y);
}
}
//add 10 bubbles
function addBubble(_event: MouseEvent): void {
for (let i: number = 0; i < click; i++) {
let x: number = random(_event.offsetX - 100, _event.offsetX + 100);
let y: number = random(_event.offsetY - 100, _event.offsetY + 100);
createBubble(x, y);
}
console.log("addedBubbles");
}
//create one bubble
function createBubble(_x: number, _y: number): void {
let bubble: Bubble = new Bubble(_x, _y);
bubbles.push(bubble);
}
//random position
function random(_min: number, _max: number): number {
return Math.random() * (_max - _min) + _min;
}
//information starfish
function showInfoSeestern(): void {
console.log("testSeestern");
document.getElementById("infoSeestern").style.display = "block";
addStar();
}
//add one starfish on random position
function addStar(): void {
let sf: StarFish = new StarFish(this.x, this.y);
sf.draw();
animals.push(sf);
z++;
console.log("addedStarfish");
}
//information fish
function showInfoFisch(): void {
console.log("testFisch");
document.getElementById("infoFisch").style.display = "block";
addFish();
}
//add one fisch on random position
function addFish(): void {
let lf: LittleFish = new LittleFish(this.x, this.y);
lf.draw();
animals.push(lf);
z++;
console.log("addedFish");
}
//information parasite
function showInfoParasite(): void {
console.log("testParasite");
document.getElementById("infoParasite").style.display = "block";
addParasite();
}
//add new parasites on fixed position
function addParasite(): void {
let para: Parasite = new Parasite(100, 425);
parasites.push(para);
z++;
console.log("addedParasite");
}
}
|
8d5f1c26f08348b3518825b6968689116824979c
|
TypeScript
|
fernandoj92/ltm-learning-interface
|
/app/dashboard/test-cytoscape/model/cytoscapeNode.ts
| 2.703125
| 3
|
import { Node } from '../../../model/bayesianNetwork/dag/node'
export class CytoscapeNode{
data: CytoscapeNodeData
constructor(node: Node){
this.data = new CytoscapeNodeData(node.id, node.name)
}
}
class CytoscapeNodeData{
id: string;
name: string;
constructor(id:string, name:string){
this.id = id
this.name = name
}
}
|
67a517cd2813cb39b63bc563703ee906e688a821
|
TypeScript
|
alexanderyarm/sesame
|
/src/shared/components/Autocomplete/hooks/clickOutsideElement.ts
| 2.953125
| 3
|
import { MutableRefObject, useEffect, useRef } from "react";
const refStack: MutableRefObject<Element | null>[] = [];
export const useClickOutsideElement = (callback: () => void) => {
const ref = useRef<HTMLDivElement>(null);
useEffect((): ReturnType<React.EffectCallback> => {
refStack.push(ref);
const listener: EventListener = (event): void => {
// Do nothing if clicking ref's element or descendent elements
if (!ref.current || ref.current.contains(event.target as Node)) {
return;
}
if (refStack[refStack.length - 1] === ref) {
callback();
}
};
document.addEventListener("click", listener);
return (): void => {
refStack.pop();
document.removeEventListener("click", listener);
};
}, [ref, callback]);
return ref;
};
|
dbc0c91ac0c0702290e6d8424930b924633e9604
|
TypeScript
|
boterojuanpa/hackaton-proteccion
|
/frontend/src/app/shared/model/usuario.model.ts
| 2.8125
| 3
|
export class Usuario {
public nombre: string;
public cedula: number;
constructor(nombre: string, cedula: number) {
this.nombre = nombre;
this.cedula = cedula;
}
}
|
4bf10ad4e3bec7bb878c67b08c7090f2e4dca1fc
|
TypeScript
|
typescript-eslint/typescript-eslint
|
/packages/eslint-plugin/src/rules/naming-convention-utils/parse-options.ts
| 2.578125
| 3
|
import * as util from '../../util';
import {
MetaSelectors,
Modifiers,
PredefinedFormats,
Selectors,
TypeModifiers,
UnderscoreOptions,
} from './enums';
import { isMetaSelector } from './shared';
import type {
Context,
NormalizedSelector,
ParsedOptions,
Selector,
} from './types';
import { createValidator } from './validator';
function normalizeOption(option: Selector): NormalizedSelector[] {
let weight = 0;
option.modifiers?.forEach(mod => {
weight |= Modifiers[mod];
});
option.types?.forEach(mod => {
weight |= TypeModifiers[mod];
});
// give selectors with a filter the _highest_ priority
if (option.filter) {
weight |= 1 << 30;
}
const normalizedOption = {
// format options
format: option.format ? option.format.map(f => PredefinedFormats[f]) : null,
custom: option.custom
? {
regex: new RegExp(option.custom.regex, 'u'),
match: option.custom.match,
}
: null,
leadingUnderscore:
option.leadingUnderscore !== undefined
? UnderscoreOptions[option.leadingUnderscore]
: null,
trailingUnderscore:
option.trailingUnderscore !== undefined
? UnderscoreOptions[option.trailingUnderscore]
: null,
prefix: option.prefix && option.prefix.length > 0 ? option.prefix : null,
suffix: option.suffix && option.suffix.length > 0 ? option.suffix : null,
modifiers: option.modifiers?.map(m => Modifiers[m]) ?? null,
types: option.types?.map(m => TypeModifiers[m]) ?? null,
filter:
option.filter !== undefined
? typeof option.filter === 'string'
? {
regex: new RegExp(option.filter, 'u'),
match: true,
}
: {
regex: new RegExp(option.filter.regex, 'u'),
match: option.filter.match,
}
: null,
// calculated ordering weight based on modifiers
modifierWeight: weight,
};
const selectors = Array.isArray(option.selector)
? option.selector
: [option.selector];
return selectors.map(selector => ({
selector: isMetaSelector(selector)
? MetaSelectors[selector]
: Selectors[selector],
...normalizedOption,
}));
}
function parseOptions(context: Context): ParsedOptions {
const normalizedOptions = context.options
.map(opt => normalizeOption(opt))
.reduce((acc, val) => acc.concat(val), []);
const result = util.getEnumNames(Selectors).reduce((acc, k) => {
acc[k] = createValidator(k, context, normalizedOptions);
return acc;
}, {} as ParsedOptions);
return result;
}
export { parseOptions };
|
477bbdcd68db5570924c8b3d33a7dcb74677c748
|
TypeScript
|
DaYeSquad/json-ts-mapper
|
/src/object-mapper.ts
| 2.96875
| 3
|
// Copyright 2018 Frank Lin (lin.xiaoe.f@gmail.com). All rights reserved.
// Use of this source code is governed a license that can be found in the LICENSE file.
export interface JsonField {
name: string;
jsonKey: string;
serializer?: (value: any) => any;
}
/**
* Mapping for object.
*/
export class ObjectMapper {
private _jsonDefinitions: Map<{ new(): any }, JsonField[]> = new Map();
static deserialize(cls: { new(): any }, json: any): any {
/* tslint:disable-next-line */
return objectMapper.deserialize(cls, json);
}
deserialize<T>(cls: { new(): T }, json: any): T {
const fields: JsonField[] = this._jsonDefinitions.get(cls);
const instance: any = new cls();
for (const field of fields) {
if (field.serializer) {
instance[field.name] = field.serializer(json);
continue;
}
const maybeMultipleLevelKey: string[] = field.jsonKey.split("."); // 支持根据点符号(.)切割层级
if (maybeMultipleLevelKey.length > 0) {
let jsonRef = json;
for (const key of maybeMultipleLevelKey) {
if (jsonRef[key] !== undefined) {
jsonRef = jsonRef[key];
} else {
return instance;
}
}
instance[field.name] = jsonRef;
} else {
instance[field.name] = json[field.jsonKey];
}
}
return instance;
}
addJsonProperty(cls: { new(): any }, property: JsonField): void {
if (!this._jsonDefinitions.get(cls)) {
this._jsonDefinitions.set(cls, []);
}
this._jsonDefinitions.get(cls).push(property);
}
}
export const objectMapper = new ObjectMapper();
|
7d3e62e0be999b00a4064f736d83c9284055da9b
|
TypeScript
|
younaAnn/playwright-seed
|
/src/page-objects/ui-elements/input.ts
| 2.734375
| 3
|
import { Timeouts } from '../../shared/timeouts';
import { UIElement } from '../base/ui-element';
export class Input extends UIElement {
async fill(value: string, options?: Record<string, any>): Promise<void> {
const el = await this.wait();
return el.fill(value, options);
}
async press(key: string, options?: Record<string, any>): Promise<void> {
const el = await this.wait();
return el.press(key, options);
}
async getValue(timeout?: number): Promise<string> {
const defaultTimeout = timeout ?? Timeouts.FiveSecondsTimeout;
await this.wait({ timeout: defaultTimeout });
return this.page.$eval(this.selector, (el) => (el as HTMLInputElement).value);
}
}
|
9481ca12f2bb31e2cf1b737e67e0f943c793c181
|
TypeScript
|
DistinctionWei/ts-utility-plugins
|
/src/ddzy/__tests__/array/pullAll.test.ts
| 3.359375
| 3
|
import { pullAll } from "../../utility/array/pullAll";
describe('pullAll tests...', () => {
test('Method pullAll should receive an array composed of number and return the filtered array', () => {
const received = {
origin: [1, 2, 3, 1, 2, 3],
selector: [2, 3],
};
const expected = {
isEqual: true,
result: [1, 1],
};
const result = pullAll<number>(received.origin, received.selector);
expect(result === received.origin).toBe(expected.isEqual);
result.forEach((v, i) => {
expect(v).toBe(expected.result[i]);
});
});
test('Method pullAll should receive an array composed of plain object and return the filtered array', () => {
interface IOriginParams {
name: string,
age: number,
};
const received = {
origin: [
{
name: 'duan',
age: 21,
},
{
name: 'zhao',
age: 22,
},
{
name: 'duan',
age: 21,
},
],
selector: [
{
name: 'duan',
age: 21,
},
],
};
const expected = {
isEqual: true,
result: [
{
name: 'duan',
age: 21,
},
{
name: 'zhao',
age: 22,
},
{
name: 'duan',
age: 21,
},
],
};
const result = pullAll<IOriginParams>(received.origin, received.selector);
expect(result === received.origin).toBe(expected.isEqual);
expect(result.length).toBe(expected.result.length);
});
test('Method pullAll should receive an array composed of mixed value and return the filtered array', () => {
const received = {
origin: [
0,
19980808,
'duanzhaoyang',
false,
null,
undefined,
Symbol('a'),
function () { },
{},
[],
],
selector: [false, undefined, 19980808, []],
};
const expected = {
isEqual: true,
result: [
0,
'duanzhaoyang',
null,
Symbol('a'),
function () { },
{},
[],
],
};
const result = pullAll<any>(received.origin, received.selector);
expect(result === received.origin).toBe(expected.isEqual);
expect(result.length).toBe(expected.result.length);
});
});
|
0af37b417fa531152bdaff113ba28d6355504f74
|
TypeScript
|
tarngerine/blogring
|
/src/lib/index.ts
| 2.625
| 3
|
import { filterHueRotate, formatRgb, parse } from 'culori';
import { useEffect, useRef, useState } from 'react';
import { Vec } from '../types';
// lerp function between two ranges
export function lerp(value: number, r1: [number, number], r2: [number, number]): number {
return ((value - r1[0]) * (r2[1] - r2[0])) / (r1[1] - r1[0]) + r2[0];
}
// Stores the size of an element
export function useSize() {
const ref = useRef<HTMLDivElement>(null);
const [size, setSize] = useState<Vec>({ x: 0, y: 0 });
const [observer] = useState(
new ResizeObserver((entries) => {
const entry = entries[0];
if (entry.contentRect) {
setSize({ x: entry.contentRect.width, y: entry.contentRect.height });
}
}),
);
useEffect(() => {
const el = ref.current;
if (!el) return;
observer.observe(el);
}, [observer]);
return { size, ref } as const;
}
// Generate a random color in our palette
export const BASE_COLOR = 'salmon'; // sets the SV for our colors
export function randomColor() {
const hueRotate = filterHueRotate(Math.random() * 360);
return formatRgb(hueRotate(parse(BASE_COLOR)));
}
export { SocketProvider } from './ws';
|
ba77e51bbdf5d033d4134147bf0d2c5ce3e2ce7f
|
TypeScript
|
rafael-g-depaulo/discord-bot
|
/libs/ol-fantasy-battle/src/Models/PlayerUser/index.test.ts
| 2.984375
| 3
|
import mockAttributes from "Utils/mockAttributes"
import { useDbConnection } from "@discord-bot/mongo"
import PcModel, { Pc } from "Models/PlayerCharacter"
import PlayerUserModel, { PlayerUser } from "./index"
import { createPlayerUserProps } from "./statics/create"
describe("PlayerUser Model", () => {
useDbConnection("PlayerUser")
const userInfo: PlayerUser = {
userId: "1234567890",
username: "test",
characters: []
}
describe("CRUD", () => {
it("creates", async () => {
const user = new PlayerUserModel(userInfo)
const userSaved = await user.save()
expect(user.userId).toStrictEqual(userSaved?.userId)
expect(user._id).toStrictEqual(userSaved?._id)
expect(userInfo.userId).toStrictEqual(userSaved?.userId)
})
it("reads", async () => {
const user = new PlayerUserModel(userInfo)
await user.save()
const readPlayerUser = await PlayerUserModel.findById(user._id)
expect(user._id).toStrictEqual(readPlayerUser?._id)
})
it("updates", async () => {
const user = new PlayerUserModel(userInfo)
await user.save()
const read1 = await PlayerUserModel.findById(user._id)
user.userId = "69696969"
await user.save()
const read2 = await PlayerUserModel.findById(user._id)
expect(read1?.userId).toEqual("1234567890")
expect(read2?.userId).toEqual("69696969")
})
it("deletes", async () => {
const user = new PlayerUserModel(userInfo)
await user.save()
const read = await PlayerUserModel.findById(user._id)
expect(read).not.toBe(null)
await user.delete()
const deleted = await PlayerUserModel.findById(user._id)
expect(deleted).toBe(null)
})
})
describe("relation: characters", () => {
it('works', async () => {
// create user
const user = new PlayerUserModel(userInfo)
// create character
const charProps: Pc = {
name: "test char",
attributes: mockAttributes(),
}
const character = new PcModel(charProps)
// add character to user's characters
user.characters.push(character)
// save user
await user.save()
// retrieve user
const savedUser = await PlayerUserModel.findOne({ _id: user._id })
// check that character is saved as part of user schema (as a sub-document)
expect(savedUser?.characters[0]._id).toEqual(character._id)
expect(savedUser?.characters[0].name).toEqual(character.name)
})
})
describe("statics", () => {
describe('.createUser()', () => {
it('throws if bad props', () => {
expect(() => PlayerUserModel.createUser({} as createPlayerUserProps)).toThrowError(`Fantasy Battle: createCharacter(): username prop missing or empty`)
expect(() => PlayerUserModel.createUser({ username: true } as unknown as createPlayerUserProps)).toThrowError(`Fantasy Battle: createCharacter(): username prop missing or empty`)
expect(() => PlayerUserModel.createUser({ username: "" } as createPlayerUserProps)).toThrowError(`Fantasy Battle: createCharacter(): username prop missing or empty`)
expect(() => PlayerUserModel.createUser({ username: "asd", userId: {} } as unknown as createPlayerUserProps)).toThrowError(`Fantasy Battle: createCharacter(): userId prop missing or empty`)
expect(() => PlayerUserModel.createUser({ username: "asd", userId: "" } as createPlayerUserProps)).toThrowError(`Fantasy Battle: createCharacter(): userId prop missing or empty`)
})
it('allows creating a new user', async () => {
const user = PlayerUserModel.createUser({ userId: "420", username: "testUsername" })
// check that the character was added to user
expect(user.username).toBe("testUsername")
expect(user.userId).toBe("420")
expect(user.characters.length).toBe(0)
})
})
describe(".getUser()", () => {
it("works when given a correct userId", async () => {
const user = new PlayerUserModel(userInfo)
const userSaved = await user.save()
const fetchedUser = await PlayerUserModel.getUser(userInfo.userId)
expect(fetchedUser?.userId).toBe(userSaved.userId)
expect(fetchedUser?.userId).toBe(userInfo.userId)
})
it('returns null when given an incorrect userId', async () => {
const fetchedUser = await PlayerUserModel.getUser(userInfo.userId)
expect(fetchedUser).toBe(null)
})
})
describe(".getOrCreate()", () => {
it("retrieves an existing user", async () => {
const createdUser = PlayerUserModel.createUser(userInfo)
await createdUser.save()
const fetchedUser = await PlayerUserModel.getOrCreate(userInfo)
expect(fetchedUser.userId).toBe(userInfo.userId)
expect(fetchedUser.username).toBe(userInfo.username)
expect(await PlayerUserModel.countDocuments()).toBe(1)
})
it('creates a new user', async () => {
expect(await PlayerUserModel.countDocuments()).toBe(0)
const fetchedUser = await PlayerUserModel.getOrCreate(userInfo)
expect(fetchedUser.userId).toBe(userInfo.userId)
expect(fetchedUser.username).toBe(userInfo.username)
expect(await PlayerUserModel.countDocuments()).toBe(1)
})
})
})
describe("methods", () => {
describe(".addCharacter()", () => {
it("works", () => {
const user = PlayerUserModel.createUser({ username: "userTest", userId: "420" })
expect(user.characters.length).toBe(0)
user.addCharacter(PcModel.createCharacter({ name: "Allor" }))
expect(user.characters.length).toBe(1)
expect(user.characters[0]).toMatchObject({ name: "Allor" })
})
})
describe(".removeCharacter()", () => {
it('allows removing a character', async () => {
const user = PlayerUserModel.createUser({ username: "userTest", userId: "420" })
// add character
const allor = PcModel.createCharacter({ name: "Allor" })
user.addCharacter(allor)
// check that the character was removed from user
expect(user.characters[0].name).toBe("Allor")
expect(user.characters.length).toBe(1)
expect(user.activeCharIndex).toBe(0)
// remove character
user.removeCharacter(allor)
// check that the character was removed from user
expect(user.characters.length).toBe(0)
expect(user.activeCharIndex).toBe(undefined)
})
it('resets the characterIndex', () => {
const user = PlayerUserModel.createUser({ username: "userTest", userId: "420" })
// add character
const allor = PcModel.createCharacter({ name: "Allor" })
const horu = PcModel.createCharacter({ name: "Horu" })
user.addCharacter(allor)
user.addCharacter(horu)
// check that the character was removed from user
expect(user.characters.length).toBe(2)
expect(user.characters[0].name).toBe("Allor")
expect(user.characters[1].name).toBe("Horu")
expect(user.activeCharIndex).toBe(0)
// remove character
user.removeCharacter(allor)
// check that the character was removed from user
expect(user.characters.length).toBe(1)
expect(user.activeCharIndex).toBe(0)
// remove character
user.removeCharacter(horu)
// check that the character was removed from user
expect(user.characters.length).toBe(0)
expect(user.activeCharIndex).toBe(undefined)
})
})
describe(".getCharacter()", () => {
it('allows getting a character by fullname', async () => {
const user = PlayerUserModel.createUser({ userId: "123456789", username: "usernameTest" })
// add character
user.addCharacter(PcModel.createCharacter({ name: "Allor Aglon" }))
const allor = user.getCharacter("Allor Aglon")
// check that the character was added to user
expect(allor?.name).toBe("Allor Aglon")
})
it(`doesn't care about CaSe`, async () => {
const user = PlayerUserModel.createUser({ userId: "123456789", username: "usernameTest" })
// add character
user.addCharacter(PcModel.createCharacter({ name: "Allor Aglon" }))
const allor = user.getCharacter("ALLOR aglon")
// check that the character was added to user
expect(allor?.name).toBe("Allor Aglon")
})
it(`works with substrings of the full name`, async () => {
const user = PlayerUserModel.createUser({ userId: "123456789", username: "usernameTest" })
// add character
user.addCharacter(PcModel.createCharacter({ name: "Allor Aglon" }))
const allor1 = user.getCharacter("allor")
const allor2 = user.getCharacter("aglon")
// check that the character was added to user
expect(allor1?.name).toBe("Allor Aglon")
expect(allor2?.name).toBe("Allor Aglon")
})
})
})
})
|
595423ef4c79eb2cc37a3ff6ac903ca18d32e08e
|
TypeScript
|
Gimorhee/prep-repo
|
/November2019/Typescript/greeter.ts
| 3.703125
| 4
|
class Student {
fullName: string;
constructor(public firstName: string, public middleInitial: string, public lastName: string) {
this.fullName = firstName + " " + middleInitial + " " + lastName
}
}
interface Person {
firstName: string;
lastName: string;
}
function greeter(person: Person) {
return "Hello, " + person.firstName + " " + person.lastName;
}
let user = { firstName: "Danny", lastName: "Rhee"};
document.body.textContent = greeter(user);
// ------------------------------------------------------------------- //
let notSure : any; notSure = 3;
let isDone : boolean = false;
let list : number[] = [ 1, 2, 3];
let x : [string, number] = ["1", 2];
enum Color { Red = 1, Green, Yellow }
let c : Color = Color.Red;
let colorName : string = Color[2];
declare function create(o: object | null) : void;
create({ pop: 0 });
create(null);
let someValue : any = "This is String";
let strLength1 : number = (<string>someValue).length;
let strLength2 : number = (someValue as string).length;
|
24f647f841ed450fcda9a677010cf897da14b5d1
|
TypeScript
|
simonxmh/restaurant-menu-builder
|
/src/ts/utils/Interfaces.ts
| 3.140625
| 3
|
import MenuItem from '../models/MenuItem';
import {
Action,
Store,
Dispatch
} from 'redux';
// Format of a menu item loaded from the API:
export interface IMenuItemRaw {
// Which category to put this food item under:
Category: string,
// Name of the menu item:
Name: string,
// Description of the menu item. Usually the ingredients.
Description: string,
// Price: In dollars:
Price: number,
// Sometimes food can contain foodstuffs that are undercooked, like a
// mediumrare steak, which restaurants must report by law. 0 or 1
"Undercooked Warning": number,
// 0 or 1:
Vegetarian: number
}
export interface IMenuItemMetaData {
// For these properties, see the definition of IMenuItemRaw:
category: string
name: string
description: string
price: number
isUndercooked: boolean
isVegetarian: boolean
}
// Interface for a parsed menu item (minus the id which is not related to
// the content of that item). The difference between this and IMenuItemRaw is
// that only the parsers will interact with IMenuItemRaw whereas the rest of the
// application will use this interface.
export interface IMenuItem extends IMenuItemMetaData {
// Whether this item is selected to be displayed on the menu or not. By
// default, all newly added items are selected:
isSelected: boolean
}
export interface IMenuItemSerialized extends IMenuItem {
id: string
}
/** Interfaces related to the Redux store */
// Part of the store concerning fetching status:
export interface IStoreFetchStatus {
// Whether we're in the middle of a fetch
isFetching: boolean,
// Error message if there was one:
message: string
}
// Structure of the Redux store:
export interface IStoreState {
// The list of all items:
items: MenuItem[]
fetchStatus: IStoreFetchStatus
}
// Structure of the redux store while stored in localStorage. Because this structure
// only consists of primitive data types, it can be `JSON.stringify`ed and stored
// in `localStorage`:
export interface IStoreStateSerialized {
items: IMenuItemSerialized[]
}
/** End of interfaces for the Redux store */
// The context argument to all container components:
export interface IContext {
store: Store<IStoreState>
}
/** Typings for actions */
// All action types in this application:
export enum ActionType {
ADD_ITEM,
REMOVE_ITEM,
TOGGLE_SELECT,
// Signal the start of a fetch, either remotely or locally. Used to display
// loading spinner:
FETCH_BEGIN,
// Signal the failure of a fetch so that an error message can be displayed:
FETCH_FAILURE,
// Signal success of a fetch, either remotely or locally. Used to update the
// content of the store and replace the loading spinner with displayed data:
FETCH_SUCCESS_REMOTE,
FETCH_SUCESS_LOCAL,
}
// Analytics-related interfaces:
// The type variable `T` is the type of the analytics payload.
export interface IAnalyticsPayload<T> {
info: T
}
export interface IAnalyticsAction<T> {
type: string,
payload: IAnalyticsPayload<T>
}
// Actions that go through analytics:
export interface ITrackableAction<T> {
meta: {
analytics: IAnalyticsAction<T>
}
}
// Actions whose only purpose is to notification e.g. start of a fetch:
export interface IActionNotify {
type: ActionType
}
export interface IActionFetchFailure extends ITrackableAction<string> {
type: ActionType,
message: string
}
// Actions that change existing items:
export interface IActionModify extends Action, ITrackableAction<string> {
type: ActionType
id: string
}
// Action to add new item:
export interface IActionAdd extends Action, ITrackableAction<IMenuItemMetaData> {
type: ActionType
data: IMenuItemMetaData
}
export interface IActionReceiveItemsFromAPI extends Action, ITrackableAction<IMenuItemRaw[]> {
type: ActionType
data: IMenuItemRaw[]
}
export interface IActionReceiveItemsFromLocal extends Action, ITrackableAction<MenuItem[]> {
type: ActionType
data: MenuItem[]
}
export type IAction = IActionModify | IActionAdd | IActionReceiveItemsFromAPI |
IActionReceiveItemsFromLocal | IActionNotify | IActionFetchFailure;
export type IThunk<T> = () => (dispatch: Dispatch<IStoreState>, getState?: () => T) => any;
/** End of typings for actions */
|
3db5addf4b2b4688ab16992fd27276c41a97e471
|
TypeScript
|
nkescobar/node-fundamentals
|
/02-fundamentos/callbacks.ts
| 3.421875
| 3
|
setTimeout(() => {
console.log('hola mundo');
}, 1000);
const getUsuarioById = (id: number, callback: Function) => {
const usuario = {
id,
nombre: 'Nasly'
};
setTimeout(()=> {
callback(usuario);
},1500);
};
// Callbacks Una funcion que se manda como argumento a otra funcion
getUsuarioById(10, (usuario: any) => {
console.log('Hola ', usuario.nombre.toUpperCase());
});
|
144089d6f74f6ec46e543cfd618e58dbd8875f00
|
TypeScript
|
Jerell/fams
|
/public/model/__tests__/node.ts
| 3.15625
| 3
|
import Node from '../node'
describe('Constructor - initial properties', () => {
it('should have a name', () => {
const node = new Node()
expect(node.name).toBeTruthy()
})
it('should have an x position', () => {
const node = new Node()
expect(node.x).not.toBeUndefined()
})
it('should have an elevation', () => {
const node = new Node()
expect(node.elevation).not.toBeUndefined()
})
it('should have a pressure', () => {
const node = new Node()
expect(node.pressure).not.toBeUndefined()
})
it('should have a temperature', () => {
const node = new Node()
expect(node.temperature).not.toBeUndefined()
})
it('should have an inflow value', () => {
const node = new Node()
expect(node.flow.in).not.toBeUndefined()
})
it('should have an outflow value', () => {
const node = new Node()
expect(node.flow.out).not.toBeUndefined()
})
it('should have a meter property that is false', () => {
const node = new Node()
expect(node.meter).toBe(false)
})
})
describe('Constructor - receiving properties', () => {
it('should accept a name', () => {
const node = new Node({ name: 'michael' })
expect(node.name).toBe('michael')
})
it('should accept an x position', () => {
const node = new Node({ x: 1 })
expect(node.x).toBe(1)
})
it('should accept an elevation value', () => {
const node = new Node({ elevation: 1 })
expect(node.elevation).toBe(1)
})
it('should accept a pressure value', () => {
const node = new Node({ pressure: 1 })
expect(node.pressure).toBe(1)
})
it('should accept a temperature value', () => {
const node = new Node({ temperature: 1 })
expect(node.temperature).toBe(1)
})
it('should accept a `flow.in` value', () => {
const node = new Node({ flow: { in: 1 } })
expect(node.inflow).toBe(1)
})
it('should accept a `flow.out` value', () => {
const node = new Node({ flow: { out: 1 } })
expect(node.outflow).toBe(1)
})
})
describe('Flow getters and setters', () => {
it('should return the same value for `node.inflow` and `node.flow.in`', () => {
const node = new Node({ flow: { in: 1 } })
expect(node.inflow).toEqual(node.flow.in)
})
it('should return the same value for `node.outflow` and `node.flow.out`', () => {
const node = new Node({ flow: { out: 1 } })
expect(node.outflow).toEqual(node.flow.out)
})
it('should update the outflow value when inflow is set', () => {
const node = new Node()
node.inflow = 1
expect(node.inflow).toEqual(node.outflow)
})
it('should not update the outflow value when constructed with a `flow.in` value', () => {
const node = new Node({ flow: { in: 1 } })
expect(node.inflow).not.toEqual(node.outflow)
})
})
describe('Pressure', () => {
it('should update when reassigned', () => {
const node = new Node()
node.pressure = 1
expect(node.pressure).toBe(1)
})
})
describe('Type', () => {
it('should have a default type of `closed`', () => {
const node = new Node()
expect(node.type).toBe('closed')
})
it('should have a type of `source` when its only flow value is `out`', () => {
const node = new Node({ flow: { out: 1 } })
expect(node.type).toBe('source')
})
it('should have a type of `destination` when its only flow value is `in`', () => {
const node = new Node({ flow: { in: 1 } })
expect(node.type).toBe('destination')
})
it('should have a type of `internal` when its inflow and outflow are equal and non-zero', () => {
const node = new Node({ flow: { in: 1, out: 1 } })
expect(node.type).toBe('internal')
})
})
describe('Flow', () => {
it('should update outflow to match when inflow changes', () => {
const node = new Node()
node.inflow = 1
expect(node.outflow).toBe(1)
})
})
describe('Density', () => {
it('should return 2.4 for T=220, P=100000', () => {
const node = new Node({ temperature: 220, pressure: 100000 })
expect(node.density).toBeCloseTo(2.405)
})
it('should return 2.2 for T=240, P=100000', () => {
const node = new Node({ temperature: 240, pressure: 100000 })
expect(node.density).toBeCloseTo(2.2)
})
})
describe('Viscosity', () => {
it('should return 0.000018 for T=373', () => {
const node = new Node({ temperature: 373 })
expect(node.viscosity).toBeCloseTo(0.000018)
})
it('should return 0.000008 for T=173', () => {
const node = new Node({ temperature: 173 })
expect(node.viscosity).toBeCloseTo(0.000008)
})
})
describe('Meter', () => {
it('should be true after `this.setMeter` is called', () => {
const node = new Node()
node.setMeter()
expect(node.meter).toBe(true)
})
})
|
4eaa35e71ef19834035f219ee7841981c1bbf3ea
|
TypeScript
|
Silence-dream/Study-Note
|
/杂乱的代码/javascript/01-链表.ts
| 3.703125
| 4
|
interface node<T> {
node: node<T> | null;
next: T | null;
}
class LinkedList<T> {
// 链表头部
private head: node<T> | null;
// 链表长度
private size: number;
// 链表尾部
private tail: node<T> | null;
constructor() {
this.head = null;
this.size = 0;
this.tail = null;
}
addFirst(item: T) {
let node = new Node(item);
if (this.head == null) {
this.head = node;
}
}
}
class Node<T> implements node<T> {
node: node<T> | null;
next: T | null;
constructor(data: node<T>) {
this.node = data;
this.next = null;
}
}
let linkedList = new LinkedList();
linkedList.addFirst(1);
console.log(linkedList);
export {};
|
4d710678fa3ece45883bdc6352e5a82d3cfaf0f1
|
TypeScript
|
sam-barker/ts
|
/src/lib/number.spec.ts
| 3.03125
| 3
|
import test, { ExecutionContext } from 'ava';
import { double } from './number';
function testDouble(
t: ExecutionContext,
input: number,
expected: number
): void {
t.is(double(input), expected);
}
testDouble.title = (
providedTitle: string = '',
input: number,
expected: number
) =>
`${providedTitle} should correctly double ${input} to make ${expected}`.trim();
test(testDouble, 2, 4);
test(testDouble, 4, 8);
test(testDouble, 0, 0);
test(testDouble, -1, -2);
|
2aed46233793177243e16a523ac6be398ba3eafa
|
TypeScript
|
hotsoycandy/hotsoyblog
|
/src/core/common/errors/CommonError.ts
| 2.84375
| 3
|
export abstract class CommonError extends Error {
constructor (message: string, resErrorMessage?: string) {
super(message)
this.resErrorMessage = resErrorMessage ?? message
}
// http api response properties
readonly abstract resErrorCode: string
resErrorMessage: string
readonly abstract resStatusCode: number
}
|
ee9aadb44353299365f79c5e12744d51981c9412
|
TypeScript
|
ZephyrAndMoon/best-utils
|
/src/addClass.ts
| 3.109375
| 3
|
import hasClass from './hasClass'
/**
* addClass 添加class类名
* @version 1.0.2
* @param el THML元素
* @param cls class类名
* @category addClass
* @example
* ``` typescript
* addClass(el, 'dom-class-wrap')
* ```
*/
const addClass = (el: HTMLElement, cls: string): void => {
if (!el) return
let curClass = el.className
const classes = (cls || '').split(' ')
for (let i = 0, j = classes.length; i < j; i++) {
const clsName = classes[i]
if (!clsName) continue
if (el.classList) {
el.classList.add(clsName)
} else if (!hasClass(el, clsName)) {
curClass += ' ' + clsName
}
}
if (!el.classList) {
el.className = curClass
}
}
export default addClass
|
a48677d5433b6964cac50eb33b616109f6c16182
|
TypeScript
|
kanbang/battle-city-mp
|
/actions/Action.ts
| 3.0625
| 3
|
export enum ActionType {
ANY = 'any',
BUTTON_PRESS = 'button-press',
}
export interface ActionOptions {
timestamp: number;
type?: ActionType;
}
export class Action {
timestamp: number;
type: ActionType;
constructor(options: ActionOptions) {
this.timestamp = options.timestamp;
this.type = options.type ?? ActionType.ANY;
}
toOptions(): ActionOptions {
return {
type: this.type,
timestamp: this.timestamp,
};
}
}
|
6460a969cc3a84d69016191672b17ccb2960db22
|
TypeScript
|
ruslanguns/nest-mongoose-crud
|
/src/talents/talents.controller.ts
| 2.578125
| 3
|
import { Controller, Get, Post, Put, Delete, Param, Body } from '@nestjs/common';
import { TalentsDto } from './talents.dto';
import { ValidateObjectId } from '../_shared/pipes/validate-object-id.pipe';
import { TalentsService } from './talents.service';
import { HttpException } from '@nestjs/common/exceptions/http.exception';
@Controller('talents')
export class TalentsController {
constructor(
private readonly talentsService: TalentsService,
) { }
/**
* Get list of talents
*/
@Get()
async getTalents() {
return await this.talentsService.getTalents();
}
/**
* Get Talent by Id
*/
@Get(':talentId')
async getTalentById(
@Param('talentId', new ValidateObjectId()) talentId,
) {
return await this.talentsService.getTalentById(talentId);
}
/**
* Create a new talent
*/
@Post()
async createTalent(
@Body() talentsDto: TalentsDto,
) {
return await this.talentsService.createTalent(talentsDto);
}
/**
* Remplace a talent
*/
@Put(':talentId')
async updateTalent(
@Param('talentId', new ValidateObjectId()) talentId,
@Body() talentsDto: TalentsDto,
) {
return await this.talentsService.updateTalent(talentId, talentsDto);
}
/**
* Delete talent
*/
@Delete(':talentId')
async deleteTalent(
@Param('talentId', new ValidateObjectId()) talentId,
) {
await this.talentsService.deleteTalent(talentId);
throw new HttpException('Talent deleted', 200);
}
}
|
17c7a9db550a3c1a4a693f258b7006a3688a0e0b
|
TypeScript
|
OptimalBits/ground
|
/lib/container/sequence.ts
| 2.65625
| 3
|
/**
Ground Web Framework (c) 2011-2013 Optimal Bits Sweden AB
MIT Licensed.
*/
/**
Sequence Class
This class represents a ordered collection of models.
The sequence supports persistent storage, offline and
automatic client<->server synchronization.
Events:
*/
/// <reference path="container.ts" />
/// <reference path="../log.ts" />
/// <reference path="../using.ts" />
/// <reference path="../base.ts" />
/// <reference path="../model.ts" />
/// <reference path="../overload.ts" />
/// <reference path="../mutex.ts" />
module Gnd {
export interface ISeqModel {
model: Model;
id: string;
};
export interface SequenceEvents
{
on(evt: string, listener: (...args: any[]) => void): Base;
/**
* Fired when any model in the collection changes any property.
*
* @event updated:
* @param item {Model}
* @param args {any}
*/
on(evt: 'updated:', listener: (item: Model, args:any) => void): Base;
/**
* Fired when a model has been inserted in the sequence
*
* @event inserted:
* @param item {Model}
* @param index {Number}
*/
on(evt: 'inserted:', listener: (item: Model, index: number) => void): Base;
/**
* Fired when a model has been removed from the sequence
*
* @event removed:
* @param item {Model}
* @param index {Number}
*/
on(evt: 'removed:', listener: (item: Model, index: number) => void): Base;
/**
* Fired when the collection has been resynced.
*
* @event resynced:
*/
on(evt: 'resynced:', listener: () => void): Base;
}
/**
The {{#crossLink "Sequence"}}{{/crossLink}} class is used to represent an
sorted set of models providing special method for typical sequence operations
such as insert, move, push, etc
Sequences are normally instantiated lazily, meaning that the sequence instance
is created and afterwards the data is fetched asynchronously. The sequence
can be used before the data has arrived, and as long as the code using the
sequence is reactive (based on the events generated by the sequence)
everything will work as expected.
Sequences inherit the following methods from [Underscore / Lodash](http://http://underscorejs.org/#collections)
forEach, each, map, reduce, reduceRight, find, detect, pluck,
filter, select, reject, every, all, some, any, include,
contains, invoke, max, min, sortBy, sortedIndex, toArray, size,
first, rest, last, without, indexOf, lastIndexOf, isEmpty, groupBy
@class Sequence
@extends Container
@constructor
@param model {IModel}
@param [opts] {ContainerOptions}
@param [parent] {Model}
@param [items] {ISeqModel[]}
**/
export class Sequence extends Container implements SequenceEvents
{
static mergeFns = {
id: function(item){
return item.id;
},
keyPath: function(item){
return item.keyPath;
},
doc: function(item){
return item.doc;
},
inSync: function(item){
return item.insync;
}
};
public updateFn: (args: any) => void;
public deleteFn: (model: Model) => void;
// Mutex
private resyncMutex = Mutex();
constructor(model: IModel, opts?: ContainerOptions, parent?: Model, items?: ISeqModel[])
{
super(model, opts, parent, items);
var __this = this;
var updateFn = function(args){
__this.emit('updated:', this, args);
};
var deleteFn = (model)=>{
for(var i = this.items.length-1; i >= 0; i--){
if(this.items[i].model.id() === model.id()){
this.remove(i, {nosync: true});
}
}
};
this._init(updateFn, deleteFn);
this._promise = new Promise((resolve, reject) => {
var keyPath = this.getKeyPath();
if(keyPath && !this.opts.nosync){
this.retain();
using.storageQueue.all(keyPath).then((result) => {
this.resync(result[0]);
result[1].then((items?) => this.resync(items))
.ensure(() => {
resolve(this);
this.release();
}).fail((err) => {});
});
}else{
resolve(this);
}
});
this._promise.uncancellable = true;
}
private deleteItem(id: string, opts): Promise<any>
{
var idx = _.findIndex(this.items, {'id': id});
if(idx === -1) return Promise.resolved(this); //already deleted
return this.remove(idx, opts);
}
private insertBefore(refId: string, item: Model, opts?): Promise<any>
{
return this.insertItemBefore(refId, item, null, opts);
}
private insertItemBefore(refId: string, item: Model, id: string, opts): Promise<any>
{
var seqItem = {
model: item,
id: id,
insync: !(_.isNull(id) || _.isUndefined(id))
};
opts = Util.extendClone(this.opts, opts);
if(id) opts.id = id;
var done = (id)=>{
seqItem.id = id.id || seqItem.id;
this.storageQueue.once('inserted:'+seqItem.id, (sid)=>{
seqItem.insync = true;
});
}
var index = _.findIndex(this.items, {'id': id});
if(index !== -1){
var next = this.items[index+1];
if((!refId && !next) || refId === next.id){
return Promise.resolved(); //already at the right place
}else{
return Promise.rejected(Error('Tried to insert duplicate container'));
}
}
if(refId){
index = _.findIndex(this.items, {'id': refId});
if(index === -1){
//refId not found perform a resync
log('REFID not found. Resyncing');
return this.triggerResync();
}
}else{
//push last
index = this.items.length;
}
//Handle the case when we insert an item from the server that have a pending item on this position
while(opts.noremote && index > 0 && !this.items[index-1].insync){
index--;
refId = this.items[index].id;
}
this.initItems(item);
this.items.splice(index, 0, seqItem);
this.set('count', this.items.length);
this._keepSynced && item.keepSynced();
var promise;
if(!opts || !opts.nosync){
if(item.isPersisted() || item._persisting){
promise = this.insertPersistedItemBefore(refId, item, opts).then<any>(done);
}else{
promise = item.save().then(()=>{
return this.insertPersistedItemBefore(refId, item, opts).then(done);
});
}
}else{
promise = Promise.resolved();
}
this.emit('inserted:', item, index);
return promise;
}
private insertPersistedItemBefore(id: string, item: Model, opts: {}): Promise<any>
{
var keyPath = this.getKeyPath();
var itemKeyPath = item.getKeyPath();
return this.storageQueue.insertBefore(keyPath, id, itemKeyPath, opts);
}
/**
Pushes an item at the end of the sequence.
@method push
@param item {Model}
@param [opts] {Any}
@returns {Promise}
**/
push(item: Model, opts?): Promise<any>
{
return this.insertBefore(null, item, opts);
}
/**
Inserts an item at the beginning of the sequence
@method unshift
@param item {Model}
@param [opts] {Any}
@returns {Promise}
**/
unshift(item: Model, opts?): Promise<any>
{
var firstId = this.items.length > 0 ? _.first(this.items).id : null;
return this.insertBefore(firstId, item, opts);
}
/**
Inserts an item at the given index position in the sequence.
@method insert
@param idx {Number}
@param item {Model}
@param [opts] {Any}
@returns {Promise}
**/
insert(idx: number, item: Model, opts?): Promise<any>
{
var seqItem = this.items[idx];
var id = seqItem ? seqItem.id : null;
return this.insertBefore(id, item, opts);
}
/**
Removes an item at the given index position in the sequence.
@method remove
@param idx {Number}
@param [opts] {Any}
@returns {Promise}
**/
remove(idx: number, opts?): Promise<any>
{
var promise;
var item = this.items[idx];
if(!item){
return Promise.rejected(Error('index out of bounds'));
}
this.items.splice(idx, 1);
this.deinitItems(item.model);
this.set('count', this.items.length);
opts = Util.extendClone(this.opts, opts);
if(!opts || !opts.nosync){
promise = this.storageQueue.deleteItem(this.getKeyPath(), item.id, opts);
}else{
promise = Promise.resolved();
}
this.emit('removed:', item.model, idx);
return promise;
}
/**
Moves an item from the given index position to another index position.
@method move
@param startIdx {Number}
@param endIdx {Number}
@param [opts] {Any}
@returns {Promise}
**/
move(startIdx: number, endIdx: number, opts?): Promise<any>
{
var srcItem = this.items[startIdx];
if(srcItem){
endIdx = startIdx <= endIdx ? endIdx + 1 : endIdx;
if(0 <= endIdx && endIdx <= this.items.length){
var targetId = endIdx < this.items.length ? this.items[endIdx].id : null;
srcItem.model.retain();
return this.remove(startIdx).then(()=>{
return this.insertBefore(targetId, srcItem.model, opts);
});
}
}
return Promise.rejected(Error("Invalid indexes:"+startIdx+", "+endIdx));
}
/**
Gets an array with all the items stored in the sequence.
@method getItems
@returns {Model[]}
**/
public getItems(): Model[]
{
return _.pluck(this.items, 'model');
}
public startSync()
{
super.startSync();
this.on('insertBefore:', (id, itemKeyPath, refId)=>{
this.model.findById(itemKeyPath, true, {}).then((item)=>{
this.insertItemBefore(refId, item, id, {noremote: true});
item.release();
});
});
this.on('deleteItem:', (id) => {
this.deleteItem(id, {noremote: true});
});
}
private execCmds(commands: MergeCommand[]): Promise<any>
{
var opts = {nosync: true};
var item;
return Gnd.Promise.map(commands, (cmd) => {
switch(cmd.cmd) {
case 'insertBefore':
item = this.model.create(cmd.doc, this.autosync());
item.autorelease();
return this.insertItemBefore(cmd.refId, item, cmd.newId, opts);
case 'removeItem':
return this.deleteItem(cmd.id, opts);
case 'update':
item = this['find']((item) => cmd.doc._cid == item.id());
item && item.resync(cmd.doc);
return Promise.resolved();
default:
throw Error('Invalid command:'+cmd);
}
});
}
private triggerResync(): Promise<any>
{
var keyPath = this.getKeyPath();
return this.storageQueue.all(keyPath, {}, {}).then((result) =>
result[1].then((items) => this.resync(items))
);
}
public resync(remoteItems?: any[]): Promise<any>
{
return this.resyncMutex(() => {
if(remoteItems){
return this._resync(remoteItems);
}else{
this.retain();
using.storageQueue.allRemote(this.getKeyPath(), {}, {})
.then((items) => this._resync(<any>items)).ensure(()=>this.release());
}
});
}
private _resync(items: any[]): Promise<any>
{
var commands = Sequence.merge(items, this.items, Sequence.mergeFns);
return this.execCmds(commands).then(() => {
this.emit('resynced:');
});
}
static merge(source: any[], target: any[], fns: MergeFunctions): MergeCommand[]
{
source = source || [];
var insertCommands: MergeCommand[] = [];
var removeCommands: MergeCommand[] = [];
var updateCommands: MergeCommand[] = [];
var remainingItems = [];
var sourceIds = _.map(source, function(item){
return fns.id(item); //TODO: Change to id
}).sort();
//Determine which items to delete
_.each(target, function(targetItem){
if(fns.inSync(targetItem) && -1 === _.indexOf(sourceIds, fns.id(targetItem), true)){
removeCommands.push({
cmd: 'removeItem',
id: fns.id(targetItem)
});
}else{
remainingItems.push(targetItem);
}
});
var i=0;
var j=0;
var targetItem, sourceItem;
// insert new items on the right place
while(i<remainingItems.length && j<source.length){
targetItem = remainingItems[i];
if(fns.inSync(targetItem)){
sourceItem = source[j];
if(fns.id(targetItem) === fns.id(sourceItem)){
updateCommands.push({
cmd: 'update',
// id: fns.id(sourceItem),
keyPath: fns.keyPath(sourceItem), //TODO: not always needed
doc: fns.doc(sourceItem)
});
i++;
}else{
insertCommands.push({
cmd: 'insertBefore',
refId: fns.id(targetItem),
newId: fns.id(sourceItem),
keyPath: fns.keyPath(sourceItem), //TODO: not always needed
doc: fns.doc(sourceItem)
});
}
j++;
}else{
i++;
}
}
//append remaining new items
while(j<source.length){
sourceItem = source[j];
insertCommands.push({
cmd: 'insertBefore',
refId: null,
newId: fns.id(sourceItem),
keyPath: fns.keyPath(sourceItem), //TODO: see above
doc: fns.doc(sourceItem)
});
j++;
}
//remove remaining old items
while(i<remainingItems.length){
targetItem = remainingItems[i];
if(fns.inSync(targetItem)){
removeCommands.push({
cmd: 'removeItem',
id: fns.id(targetItem)
});
}
i++;
}
// Adapt insert commands if pointing at deleted item
_.each(insertCommands, function(insertCmd){
var found = _.find(removeCommands, function(removeCmd: any){
return removeCmd.id === insertCmd.refId;
});
if(found){
insertCmd.refId = null;
}
});
// return the sequence of commands that transforms the target sequence according
// to the source
// it is important that the removecommands come before the insertcommands
return removeCommands.concat(insertCommands).concat(updateCommands);
}
}
//
// Underscore methods that we want to implement on the Sequence
//
var methods =
['each', 'map', 'reduce', 'reduceRight', 'find', 'detect', 'pluck',
'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include',
'contains', 'invoke', 'max', 'min', 'toArray', 'size',
'first', 'rest', 'last', 'without', 'indexOf', 'lastIndexOf', 'isEmpty']
// Mix in each Underscore method as a proxy to `Sequence#items`.
// The pluck is a candidate for optimization
_.each(methods, function(method) {
Sequence.prototype[method] = function() {
return _[method].apply(_, [_.pluck(this.items, 'model')].concat(_.toArray(arguments)))
}
});
export interface MergeFunctions {
id: (item: {}) => string;
keyPath: (item: {}) => string[];
doc: (item: {}) => {};
inSync: (item: {}) => boolean;
}
export interface MergeCommand {
cmd: string;
id?: string;
refId?: string;
newId?: string;
keyPath?: string[];
doc?: {};
}
}
|
5321ab2a57eea697379b48a524bd64cf93b2237c
|
TypeScript
|
tmastalirsch/clean-architecture-ts
|
/src/utils/decorators/Injectable.ts
| 2.609375
| 3
|
import { container } from './../Container';
/**
* Decorator that marks a class as a provider.
* Providers can be injected into other classes via constructor parameter injection.
*/
export function Injectable(): ClassDecorator {
return function (constructor: any) {
container.provide({className: constructor.name, useValue: constructor});
}
}
|
72a677c18084295d9f3c73698b1bb2d0f8ac40a2
|
TypeScript
|
Rajiv-Patel/Angular6HerokuApp
|
/src/app/entertainment/music/music.service.ts
| 2.515625
| 3
|
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { HttpClient } from '@angular/common/http';
// Ang5
// import { Observable } from 'rxjs/observable';
// Ang6
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';
import { RootObject} from './music_model';
@Injectable()
export class musicService {
//private _productUrl = 'https://ngproductsparam.herokuapp.com/api/getProductDetails';
//private _musicUrl = 'https://ngmovies.herokuapp.com/api/getMovies';
private _musicUrl = 'https://ngmusicdb.herokuapp.com/api/getMusic';
constructor(private _http: Http,
private __http: HttpClient) {}
getMusic(): Observable<RootObject[]> {
return this.__http.get<RootObject[]>(this._musicUrl);
}
// getProduct(): Observable<RajInterfaceIproduct[]> {
// return this.__http.get<RajInterfaceIproduct[]>(this._productUrl);
// }
// getProductDetail(id): Observable<RajInterfaceIproduct[]> {
// return this.__http.get<RajInterfaceIproduct[]>(`${this._productUrl}?productId=${id}`);
// }
// getMovies(): Observable<any[]> {
// return this.__http.get<any[]>(this._moviesUrl);
// }
}
/* https://jsonformatter.curiousconcept.com/
[
{
"_id":"5ab17276f36d282750913a51",
"artists":[
{
"id":1,
"name":"Jimi Hendrix",
"cover":"jimi_hendrix",
"bio":"James Marshall Jimi Hendrix was an American rock guitarist, singer, and songwriter. ",
"albums":[
{
"albumId":"a1",
"title":"Electric Ladyland",
"year":1968,
"cover":"electric-ladyland",
"price":20
},
{
"albumId":"a2",
"title":"Experience",
"year":1971,
"cover":"experienced",
"price":25
},
{
"albumId":"a3",
"title":"Isle of Wright",
"year":1971,
"cover":"isle_of_wright",
"price":15
},
{
"albumId":"a4",
"title":"Band of Gypsys",
"year":1970,
"cover":"band_of_gypsys",
"price":10
}
],
"genre":"rock, blues"
},
{
"id":2,
"name":"Madonna",
"cover":"madonna",
"bio":"Madonna Louise Ciccone is an American singer, songwriter, actress, and businesswoman.",
"albums":[
{
"albumId":"b1",
"title":"Like a Virgin",
"year":1984,
"cover":"like_a_virgin",
"price":20
},
{
"albumId":"b2",
"title":"True Blue",
"year":1986,
"cover":"true_blue",
"price":25
},
{
"albumId":"b3",
"title":"Erotica",
"year":1994,
"cover":"erotica",
"price":15
},
{
"albumId":"b4",
"title":"Ray of Light",
"year":1998,
"cover":"ray_of_light",
"price":10
}
],
"genre":"pop"
},
{
"id":3,
"name":"Johnny Cash",
"cover":"johnny_cash",
"bio":"John R. Cash was an American singer-songwriter, guitarist, actor, and author.",
"albums":[
{
"albumId":"c1",
"title":"Ain't No Grave",
"year":2010,
"cover":"no_grave",
"price":20
},
{
"albumId":"c2",
"title":"Out Among the Stars",
"year":2014,
"cover":"among_stars",
"price":25
},
{
"albumId":"c3",
"title":"Solitary Man",
"year":2000,
"cover":"solitary_man",
"price":15
},
{
"albumId":"c4",
"title":"The Man Comes Around",
"year":2002,
"cover":"man_comes_around",
"price":10
}
],
"genre":"pop"
},
{
"id":4,
"name":"Pink Floyd",
"cover":"pink_floyd",
"bio":"Pink Floyd were an English rock band formed in London in 1965. They achieved international acclaim with their progressive and psychedelic music. ",
"albums":[
{
"albumId":"d1",
"title":"The Wall",
"year":1979,
"cover":"the_wall",
"price":20
},
{
"albumId":"d2",
"title":"The Dark Side of the Moon",
"year":1973,
"cover":"dark_side",
"price":25
},
{
"albumId":"d3",
"title":"Animals",
"year":1977,
"cover":"animals",
"price":15
}
],
"genre":"Rock"
}
]
}
]
*/
/*
promises <= ===== .then
Observable => rxjs ====== .subscribe (fast)(stream line)
http=> old
httpclient => new
getProduct(): Promise<RajInterfaceIproduct[]> {
return this._http.get(this._productUrl)
.toPromise()
.then((res) => res.json());
}
private extractData(res: Response) {
return res.json();
}
getProduct(): Observable<RajInterfaceIproduct[]> {
return this._http.get(this._productUrl)
.pipe(map(this.extractData));
}
*/
|
c9070b93c9c689081155be2004ad135ef5e3b88d
|
TypeScript
|
robholland/ui
|
/src/global.d.ts
| 2.625
| 3
|
/// <reference types="@sveltejs/kit" />
interface Window {
Prism: {
highlightAll: () => void;
};
}
type Heroicon = { [key: string]: string }[][];
type WorkflowStatus =
| 'Running'
| 'TimedOut'
| 'Completed'
| 'Failed'
| 'Completed'
| 'ContinuedAsNew'
| 'Canceled'
| 'Terminated'
| null;
type NamespaceScopedRequest = { namespace: string };
type NextPageToken = Uint8Array | string;
type WithNextPageToken = { nextPageToken?: NextPageToken };
type WithoutNextPageToken<T> = Omit<T, keyof WithNextPageToken>;
type PaginationCallbacks<T> = {
onStart?: () => void;
onUpdate?: (
full: WithoutNextPageToken<T>,
current: WithoutNextPageToken<T>,
) => void;
onComplete?: (finalProps: WithoutNextPageToken<T>) => void;
onError?: (error: unknown) => void;
};
type WorkflowType = string | null;
type WorkflowExecutionFilters = {
type: WorkflowType;
status: WorkflowStatus;
};
type EventFormat = 'grid' | 'json';
type ActivityStatus =
| 'Started'
| 'Scheduled'
| 'Completed'
| 'Failed'
| 'TimedOut'
| 'CancelRequested'
| 'Canceled';
type Activity = {
id?: string;
status?: ActivityStatus;
activityTaskStartedEvent?: ActivityTaskStartedEvent;
activityTaskScheduledEvent?: ActivityTaskScheduledEvent;
activityTaskCompletedEvent?: ActivityTaskCompletedEvent;
activityTaskFailedEvent?: ActivityTaskFailedEvent;
activityTaskTimedOutEvent?: ActivityTaskTimedOutEvent;
activityTaskCancelRequestedEvent?: ActivityTaskCancelRequestedEvent;
activityTaskCanceledEvent?: ActivityTaskCanceledEvent;
};
|
6bb12508185db8c937951198767f177f6dcc8d43
|
TypeScript
|
LanceTurri/destiny-ipsum
|
/src/data/vance.ts
| 2.59375
| 3
|
// tslint:disable-max-line-length
export const VANCE_INTROS = [
'Is it time?',
'I\'m listening, Guardian.',
'Let\'s talk.',
'Go ahead, Guardian.',
'The Trials will wait for you.',
'Eyes open Guardian.',
'Light go with you, Guardian.',
'Go with the Light.',
'I hope we\'ll meet again.',
'Time to say goodbye.',
];
export const VANCE_DIALOGUE = {
'Send Offs': [
'I\'m here.',
'Let\'s begin.',
'Guardian.',
'Is it time?',
'I\'m listening, Guardian.',
'Welcome.',
'Let\'s talk.',
'Go ahead, Guardian.',
'What do you need?',
'Welcome, Guardian.',
'Let\'s see.',
'I\'m ready.',
'I lost time to say goodbye.',
'The Trials will wait for you.',
'Eyes open Guardian.',
'Light go with you, Guardian.',
'Goodbye.',
'Keep your eyes open.',
'Go with the Light.',
'I hope we\'ll meet again.',
'If it\'s time.',
'Time to say goodbye.',
],
'Idle': [
'I was just reading his words. Osiris. Have you heard of him?',
'I\'m looking for a weapon. A weapon and the right moment.',
'Are you the one who faced Crota?',
'What are the Warlocks focused on these days?',
'I was just meditating, Warlock. Would you like to join me?',
'I used to be a Warlock, now I follow a different path.',
'Warlock!',
'No, you are not one of Ikora\'s Hidden, are you? I feel like we\'ve met before.',
'When you\'ve been out of The City so long you start to talk to yourself, Don\'t mind me.',
'He is the one true Speaker, who knows that the Traveler will never speak again.',
'Show us your Light.',
'I was talking to myself, you\'re not interrupting anything.',
'Go on. Ask your question.',
'It\'s a long time since I\'ve been back at The Tower. Does the Speaker still speak of Osiris?',
'You are aware of the Hidden, yes? But you are not one of them. You do not wear the mark.',
'Maybe you\'re the one. Why don\'t you show us.',
'I was meditating, Titan. Join me if you\'d like.',
'I\'m an old, blind Warlock far from home. Perhaps we can talk.',
'A Titan. I can sense you.',
'Titan!',
'My regards to Commander Zavala, Titan.',
'Lets talk, Titan.',
'What brings you out here so close to the Darkness. Can you feel it?',
'Titans know the value of stillness.',
'My regards to Cayde, Hunter.',
'Maybe you\'re the one we need, come forward.',
'Good to meet you, Guardian. Have you heard of Osiris?',
'There\'s a deep, dark course ahead of us. The Wolves are just the beginning.',
'They call me Vance. Nice to meet you. A guest on the Reef, like yourself.',
'I follow Osiris, not the Speaker. Do you know his legend?',
'I think of myself as a Hunter too. In a way.',
'is it coincidence that brings us together, do you think?',
'A Hunter. I can sense you.',
'I see you have been to the darkness and back. Tell Eris I said hello.',
'Hunter!',
'If you seek Osiris, you must begin with the trials.',
'I sacrificed my sight in the Trials and it wasn\'t enough.',
'Does Osiris live? I assure you, he lives through me.',
'Ask yourself \'What would YOU do if the Speaker was proven a charlatan?\'',
'You know why I\'m here and you know what I offer',
'Osiris stood before the Nine on the ice fields of Europa but the time wasn\'t right',
'My master always had... an understanding with the Queen.',
'Take your time.',
'I may be blind, Guardian but I know you\'re there.',
'You seek great challenges.',
'Don\'t worry about the candles, they center me.',
'I can wait.',
'C\'mon lets get a sense of your might.',
'The candles are for focus, don\'t let them distract you.',
'Do what the Queen asks, this is all part of the pattern.',
'Come. Show us your Light.',
'Yes, I am what you think I am.',
'If you\'re looking for me, you\'ve found me.',
'Excuse me, i was just meditating.',
'I lost my sight long ago, but there are other senses.',
'If you think you\'re ready then you\'re ready.',
'You\'ve heard of the great Osiris, Guardian.',
'I came here because we have business of our own with the Queen.',
'Nothing to do with Wolves, but plenty to do with Skolas.',
'Tell me Guardian, do you think you\'re ready for the Trials?',
'Good, think first.',
'Osiris fought at the battle of Six Fronts, it\'s said he seemed to be everywhere at once that day.',
'They say the Nine released Skolas, no doubt they had their reasons.',
'But it brought you here and they may yet regret that.',
'If it\'s not time, it\'s not time',
'Breathe.',
'(whispered) The Queen and Osiris, I believe they conspire.',
'Have you heard the name Oryx, Guardian?',
'In your own time.',
'He trusts Ikora, he knows her Hidden too well.',
'There are a few of us \'followers of Osiris\'. We... move around a lot.',
'No rush',
'(whispered) Oryx, this name, do you know it?',
'They want this Oryx here, out of the darkness',
'I began as a Guardian, I left to follow a different path.',
'Perhaps you will too one day.',
'It all has to come together, but what if we miss',
'When you\'re ready.',
'He says the Nine are vulnerable every moment they touch our world.',
'Listen. Do you hear that?',
'The purpose of the Trials is to hone the right weapon for the right moment.',
'If we miss our moment, if we\'re not ready. It won\'t come again',
'Is this where I should be?',
'I need to see the Queen again',
'Quiet. Still. Wait for them to come into alignment.',
'It\'s hard to be your eyes out here, Master.',
'Ah, here. If were not ready when the moment comes, if we miss by seconds. Darkness',
'Alas, Guardians will find us',
'The right weapon, honed in the Trials and ready at the right moment',
'What a strange place to find myself. What a strange time.',
'Be still, be still. Let them come to you',
'Be still. Watch. No body. No weight. Be an eye',
'Why do wish for me to shadow this Uldren? Does he scare you',
'Who is this one who calls himself Arty?',
'Speak through me, Master. Let me help you find them',
'Why do you make me deal with this Shaxx, Master? Is it a test?',
'None of them are ready for Mercury',
'I waited and waited and suddenly here they all are, you were right',
'The Wolves will test them, make them ready for the Trials',
'What does he say about the Nine?',
'Lets see. 1, 2, 3, Strike, Step, Strike, 3, 2, 1.',
'So many Guardians here, so few who have what it takes.',
'Which technique? Guard, Strike, Guard, step, again',
'Ask yourself, what would you do if it was proven the Speaker was a charlatan?',
'If you think you\'re ready, then you\'re ready.',
'I was once a Guardian, like yourself, but now I am on a different path.',
'I can\'t tell you where Osiris has gone. It isn\'t time for you to know.',
'My regards to Ikora, Warlock.',
'What have you done for Osiris today?',
'Hmm... No, I can\'t say that I know much about \'Arc\' energies... We do not have electricity here, as you can see...',
],
};
|
a5c4fe1d74b297d05961f47365868a18487d5d4b
|
TypeScript
|
huanghaiyang/cook-hooks
|
/src/useWaterfall.ts
| 2.59375
| 3
|
import { useMountedState } from 'react-use';
import { useCallback } from 'react';
export type UseWaterfall = () => (wrappedPromises: ((param?: any) => Promise<any>)[]) => Promise<any>;
const useWaterfall: UseWaterfall = () => {
const isMounted = useMountedState();
return useCallback((wrappedPromises: ((param?: any) => Promise<any>)[]) => {
return new Promise<any>((resolve, reject) => {
if (!wrappedPromises.length) resolve();
const onError = (error: Error) => {
isMounted() && reject(error);
};
let taskIndex = 0;
function nextTask(previousResult?: any) {
if (taskIndex === wrappedPromises.length) {
isMounted && resolve(previousResult);
return;
}
const task = wrappedPromises[taskIndex++];
task(previousResult).then(result => nextTask(result), onError);
}
nextTask();
});
}, []);
};
export default useWaterfall;
|
28eba6b5c3918e331de5f438d48efe964990544f
|
TypeScript
|
ATKovz/blog
|
/2022/[TS]练习/29.实现StringToPath.ts
| 3.671875
| 4
|
// 实现一个 ToPath 工具类型,用于把属性访问(. 或 [])路径转换为元组的形式。具体的使用示例如下所示:
namespace ToPath {
type A = ToPath<'foo.bar.baz'> //=> ['foo', 'bar', 'baz']
type B = ToPath<'foo.bar[0].baz'> //=> ['foo', 'bar', '0', 'baz']
type ToPath<S extends string, Stack extends any[] = []> = S extends `${infer Head}[${infer N}]${infer Rest}`
// []后带 '.' 需要移除点再继续
? [...Stack, ...ToPath<Head>, N, ...ToPath<Rest>]
: S extends `${infer Head}.${infer Rest}`
// 移除完 [] 后有可能会是 '.a.b' 这种形式,需要判断非空
? Head extends ''
? [...Stack, ...ToPath<Rest>]
: [...Stack, Head, ...ToPath<Rest>]
// 结束标识,直接插入最后一个
: S extends `${infer End}.`
? [...Stack, End]
: [...Stack, S]
type Merge<A extends Object, B extends Object> = {
[K in (keyof A | keyof B)]: K extends keyof B
? K extends keyof A
? A[K] | B[K]
: B[K]
: K extends keyof A
? A[K]
: never
}
type R = Merge<{ dsd: 'teo' }, { name: 'tiny teo', gender: 'unknown' }>
}
|
f89f1b89a78b3c7ca4647e634d26c27c40d6f1a8
|
TypeScript
|
oliviertassinari/material-ui
|
/packages/mui-system/src/createTheme/createSpacing.test.ts
| 3.109375
| 3
|
import { expect } from 'chai';
import createSpacing, { Spacing } from './createSpacing';
describe('createSpacing', () => {
it('should be configurable', () => {
let spacing: Spacing;
spacing = createSpacing();
expect(spacing(1)).to.equal('8px');
spacing = createSpacing(10);
expect(spacing(1)).to.equal('10px');
spacing = createSpacing([0, 8, 16]);
expect(spacing(2)).to.equal('16px');
spacing = createSpacing(['0rem', '8rem', '16rem']);
expect(spacing(2)).to.equal('16rem');
spacing = createSpacing((factor: number) => factor ** 2);
expect(spacing(2)).to.equal('4px');
spacing = createSpacing((factor: number) => `${0.25 * factor}rem`);
expect(spacing(2)).to.equal('0.5rem');
});
it('should support recursion', () => {
const spacing = createSpacing();
createSpacing(spacing);
});
it('should support a default value when no arguments are provided', () => {
let spacing;
spacing = createSpacing();
expect(spacing()).to.equal('8px');
spacing = createSpacing((factor: number) => `${0.25 * factor}rem`);
expect(spacing()).to.equal('0.25rem');
});
it('should support multiple arguments', () => {
let spacing;
spacing = createSpacing();
expect(spacing(1, 2)).to.equal('8px 16px');
spacing = createSpacing((factor: number) => `${0.25 * factor}rem`);
expect(spacing(1, 2)).to.equal('0.25rem 0.5rem');
});
it('should support string arguments', () => {
let spacing;
spacing = createSpacing();
expect(spacing(1, 'auto')).to.equal('8px auto');
spacing = createSpacing((factor: number | string) =>
typeof factor === 'string' ? factor : `${0.25 * factor}rem`,
);
expect(spacing(1, 'auto', 2, 3)).to.equal('0.25rem auto 0.5rem 0.75rem');
});
describe('warnings', () => {
it('should warn for wrong input', () => {
expect(() => {
createSpacing({
// @ts-expect-error
unit: 4,
});
}).toErrorDev('MUI: The `theme.spacing` value ([object Object]) is invalid');
});
});
});
|
f3ba17357feea80bf1c7b53e211b7ef7fe495fff
|
TypeScript
|
nadberezny/nussknacker
|
/ui/client/reducers/toolbars.ts
| 2.703125
| 3
|
import {persistReducer} from "redux-persist"
import storage from "redux-persist/lib/storage"
import {Reducer} from "../actions/reduxTypes"
import {combineReducers} from "redux"
export enum ToolbarsSide {
TopRight = "TOP-RIGHT",
BottomRight = "BOTTOM-RIGHT",
TopLeft = "TOP-LEFT",
BottomLeft = "BOTTOM-LEFT",
Hidden = "HIDDEN",
}
type NodeToolbox = {
opened: Record<string, boolean>,
}
type InitData = Array<[string, ToolbarsSide]>
type Positions = {
[side in ToolbarsSide]?: string[]
}
type Collapsed = Record<string, boolean>
export type ToolbarsState = {
positions: Positions,
initData: InitData,
collapsed: Collapsed,
nodeToolbox: NodeToolbox,
}
type Id = `#${string}`
export type ToolbarsStates = {currentConfigId?: string} & { [id in Id]: ToolbarsState }
const nodeToolbox: Reducer<NodeToolbox> = (state = {opened: {}}, action) => {
switch (action.type) {
case "TOGGLE_NODE_TOOLBOX_GROUP":
return {
opened: {
...state.opened,
[action.nodeGroup]: !state.opened[action.nodeGroup],
},
}
case "RESET_TOOLBARS":
return {
opened: {},
}
default:
return state
}
}
function setupPositions(positions: Positions, toolbars: Array<[string, ToolbarsSide]>): Positions {
const groups = Object.values(positions)
const newToolbars = toolbars.filter(([id]) => !groups.some(g => g.includes(id)))
return newToolbars.reduce((nextState, [id, side]) => {
const currentValues = nextState[side || ToolbarsSide.TopRight] || []
return {...nextState, [side || ToolbarsSide.TopRight]: [...currentValues, id]}
}, positions)
}
function insertItemOnTargetPlaceOnList(
state: Positions,
fromToolbar: ToolbarsSide | string,
toToolbar: ToolbarsSide | string,
fromIndex: number,
toIndex: number,
): [string[], string[]] {
const isSameToolbar = fromToolbar === toToolbar
const src = [].concat(state[fromToolbar])
const [item] = src.splice(fromIndex, 1)
const dst = isSameToolbar ? src : [].concat(state[toToolbar])
dst.splice(toIndex, 0, item)
return [src, dst]
}
const positions: Reducer<Positions> = (state = {}, action) => {
switch (action.type) {
case "MOVE_TOOLBAR":
const [fromToolbar, fromIndex] = action.from
const [toToolbar, toIndex] = action.to
const [src, dst] = insertItemOnTargetPlaceOnList(state, fromToolbar, toToolbar, fromIndex, toIndex)
return {
...state,
[fromToolbar]: src,
[toToolbar]: dst,
}
case "REGISTER_TOOLBARS":
case "RESET_TOOLBARS":
return setupPositions(state, action.toolbars)
default:
return state
}
}
const collapsed: Reducer<Collapsed> = (state = {}, action) => {
switch (action.type) {
case "TOGGLE_ALL_TOOLBARS":
// eslint-disable-next-line i18next/no-literal-string
throw "not implemented"
return state
case "TOGGLE_TOOLBAR":
return {...state, [action.id]: action.isCollapsed}
default:
return state
}
}
const initData: Reducer<InitData> = (state = [], action) => {
return action.type === "REGISTER_TOOLBARS" ? action.toolbars : state
}
const resetReducer: Reducer<ToolbarsState> = (state, action) => {
return action.type === "RESET_TOOLBARS" ? {...state, collapsed: {}, positions: {}} : state
}
const combinedReducers = combineReducers<ToolbarsState>({
collapsed, positions, nodeToolbox, initData,
})
const configReducer: Reducer<ToolbarsState> = (state, action) => {
const withReset = resetReducer(state, action)
return combinedReducers(withReset, action)
}
const configIdReducer: Reducer<string> = (state = "", action) => {
return action.type === "REGISTER_TOOLBARS" ? action.configId : state
}
const reducer: Reducer<ToolbarsStates> = (state = {}, action) => {
const currentConfigId = configIdReducer(state.currentConfigId, action)
return currentConfigId ?
{...state, currentConfigId, [`#${currentConfigId}`]: configReducer(state[`#${currentConfigId}`], action)} :
state
}
export const toolbars = persistReducer({key: `toolbars`, storage}, reducer)
|
8cce11fb28babe76a8c2564b8d8bfd250b396553
|
TypeScript
|
danikaze/kokan
|
/store/clean-state-for-client.ts
| 3
| 3
|
import { State } from './model';
/**
* Return a copy of the passed state after cleaning it for the client
* Basically, edits and removes parts that shouldn't be "shown" in the client
*/
export function cleanStateForClient(state: State): State {
const frontendState = { ...state };
const log = state.settings.log;
frontendState.settings.log = {
level: log.level,
silent: log.silent,
console: log.console,
};
return frontendState;
}
|
dc7e8542ebcbc0562ea1c3239c111d14f7db7356
|
TypeScript
|
fixiabis/Sealed
|
/Relati/v0.1.3/Relati/js/signOXDUA.ts
| 2.625
| 3
|
function signOXDUA(board) {
var symbolColor = {
"O": "#dc143c",
"X": "#4169e1",
"D": "#ffa500",
"U": "#2e8b57"
};
var viewer = board.viewer;
function cleanSign(grid) {
for (var i = 0; i < grid.views.length; i++) {
viewer.removeChild(grid.views[i]);
}
grid.views = [];
}
function createDot(svg, grid, sym) {
var view = svg("circle");
view.setAttribute("stroke-width", "0.2");
view.setAttribute("cx", "" + (grid.x * 5 + 2.5));
view.setAttribute("cy", "" + (grid.y * 5 + 2.5));
view.setAttribute("r", "0.4");
view.setAttribute("fill", symbolColor[sym]);
return view;
}
board.addSign("next", "", function (svg, grid) {
cleanSign(grid);
});
for (var sym in symbolColor) {
(function (sym) {
board.addSign("next", sym, function (svg, grid) {
cleanSign(grid);
var view = createDot(svg, grid, sym);
grid.views.push(view);
viewer.appendChild(view);
});
})(sym);
}
board.addSign("symbol", "", function (svg, grid) {
cleanSign(grid);
});
board.addSign("symbol", "O", function (svg, grid) {
cleanSign(grid);
var view = svg("circle");
view.setAttribute("stroke-width", "0.6");
view.setAttribute("cx", "" + (grid.x * 5 + 2.5));
view.setAttribute("cy", "" + (grid.y * 5 + 2.5));
view.setAttribute("r", "1.5");
view.setAttribute("stroke", symbolColor["O"]);
view.setAttribute("fill", "none");
view.style.animation = "blink 0.8s 2";
grid.views.push(view);
viewer.appendChild(view);
});
board.addSign("symbol", "X", function (svg, grid) {
cleanSign(grid);
var srtX = grid.x * 5 + 1;
var srtY = grid.y * 5 + 1;
var endX = grid.x * 5 + 4;
var endY = grid.y * 5 + 4;
var view = svg("path");
view.setAttribute("stroke-width", "0.6");
view.setAttribute("d", "M " + srtX + " " + srtY + " L " + endX + " " + endY);
view.setAttribute("stroke", symbolColor["X"]);
view.setAttribute("fill", "none");
view.style.animation = "blink 0.8s 2";
grid.views.push(view);
viewer.appendChild(view);
view = svg("path");
view.setAttribute("stroke-width", "0.6");
view.setAttribute("d", "M " + srtX + " " + endY + " L " + endX + " " + srtY);
view.setAttribute("stroke", symbolColor["X"]);
view.setAttribute("fill", "none");
view.style.animation = "blink 0.8s 2";
grid.views.push(view);
viewer.appendChild(view);
});
board.addSign("symbol", "D", function (svg, grid) {
cleanSign(grid);
var srtX = grid.x * 5 + 1;
var srtY = grid.y * 5 + 1;
var endX = grid.x * 5 + 4;
var endY = grid.y * 5 + 4;
var view = svg("path");
view.setAttribute("stroke-width", "0.6");
view.setAttribute(
"d",
`M ${endX} ${endY} L ${srtX} ${endY} L ${srtX + 1.5} ${srtY}Z`
);
view.setAttribute("stroke", symbolColor["D"]);
view.setAttribute("fill", "none");
view.style.animation = "blink 0.8s 2";
grid.views.push(view);
viewer.appendChild(view);
});
board.addSign("symbol", "U", function (svg, grid) {
cleanSign(grid);
var srtX = grid.x * 5 + 1;
var srtY = grid.y * 5 + 1;
var endX = grid.x * 5 + 4;
var endY = grid.y * 5 + 4;
var view = svg("path");
view.setAttribute("stroke-width", "0.6");
view.setAttribute(
"d",
`M ${srtX} ${srtY} V ${endY} H ${endX} V ${srtY} Z`
);
view.setAttribute("stroke", symbolColor["U"]);
view.setAttribute("fill", "none");
view.style.animation = "blink 0.8s 2";
grid.views.push(view);
viewer.appendChild(view);
});
function normalStatus(grid) {
for (var i = 0; i < grid.views.length; i++) {
grid.views[i].setAttribute("stroke-width", "0.6");
grid.views[i].setAttribute("stroke", symbolColor[grid.symbol]);
}
}
board.addSign("status", "normal", function (svg, grid) {
normalStatus(grid);
});
board.addSign("status", "forbid", function (svg, grid) {
normalStatus(grid);
for (var i = 0; i < grid.views.length; i++) {
grid.views[i].setAttribute("stroke", "#666");
}
});
board.addSign("status", "source", function (svg, grid) {
normalStatus(grid);
for (var i = 0; i < grid.views.length; i++) {
grid.views[i].setAttribute("stroke-width", "0.8");
}
});
board.addSign("status", "broken", function (svg, grid) {
normalStatus(grid);
for (var i = 0; i < grid.views.length; i++) {
grid.views[i].setAttribute("stroke", "#ddd");
}
});
}
|
f05c2b3e0c7d58a24c856370d4c748b4fb7342bd
|
TypeScript
|
bigcommerce/checkout-sdk-js
|
/packages/core/src/common/utility/guard.ts
| 3.03125
| 3
|
export default function guard<T>(value: T, errorFactory?: () => Error): NonNullable<T> {
if (value === undefined || value === null) {
throw errorFactory ? errorFactory() : new Error('An unexpected error has occurred.');
}
return value as NonNullable<T>;
}
|
1adff6e2dbd9dfcf77a419f73da2e1c2aafed620
|
TypeScript
|
mlnima/reactServerSideRenderingWithNext
|
/packages/custom-util/src/date-utils/convertDurationStringToIso8601.ts
| 3.046875
| 3
|
const convertDurationStringToIso8601 = (duration: string) => {
try {
const splitDuration = duration.split(':')
const seconds = parseInt(splitDuration[splitDuration.length - 1])
const minutes = parseInt(splitDuration[splitDuration.length - 2])
const hours = parseInt(splitDuration.length === 3 ? splitDuration[splitDuration.length - 3] : '0')
return `P0DT${hours}H${minutes}M${seconds}S`
}catch (error){
return duration
}
}
export default convertDurationStringToIso8601
|
5b26151bfd5d81cf28916dd6c835f4df038e0ed6
|
TypeScript
|
esfx/esfx
|
/packages/struct-type/src/internal/array/arrayTypeImpl.ts
| 2.53125
| 3
|
/*!
Copyright 2023 Ron Buckton
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import type { ArrayType as IArrayType, FixedLengthArrayType as IFixedLengthArrayType } from "../../array.js";
import type { Type } from "../../type.js";
import { BaseArrayTypeInfo, FixedLengthArrayTypeInfo } from "./arrayTypeInfo.js";
import { TypedArrayImpl } from "./arrayImpl.js";
/* @internal */
export { ArrayType as ArrayTypeImpl };
function ArrayType<TType extends Type, TFixedLength extends number>(type: TType, fixedLength?: TFixedLength): IArrayType<TType> | IFixedLengthArrayType<TType, TFixedLength> {
return fixedLength === undefined ?
new BaseArrayTypeInfo(type).runtimeType as IArrayType<TType> :
new FixedLengthArrayTypeInfo(new BaseArrayTypeInfo(type), fixedLength).runtimeType as IFixedLengthArrayType<TType, TFixedLength>;
}
(ArrayType as any).prototype = TypedArrayImpl;
|
2b0c420dea878e1c2360e4ca067d7545ab35facd
|
TypeScript
|
tomas-ortega/nodejs-architecture-training
|
/full-app-examples/full-app/src/dao/singleton/MongoDBConnectionPoolDAO.ts
| 2.640625
| 3
|
import * as mongoDb from "mongodb";
import { DatabaseConnectionDTO } from "../../domain/DatabaseConnectionDTO";
export class MongoDBConnectionPoolDAO {
private static _instance:MongoDBConnectionPoolDAO = new MongoDBConnectionPoolDAO();
private _connectionPool:any = null;
private _firstInstance:boolean = false;
public constructor() {
if(MongoDBConnectionPoolDAO._instance){
throw new Error("Error: Instantiation failed: Use MongoDBConnectionPoolDAO.getInstance() instead of new.");
}
MongoDBConnectionPoolDAO._instance = this;
}
public static getInstance(configurationPool: DatabaseConnectionDTO):Promise<MongoDBConnectionPoolDAO>
{
let uri: string;
return new Promise((resolve, reject) => {
try {
if (MongoDBConnectionPoolDAO._instance._connectionPool == null) {
uri = "mongodb://";
uri += configurationPool.hostName;
uri += ":";
uri += configurationPool.port;
uri += "/";
uri += configurationPool.databaseName;
let promise = mongoDb.MongoClient.connect(uri, configurationPool);
MongoDBConnectionPoolDAO._instance._firstInstance = true;
MongoDBConnectionPoolDAO._instance._connectionPool = promise;
console.log("MONGODB POOL FIRST INSTANCE");
resolve(MongoDBConnectionPoolDAO._instance);
} else {
console.log("MONGODB POOL FROM MEMORY");
MongoDBConnectionPoolDAO._instance._firstInstance = false;
resolve(MongoDBConnectionPoolDAO._instance);
}
} catch(Exception) {
reject(Exception);
}
});
}
public getFirstInstance(): boolean {
return this._firstInstance;
}
public getConnectionPool(): any {
return this._connectionPool;
}
}
|
71ce0e3848325ec8248d35069f6fb45799793807
|
TypeScript
|
Esri/hub.js
|
/packages/common/src/utils/titleize.ts
| 3.390625
| 3
|
import { capitalize } from "../util";
/**
* Capitalize every word in a sentence
* @param {string} value
* @returns {string} a sentence with every word being capitalized
*/
export function titleize(value: string) {
return value
.split(" ")
.map((k) => capitalize(k))
.join(" ");
}
|
534aafaef59717673cc76c924b343cc652317da6
|
TypeScript
|
gmmurugan/cloud-reports
|
/src/analyzers/aws/route53/domain_transfer_lock.ts
| 2.515625
| 3
|
import { CheckAnalysisType, ICheckAnalysisResult, IResourceAnalysisResult, SeverityStatus } from "../../../types";
import { BaseAnalyzer } from "../../base";
export class DomainsTransferLockAnalyzer extends BaseAnalyzer {
public analyze(params: any): any {
const allDomains = params.domains;
if (!allDomains || allDomains.length === 0) {
return undefined;
}
const domains_transfer_lock: ICheckAnalysisResult = { type: CheckAnalysisType.Reliability };
domains_transfer_lock.what = "Is transfer lock enabled for the domains?";
domains_transfer_lock.why = `It is important to enable transfer lock
for domains as it protects someone from claiming them`;
domains_transfer_lock.recommendation = "Recommended to enable transfer lock for all your domains";
const allDomainAnalysis: IResourceAnalysisResult[] = [];
for (const domain of allDomains) {
const domain_analysis: IResourceAnalysisResult = {};
if (domain.TransferLock) {
domain_analysis.severity = SeverityStatus.Good;
domain_analysis.message = "Domain has transfer lock enabled";
} else {
domain_analysis.severity = SeverityStatus.Warning;
domain_analysis.message = "Domain doesn't have transfer lock enabled";
domain_analysis.action = "Enable transfer lock for the domain";
}
domain_analysis.resource = domain;
domain_analysis.resourceSummary = {
name: "Domain", value: domain.DomainName,
};
allDomainAnalysis.push(domain_analysis);
}
domains_transfer_lock.regions = { global: allDomainAnalysis };
return { domains_transfer_lock };
}
}
|
b5e434e22174531347c58ba958d40d4d32a24ba9
|
TypeScript
|
Zabadeus/o-marketplace
|
/server/src/product/resolvers/product.ts
| 2.59375
| 3
|
import { Response } from "express";
import { Arg, Ctx, Mutation, Query, Resolver } from "type-graphql";
import { AnyObject } from "../../common/types/AnyObject";
import { MyContext } from "../../common/types/MyContext";
import { checkAndUpdate } from "../../common/utils/checkAndUpdate";
import { Product } from "../entities/Product";
import { ProductInput } from "./Input-Types/prod-input";
@Resolver(_of => Product)
export class ProductResolver {
@Query(_returns => Product, { nullable: false })
async returnSingleProduct(@Arg("id") id: string, @Ctx() { em }: MyContext) {
return await em.findOne(Product, { id });
}
@Query(() => [Product])
async returnAllProducts(@Ctx() { em }: MyContext) {
return await em.find(Product, {});
}
@Mutation(() => Product)
async createProduct(
@Arg("data") input: ProductInput,
@Ctx() { em }: MyContext
): Promise<Product> {
const product = await em.create(Product, { ...input });
//populateEntity(product, input);
await em.persistAndFlush(product);
return product;
}
@Mutation(() => Product, { nullable: true })
async updateProduct(
@Arg("id") id: string,
@Arg("data") input: ProductInput,
@Ctx() { em, res }: MyContext
): Promise<AnyObject<Product> | Response> {
const entity = await em.findOne(Product, { id });
const result = checkAndUpdate(entity, input, em, res);
return result;
}
}
|
e84523c3c7cb5ad635cd64e4aba6e9e19a176987
|
TypeScript
|
aardvarkxr/aardvark
|
/websrc/whiteboard/src/stroke.ts
| 2.640625
| 3
|
import { AvVector } from '@aardvarkxr/aardvark-shared';
import { vec2, vec3 } from '@tlaukkan/tsm';
import Color from 'color';
import { exportGLB, GLTFAsset, Material, Mesh as GltfMesh, Node, Scene, Vertex } from "gltf-js-utils";
import { CatmullRomCurve3, ExtrudeGeometry, ExtrudeGeometryOptions, Geometry, Matrix4, Shape, SphereGeometry, Vector3 } from 'three';
export interface Stroke
{
id: number;
thickness: number;
points?: vec2[];
networkPoints?: AvVector[];
color: string;
}
export function optimizeStroke( stroke: Stroke )
{
if( !stroke || stroke.points.length < 3 )
{
return 0;
}
let pointsRemoved = 0;
while( true )
{
let bestIndex: number;
let bestError = 99999;
// Look for points we can slice out of the stroke because
// their error is too small to matter
for( let n = 0; n < stroke.points.length - 2; n++ )
{
let distN1 = vec2.distance( stroke.points[n], stroke.points[n + 1] );
let distN2 = vec2.distance( stroke.points[n], stroke.points[n + 2] );
let fakeN1 = vec2.mix(stroke.points[n], stroke.points[n+2], distN1/distN2, new vec2() );
let error = vec2.distance(stroke.points[n+1], fakeN1);
if( error < bestError )
{
bestIndex = n + 1;
bestError = error;
}
}
if( !bestIndex || bestError > 0.001 )
{
break;
}
else
{
stroke.points.splice( bestIndex, 1 );
pointsRemoved++;
}
}
return pointsRemoved;
}
function makeVert( pos: vec3, uv?: vec2 )
{
let v1 = new Vertex();
v1.x = pos.x;
v1.y = pos.y;
v1.z = pos.z;
v1.u = uv?.x ?? 0;
v1.v = uv?.y ?? 0;
return v1;
}
function makeCubeMesh( center: vec3, dims: vec3 )
{
const mesh = new GltfMesh();
let v1 = makeVert( new vec3( [ center.x - dims.x/2, center.y - dims.y/2, center.z - dims.z/2 ] ) );
let v2 = makeVert( new vec3( [ center.x - dims.x/2, center.y - dims.y/2, center.z + dims.z/2 ] ) );
let v3 = makeVert( new vec3( [ center.x - dims.x/2, center.y + dims.y/2, center.z - dims.z/2 ] ) );
let v4 = makeVert( new vec3( [ center.x - dims.x/2, center.y + dims.y/2, center.z + dims.z/2 ] ) );
let v5 = makeVert( new vec3( [ center.x + dims.x/2, center.y - dims.y/2, center.z - dims.z/2 ] ) );
let v6 = makeVert( new vec3( [ center.x + dims.x/2, center.y - dims.y/2, center.z + dims.z/2 ] ) );
let v7 = makeVert( new vec3( [ center.x + dims.x/2, center.y + dims.y/2, center.z - dims.z/2 ] ) );
let v8 = makeVert( new vec3( [ center.x + dims.x/2, center.y + dims.y/2, center.z + dims.z/2 ] ) );
// front
mesh.addFace( v4, v2, v8, null, 0 );
mesh.addFace( v2, v6, v8, null, 0 );
// top
mesh.addFace( v8, v3, v4, null, 0 );
mesh.addFace( v3, v8, v7, null, 0 );
// right
mesh.addFace( v6, v7, v8, null, 0 );
mesh.addFace( v7, v6, v5, null, 0 );
// back
mesh.addFace( v5, v1, v7, null, 0 );
mesh.addFace( v7, v1, v3, null, 0 );
// bottom
mesh.addFace( v2, v1, v6, null, 0 );
mesh.addFace( v6, v1, v5, null, 0 );
// left
mesh.addFace( v3, v2, v4, null, 0 );
mesh.addFace( v2, v3, v1, null, 0 );
return mesh;
}
export function strokeToGlb( stroke: Stroke )
{
//Create an array of three.js points for the path
let threePoints:Vector3[];
if( stroke.points )
{
threePoints = stroke.points.map( ( p ) => new Vector3( p.x, p.y, 0 ) );
}
else
{
threePoints = stroke.networkPoints.map( ( p ) => new Vector3( p.x, p.y, 0 ) );
}
let geometry: Geometry = null;
if( threePoints.length == 1 )
{
geometry = new SphereGeometry( stroke.thickness/2, 10, 10 );
let translateMat = new Matrix4();
translateMat.makeTranslation( threePoints[0].x, threePoints[0].y, threePoints[0].z );
geometry.applyMatrix4( translateMat );
}
else
{
var curve = new CatmullRomCurve3( threePoints, false, "chordal", 0.1 );
// make a nice circle shape
const k_circleSegments = 16;
var circle = new Shape();
circle.moveTo( 0, stroke.thickness/2 );
for( let theta = Math.PI/ k_circleSegments; theta <= Math.PI * 2; theta += Math.PI/ k_circleSegments )
{
circle.lineTo(
Math.sin( theta ) * stroke.thickness / 2,
Math.cos( theta ) * stroke.thickness / 2,
);
}
let extrudeSettings:ExtrudeGeometryOptions =
{
steps: threePoints.length * 2,
extrudePath: curve,
};
geometry = new ExtrudeGeometry( circle, extrudeSettings );
}
let asset = new GLTFAsset();
let mesh = new GltfMesh();
let tmpColor = Color( stroke.color );
let mat = new Material();
mat.pbrMetallicRoughness.baseColorFactor =
[
tmpColor.red() / 255,
tmpColor.green() / 255,
tmpColor.blue() / 255,
tmpColor.alpha(),
];
mesh.material = [ mat ];
let verts: Vertex[] = [];
for( let v of geometry.vertices )
{
verts.push( makeVert( new vec3( [ v.x, v.y, v.z ] ) ) );
}
for( let f of geometry.faces )
{
mesh.addFace( verts[ f.a ], verts[ f.b], verts[ f.c ], null, 0 );
}
let scene = new Scene();
let node = new Node();
node.mesh = mesh;
scene.addNode( node );
asset.addScene(scene );
return exportGLB( asset );
}
|
dcb28d6bd7ea6dc8e0e7155ea4fad4ccabb3c3b1
|
TypeScript
|
nhsz/trello-clone
|
/src/reducers/appState.ts
| 2.515625
| 3
|
import { nanoid } from 'nanoid';
import { DragAction, ListAction, TaskAction } from '../actions';
import { AppState } from '../contexts';
import {
emptyAllOtherLists,
findListIndexById,
findTaskList,
getTasksFromOtherLists,
insertItemAtIndex,
moveItem,
overrideListAtIndex,
removeItemAtIndex
} from '../utils';
export type Action = TaskAction | ListAction | DragAction;
type Reducer = (state: AppState, action: Action) => AppState;
const appStateReducer: Reducer = (state, action) => {
switch (action.type) {
case 'ADD_TASK': {
const { lists } = state;
const { id, text, addFirst } = action.payload;
const targetListIndex = findListIndexById(lists, id);
const targetList = lists[targetListIndex];
const newTargetList = {
...targetList,
tasks: addFirst
? [{ id: nanoid(), text }, ...targetList.tasks]
: [...targetList.tasks, { id: nanoid(), text }]
};
return {
...state,
lists: overrideListAtIndex(lists, newTargetList, targetListIndex)
};
}
case 'ADD_LIST': {
return {
...state,
lists: [
...state.lists,
{
id: nanoid(),
title: action.payload,
tasks: []
}
]
};
}
case 'EDIT_TASK': {
const { lists } = state;
const { id, text } = action.payload;
const listId = findTaskList(lists, id);
const targetListIndex = findListIndexById(lists, listId);
const targetList = lists[targetListIndex];
const newTargetList = {
...targetList,
tasks: targetList.tasks.map(task => {
if (task.id === id) {
return {
...task,
text
};
}
return task;
})
};
return {
...state,
lists: overrideListAtIndex(lists, newTargetList, targetListIndex)
};
}
case 'REMOVE_TASK': {
const { lists } = state;
const taskId = action.payload;
const listId = findTaskList(lists, taskId);
const targetListIndex = findListIndexById(lists, listId);
const targetList = lists[targetListIndex];
const newTargetList = {
...targetList,
tasks: targetList.tasks.filter(task => task.id !== taskId)
};
return {
...state,
lists: overrideListAtIndex(lists, newTargetList, targetListIndex)
};
}
case 'REMOVE_LIST': {
const { lists } = state;
const listId = action.payload;
return {
...state,
lists: lists.filter(list => list.id !== listId)
};
}
case 'MOVE_TASK': {
const { lists } = state;
const { dragIndex, hoverIndex, sourceListId, targetListId } = action.payload;
const sourceListIndex = findListIndexById(lists, sourceListId);
const targetListIndex = findListIndexById(lists, targetListId);
const sourceList = lists[sourceListIndex];
const task = sourceList.tasks[dragIndex];
const updatedSourceList = {
...sourceList,
tasks: removeItemAtIndex(sourceList.tasks, dragIndex)
};
const stateWithUpdatedSourceList = {
...state,
lists: overrideListAtIndex(lists, updatedSourceList, sourceListIndex)
};
const targetList = stateWithUpdatedSourceList.lists[targetListIndex];
const updatedTargetList = {
...targetList,
tasks: insertItemAtIndex(targetList.tasks, task, hoverIndex)
};
return {
...stateWithUpdatedSourceList,
lists: overrideListAtIndex(
stateWithUpdatedSourceList.lists,
updatedTargetList,
targetListIndex
)
};
}
case 'MOVE_LIST': {
const { lists } = state;
const { dragIndex, hoverIndex } = action.payload;
return {
...state,
lists: moveItem(lists, dragIndex, hoverIndex)
};
}
case 'MOVE_LIST_TO_POSITION': {
const { lists } = state;
const { listId, index } = action.payload;
const targetListIndex = findListIndexById(lists, listId);
const targetList = lists[targetListIndex];
const updatedLists = removeItemAtIndex(lists, targetListIndex);
return {
...state,
lists: insertItemAtIndex(updatedLists, targetList, index - 1)
};
}
case 'ARCHIVE_ALL_TASKS': {
const { lists } = state;
const listId = action.payload;
const targetListIndex = findListIndexById(lists, listId);
const targetList = lists[targetListIndex];
const newTargetList = {
...targetList,
tasks: []
};
return {
...state,
lists: overrideListAtIndex(lists, newTargetList, targetListIndex)
};
}
case 'MOVE_ALL_TASKS_IN_THIS_LIST': {
const { lists } = state;
const listId = action.payload;
const targetListIndex = findListIndexById(lists, listId);
const targetList = lists[targetListIndex];
const tasksFromOtherLists = getTasksFromOtherLists(lists, listId);
const emptyLists = emptyAllOtherLists(lists, listId);
const newTargetList = {
...targetList,
tasks: targetList.tasks.concat(tasksFromOtherLists)
};
return {
...state,
lists: overrideListAtIndex(emptyLists, newTargetList, targetListIndex)
};
}
case 'SET_DRAGGED_ITEM': {
return {
...state,
draggedItem: action.payload
};
}
default:
return state;
}
};
export { appStateReducer };
|
d1833e06d18d8d87557fc74b33125e52f6647171
|
TypeScript
|
evansb/source-toolchain
|
/src/session.ts
| 3.0625
| 3
|
/**
* Interactive toolchain Session.
*/
import * as es from 'estree'
import * as EventEmitter from 'eventemitter2'
import * as invariant from 'invariant'
import { parse } from './parser'
import { StaticState } from './types/static'
import { createContext } from './context'
import { InterpreterState } from './types/dynamic'
import { evalProgram, createInterpreter } from './interpreter'
import {
VisualizerState,
create as createVisualizer,
next as nextVisualizer
} from './visualizer'
/**
* The instance of this class models an interactive toolchain session.
*
* @example
* const
*/
export class Session extends EventEmitter.EventEmitter2 {
/** Current state of the interpreter */
public interpreter: InterpreterState
/** Current state of the expression visualizer */
public visualizer: VisualizerState
/** Current static analyzer state */
public context: StaticState
private genInterpreter: Iterator<InterpreterState>
constructor(public week: number) {
super()
}
/**
* Re-start the parser, interpreter, and visualizer with
* a new code. Emits start event when done.
*
* @param code The JavaScript code
*/
start(code: string) {
delete this.interpreter
delete this.context
delete this.visualizer
this.evalCode(code)
if (this.interpreter) {
this.emit('start')
}
}
/**
* Evaluate single step of the program.
*/
next() {
invariant(this.genInterpreter, 'start() must be called before calling next')
if (this.interpreter.isRunning) {
const { value: nextInterpreter } = this.genInterpreter.next()
// Stop interpreter on error
if (!nextInterpreter.errors.isEmpty) {
this.emit('errors', nextInterpreter.errors.toJS())
}
// Update states
this.interpreter = nextInterpreter
this.visualizer = nextVisualizer(this.visualizer, this.interpreter)
// Emit appropriate events
if (!this.interpreter.isRunning) {
this.emit('done')
} else {
this.emit('next')
}
}
}
/**
* Evaluate the remaining program until end.
*/
untilEnd() {
while (this.interpreter.isRunning) {
this.next()
}
}
/**
* Evaluate another code.
*
* @param code The code to be evaluated.
*/
addCode(code: string) {
invariant(this.interpreter, 'Must call start() before addCode()')
invariant(
!this.interpreter.isRunning,
'Cannot add more code when previous evaluation is in progress'
)
this.evalCode(code)
this.emit('start')
}
private evalCode(code: string) {
delete this.genInterpreter
this.context = this.context || createContext({ week: this.week })
this.context = parse(code, this.context)
const parserErrors = this.context.parser.errors
if (parserErrors.length > 0) {
this.emit('errors', parserErrors)
this.emit('done')
} else {
this.visualizer = createVisualizer()
this.interpreter = (this.interpreter || createInterpreter()).merge({
isRunning: true
}) as InterpreterState
this.genInterpreter = evalProgram(
this.context.parser.program!,
this.interpreter
)
}
}
}
/**
* Create a new session from some configuration.
*
* @param week The week of the language to be used.
* @returns {Session}
*/
export const createSession = (week: number): Session => {
return new Session(week)
}
|
2282a2a63600c1c7eba76b980908522b93af201f
|
TypeScript
|
jedster1111/simple-vectors
|
/src/vector/createVector.ts
| 3.296875
| 3
|
import { Vector, VectorPosition } from './types';
import { addVectors } from './addVectors';
import { areVectorsEqual } from './areVectorsEqual';
import { calculateVectorArea } from './calculateVectorArea';
import { createPosition } from './createPosition';
import { isVector } from './isVector';
import { scaleVector } from './scaleVector';
import { vectorToKey } from './vectorToKey';
import isNumber from 'is-number';
export function createVector(key: string): Vector;
export function createVector(position: VectorPosition): Vector;
export function createVector(x: number, y: number): Vector;
export function createVector(keyOrPosOrX: string | VectorPosition | number, y?: number): Vector {
const position: VectorPosition = isVector(keyOrPosOrX) ? keyOrPosOrX : getPosition(keyOrPosOrX, y);
const result: Vector = {
x: position.x,
y: position.y,
toString: () => vectorToKey(position),
add: vectorToAdd => addVectors(position, vectorToAdd),
scale: scale => scaleVector(position, scale),
isEqual: vectorToCompare => areVectorsEqual(position, vectorToCompare),
getArea: () => calculateVectorArea(position),
};
return result;
}
function getPosition(xOrKey: string | number, y: number | undefined): VectorPosition {
let position: VectorPosition;
if (typeof xOrKey === 'string' && y === undefined) {
position = createPosition(xOrKey);
} else if (isNumber(xOrKey) && y !== undefined && isNumber(y)) {
position = createPosition(+xOrKey, y);
} else {
throw new Error(`
Parameters don't meet type requirements.
Should either be two numbers, or a single string in the format "x,y".
Instead received "${xOrKey}" & "${y}".
`);
}
return position;
}
|
b1c9265a9b62508c8767d668b45bdfe0f7baed26
|
TypeScript
|
pauek/markright-ts
|
/tests/walk.ts
| 3.328125
| 3
|
import { test } from "uvu";
import * as assert from "uvu/assert";
import * as mr from "../src/markright";
const lines = (lineArray: string[]): string =>
lineArray.map((line) => line + "\n").join("");
test("Walk a text", () => {
const tree = mr.parse(`hi`);
const result = mr.walk(tree, {
[mr.symText]: ({ text }) => text.toUpperCase(),
});
assert.is(result[0], "HI", "Text should be uppercase");
});
test("Double asterisk 1", () => {
const tree = mr.parse(`hola @elm{que} tal`);
const result = mr.walk(tree, {
["elm"]: ({ children }) => `**${children}**`,
});
assert.is(result[0], "hola **que** tal");
});
test("Double asterisk 2", () => {
const tree = mr.parse(`
@elm
some content
@elm
some other content
`);
const result = mr.walk(tree, {
["elm"]: ({ children }) => `**${children}**`,
});
assert.is(
result.map((item) => item + "\n").join(""),
lines(["**some content**", "**some other content**"])
);
});
const doubleAsteriskText = `
some paragraph
in more
than one line
`;
test("Double asterisk 2", () => {
const tree = mr.parse(doubleAsteriskText);
const result = mr.walk(tree, {
[mr.symParagraph]: ({ children }) => children.join("<br>\n"),
});
assert.is(
result[0],
"some paragraph<br>\n" + "in more<br>\n" + "than one line",
"Lines should be joined by <br>"
);
});
test("Arguments", () => {
const tree = mr.parse(`@a(1, 2){content}`);
const result = mr.walk(tree, {
["a"]: ({ args, children }) => `a(${args.join(", ")})[${children}]`,
});
assert.is(result[0], "a(1, 2)[content]");
});
test("Inline element", () => {
const tree = mr.parse(`@elem{hi, there}`);
const result = mr.walk(tree, {
["elem"]: ({ children }) => `[[${children}]]`,
});
assert.is(result[0], "[[hi, there]]");
});
test("Object", () => {
const tree = mr.parse(`
@result
@obj
@name{James}
@age{27}
@obj
@name{John}
@age{13}
`);
const join = (children: mr.Item[] | string): string => {
if (typeof children === "string") {
return children;
} else {
return children.map((item) => item.toString()).join("");
}
};
const result = mr.walk(tree, {
[mr.symParagraph]: ({ children }) => children /* avoid join */,
["name"]: ({ children }) => ({ name: join(children) }),
["age"]: ({ children }) => ({ age: Number(join(children)) }),
["obj"]: ({ children }) => Object.assign({}, ...(children as any)[0]),
["result"]: ({ children }) => children,
});
assert.is(
JSON.stringify(result[0]),
JSON.stringify([
{ name: "James", age: 27 },
{ name: "John", age: 13 },
])
);
});
const htmlText = `
@html(lang="en")
@head
@style*
body { margin: 0; }
@body
@main
@section(class="first")
@h1{A classical page}
@p
Some paragraph
with more than one line
`;
const htmlResult = `<html lang="en">
<head>
<style>
body { margin: 0; }
</style>
</head>
<body>
<main>
<section class="first">
<h1>A classical page</h1>
<p>
Some paragraph with more than one line
</p>
</section>
</main>
</body>
</html>`;
test("HTML 1", () => {
const tree = mr.parse(htmlText);
const html = mr.walk(tree, mr.htmlFuncMap);
assert.is(html[0], htmlResult);
});
test.run();
|
c3f9192aad4d737f9aa17ab760ee004ecd971336
|
TypeScript
|
gribblee/GAME-Match3
|
/typescript-match3/src/matchthree/game/utils/PieceDisplayPool.ts
| 2.609375
| 3
|
import { Sprite } from "pixi.js";
import { AtlasKeys } from "./../../utils/AtlasKeys";
export class PixiSpritePool {
public static spriteList: Map<string, Sprite[]>;
public static init(): void {
this.spriteList = new Map<string, Sprite[]>();
}
public static getImage(assetId: string): Sprite {
if (this.spriteList.get(assetId) === undefined) {
this.spriteList.set(assetId, new Array<Sprite>());
}
const list: Sprite[] = this.spriteList.get(assetId);
let piece: Sprite;
if (list.length === 0) {
const texture = AtlasKeys.getTexture(assetId);
piece = new Sprite(texture);
piece.anchor.set(0.5);
} else {
piece = list.shift();
}
piece.visible = true;
piece.alpha = 1;
piece.scale.set(1);
return piece;
}
public static back(piece: Sprite): void {
const assetId = (<any>piece.texture).textureCacheIds[0];
const list: Sprite[] = this.spriteList.get(assetId);
piece.visible = false;
if (list.indexOf(piece) === -1) {
list.push(piece);
}
}
}
|
88c1086b1ff626f24ec3cde3c5a9f35c2d66d658
|
TypeScript
|
dyotov87/dyotov87.github.io
|
/projects/yuuvis/framework/src/lib/pipes/user.pipe.ts
| 2.71875
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
import { UserService } from '@yuuvis/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
/**
* Transforms any user ID into the users display name.
*
* @example
* <div *ngFor="let id of userIds | DisplayName">...</div>
*/
@Pipe({
name: 'DisplayName',
pure: false
})
export class DisplayNamePipe implements PipeTransform {
constructor(private userService: UserService) {}
transform(value: string, key?: string): Observable<string> {
let input = value;
return this.userService.getUserById(value).pipe(map(val => val.getDisplayNameName()));
}
}
/**
* Transforms any user ID into the users full name.
*
* @example
* <div *ngFor="let id of userIds | FullName">...</div>
*/
@Pipe({
name: 'FullName',
pure: false
})
export class FullNamePipe implements PipeTransform {
constructor(private userService: UserService) {}
transform(value: string, key?: string): any {
let input = value;
return this.userService.getUserById(value).pipe(map(val => val.getFullName()));
}
}
|
d404b3752e200d54a94b263349519e9cc8bf2227
|
TypeScript
|
megazazik/validate
|
/src/index.ts
| 2.734375
| 3
|
import { Result, getErrors } from './result';
export { getErrors };
export type Rule<D, R, Meta> = Meta extends undefined
? (obj: D, meta?: Meta) => R
: (obj: D, meta: Meta) => R;
export type RuleError<K, R extends Rule<any, any, any>> = {
type: K;
data: ReturnType<R>;
};
export type ObjectRules<T, Meta = undefined> = Record<
string,
Rule<T, any, Meta>
>;
export type RulesErrors<T, Rules extends ObjectRules<T, any>> = {
[R in keyof Rules]: RuleError<R, Rules[R]>;
};
export type ValidationScheme<Data, Result, Meta = undefined> = {
validate: (
...args: Meta extends undefined ? [Data, any?] : [Data, Meta]
) => null | Result;
};
type ChildMeta<T, Meta> = {
data: T;
meta: Meta;
fieldName: keyof T;
};
type ChildrenRules<T, Meta> = {
[F in keyof T]?:
| ValidationScheme<T[F], any, ChildMeta<T, Meta>>
| ObjectRules<T[F], ChildMeta<T, Meta>>;
};
type ObjectRulesNames<D, C extends SchemeRules<D, any>> = {
[F in keyof C]: C[F] extends Rule<D, any, any> ? F : never;
}[keyof C];
type ChildRulesNames<D, C extends SchemeRules<D, any>> = {
[F in keyof C]: F extends keyof D ? F : never;
}[keyof C];
type CheckIfEmptyKeys<Keys, Success, Wrong> = Wrong extends (Keys extends never
? Success
: Wrong)
? Wrong
: Success;
type ErrorsOf<T> = { errors: Array<T[keyof T]> | null };
export type ChildResult<
Children extends {
[F: string]: undefined | ValidationScheme<any, any, any>;
}
> = {
[F in keyof Children]?: Children[F] extends ValidationScheme<any, any, any>
? ReturnType<Children[F]['validate']>
: never;
};
export type ValidationResult<
Data,
Rules extends { [R: string]: Rule<Data, any, any> },
Children extends { [F in keyof Data]?: ValidationScheme<Data[F], any, any> }
> = null | Readonly<
ChildResult<Children> &
ErrorsOf<RulesErrors<any, Rules>> &
{ [R in keyof Rules]?: ReturnType<Rules[R]> }
>;
export type SchemeRules<D, Meta> = Record<
string,
| Rule<D, any, Meta>
| ValidationScheme<any, any, any>
| {
[R: string]: Rule<any, any, any>;
}
>;
export type CastSchemeMeta<S, NewMeta> = S extends Scheme<
infer D,
infer R,
infer C,
infer M
>
? NewMeta extends M
? Scheme<D, R, C, NewMeta>
: 'New meta type should extend old one'
: S extends PrimitiveScheme<infer D, infer R, infer M>
? NewMeta extends M
? PrimitiveScheme<D, R, NewMeta>
: 'New meta type should extend old one'
: never;
export interface Scheme<
Data,
Rules extends ObjectRules<Data, Meta>,
Children extends {
[F in keyof Data]?: ValidationScheme<
Data[F],
any,
ChildMeta<Data, Meta>
>;
} = {},
Meta = undefined
>
extends ValidationScheme<
Data,
ValidationResult<Data, Rules, Children>,
Meta
> {
rules<C extends SchemeRules<Data, Meta>>(
children: C & ChildrenRules<Data, Meta>
): CheckIfEmptyKeys<
Exclude<keyof C, ChildRulesNames<Data, C> | ObjectRulesNames<Data, C>>,
Scheme<
Data,
Rules & Pick<C, ObjectRulesNames<Data, C>>,
Children &
ChildrenSchemes<
Data,
Pick<C, ChildRulesNames<Data, C>>,
ChildMeta<Data, Meta>
>,
Meta
>,
| 'Wrong type of rules. Check the following fields:'
| Exclude<keyof C, ChildRulesNames<Data, C> | ObjectRulesNames<Data, C>>
>;
rules<C extends SchemeRules<Data, Meta>>(
children: (rules: Rules & Children) => C & ChildrenRules<Data, Meta>
): CheckIfEmptyKeys<
Exclude<keyof C, ChildRulesNames<Data, C> | ObjectRulesNames<Data, C>>,
Scheme<
Data,
Rules & Pick<C, ObjectRulesNames<Data, C>>,
Children &
ChildrenSchemes<
Data,
Pick<C, ChildRulesNames<Data, C>>,
ChildMeta<Data, Meta>
>,
Meta
>,
| 'Wrong type of rules. Check the following fields:'
| Exclude<keyof C, ChildRulesNames<Data, C> | ObjectRulesNames<Data, C>>
>;
getRules(): Rules & Children;
}
export interface PrimitiveScheme<
Data,
Rules extends ObjectRules<Data, unknown>,
Meta = undefined
> extends ValidationScheme<Data, ValidationResult<Data, Rules, {}>, Meta> {
rules<NewRules extends Record<string, Rule<Data, any, Meta>>>(
children: NewRules
): PrimitiveScheme<Data, Rules & NewRules, Meta>;
getRules(): Rules;
}
export type ChildrenSchemes<
Data,
Rules extends ChildrenRules<any, any>,
Meta
> = {
[Child in keyof Rules]: ChildScheme<
Rules[Child],
Child extends keyof Data ? Data[Child] : any,
Meta
>;
};
export type ChildScheme<
C extends
| ValidationScheme<any, any, any>
| { [R: string]: Rule<any, any, any> }
| undefined,
Data,
Meta
> = C extends ValidationScheme<any, any>
? C
: Data extends object
? Scheme<
Data,
C extends Record<string, Rule<any, any, Meta>> ? C : {},
{},
Meta
>
: PrimitiveScheme<Data, C extends undefined ? {} : C, Meta>;
export function init<Data, Meta = undefined>(): Data extends object
? Scheme<Data, {}, {}, Meta>
: PrimitiveScheme<Data, {}, Meta>;
export function init<Data, Meta = undefined>(
rules = {},
schemes = {}
): Data extends object
? Scheme<Data, {}, {}, Meta>
: PrimitiveScheme<Data, {}, Meta> {
return new Builder<Data, {}, {}>(rules, schemes) as any;
}
export type RulesOfScheme<S extends Scheme<any, any, any>> = S extends Scheme<
any,
infer R,
any
>
? R
: never;
export type ChildrenOfScheme<
S extends Scheme<any, any, any>
> = S extends Scheme<any, any, infer R> ? R : never;
class Builder<
Data,
Rules extends { [R: string]: Rule<Data, any, Meta> },
Children extends {
[F in keyof Data]?: ValidationScheme<
Data[F],
any,
ChildMeta<Data, Meta>
>;
} = {},
Meta = undefined
> implements Scheme<Data, Rules, Children, Meta> {
constructor(private _fullObjectRules: Rules, private _rules: Children) {}
rules<C extends SchemeRules<Data, Meta>>(
fullRules:
| (C & ChildrenRules<Data, Meta>)
| ((rules: Rules & Children) => C & ChildrenRules<Data, Meta>)
) {
const [childrenRules, rules] = separateRules(
typeof fullRules === 'function'
? fullRules(this.getRules())
: fullRules
);
const convertedRules = Object.keys(childrenRules).reduce(
(prev, propertyName) => ({
...prev,
[propertyName]:
typeof (childrenRules as any)[propertyName].validate ===
'function'
? (childrenRules as any)[propertyName]
: init<object>().rules(
(childrenRules as any)[propertyName]
)
}),
{}
);
return new Builder(
{ ...this._fullObjectRules, ...rules },
{ ...this._rules, ...convertedRules }
) as any;
}
validate(
...args: Meta extends undefined ? [Data, any?] : [Data, Meta]
): ValidationResult<Data, Rules, Children> {
let hasErrors = false;
const ownRulesErrors = validateRules(
args[0],
this._fullObjectRules,
args[1]!
);
if (ownRulesErrors) {
hasErrors = true;
}
const errors: any = new Result(ownRulesErrors || {});
if (args[0] != null) {
Object.keys(this._rules).forEach(key => {
const res = (this._rules as any)[key].validate(
(args[0] as any)[key],
{
data: args[0],
meta: args[1],
fieldName: key
}
);
if (res) {
hasErrors = true;
errors[key] = res;
}
});
}
return hasErrors ? errors : null;
}
getRules(): Rules & Children {
return { ...this._fullObjectRules, ...this._rules };
}
}
function separateRules(
rules: SchemeRules<any, any>
): [ChildrenRules<any, any>, Record<string, Rule<any, any, any>>] {
const childrenRules: ChildrenRules<any, any> = {};
const objectRules: Record<string, Rule<any, any, any>> = {};
for (const key in rules) {
const rule = rules[key];
if (typeof rule === 'function') {
objectRules[key] = rule;
} else {
childrenRules[key] = rule as any;
}
}
return [childrenRules, objectRules];
}
export function validateRules<D, Meta = undefined>(
data: D,
rules: { [R: string]: Rule<D, any, Meta> },
meta: Meta
) {
let errors: any = null;
Object.keys(rules).find(key => {
if ((rules[key] as any).isAllOfFlag === isAllOfFlag) {
const allOfRules = rules[key](data, meta);
const allErrors: any = {};
let hasError = false;
Object.keys(allOfRules).forEach(ruleKey => {
const res = allOfRules[ruleKey](data, meta);
if (res === false || res == null) {
return;
}
hasError = true;
allErrors[ruleKey] = res;
});
if (hasError) {
errors = allErrors;
return true;
}
return false;
}
const result = rules[key](data, meta);
if (result === false || result == null) {
return false;
}
errors = { [key]: result };
return true;
});
return errors;
}
// все из списка правил
const isAllOfFlag = {};
export function allOf<
T,
Rules extends { [R: string]: Rule<T, any, Meta> },
Meta
>(rules: Rules): Rules {
return Object.keys(rules).reduce((prev, key, index) => {
if (index === 0) {
const rule: any = () => rules;
rule.isAllOfFlag = isAllOfFlag;
return { ...prev, [key]: rule };
}
return { ...prev, [key]: () => false };
}, {}) as any;
}
// правила для массивов
export function list<Data, Result, Meta = undefined>(
scheme: ValidationScheme<
Data,
Result,
{
data: Data[];
meta: Meta;
index: number;
}
>
): ValidationScheme<Data[], Array<Result | null>, Meta> {
return {
validate: (
...args: Meta extends undefined ? [Data[], any?] : [Data[], Meta]
) => {
let hasError = false;
const result = args[0].map((d, index) => {
const res = scheme.validate(d, {
meta: args[1],
data: args[0],
index
});
if (res) {
hasError = true;
}
return res;
});
return hasError ? result : null;
}
};
}
// правила для объектов
export function map<Data, Result, Meta = undefined>(
scheme: ValidationScheme<
Data,
Result,
{
fieldName: string;
meta: Meta;
data: Record<string, Data>;
}
>
): ValidationScheme<Record<string, Data>, Record<string, Result | null>, Meta> {
return {
validate: (
...args: Meta extends undefined
? [Record<string, Data>, any?]
: [Record<string, Data>, Meta]
) => {
let hasError = false;
const result = Object.keys(args[0]).reduce((prev, name) => {
const res = scheme.validate(args[0][name], {
meta: args[1],
data: args[0],
fieldName: name
});
hasError = !!res || hasError;
return {
...prev,
[name]: res
};
}, {});
return hasError ? result : null;
}
};
}
export function passMeta<Data, Result, Meta, Key extends string>(
key: Key,
scheme: ValidationScheme<Data, Result, Meta>
): ValidationScheme<Data, Result, { [K in Key]: Meta }>;
export function passMeta<Data, Result, Meta, NewMeta>(
key: (meta: NewMeta) => Meta,
scheme: ValidationScheme<Data, Result, Meta>
): ValidationScheme<Data, Result, NewMeta>;
export function passMeta<Data, Result, Meta>(
key: string | ((m: any) => any),
scheme: ValidationScheme<Data, Result, Meta>
) {
return {
validate(data: Data, meta?: any) {
return (scheme as any).validate(
data,
typeof key === 'string' ? meta?.[key] : key(meta)
);
}
};
}
|
f3ae2836bac30288a156ce9a1ab9aad75864bb10
|
TypeScript
|
fossabot/streamdeck-events
|
/test/Events/Streamdeck/Sent/WillAppearEventTest.ts
| 2.609375
| 3
|
import 'mocha';
import { expect, use } from 'chai';
import { WillAppearEvent } from '@/Events/Streamdeck/Sent';
import { WillAppearType } from '@/StreamdeckTypes/Sent';
import jsonschema from 'chai-json-schema';
use(jsonschema);
describe('WillAppearEvent test', () => {
it('validates the event against the json schema', () => {
const event = new WillAppearEvent('action', 'context');
expect(JSON.parse(JSON.stringify(event))).to.be.jsonSchema(WillAppearType);
});
it('returns the right default values for the event', () => {
const event = new WillAppearEvent('action312', 'context312');
const parse: WillAppearType = JSON.parse(JSON.stringify(event));
expect(parse.action).to.equal('action312');
expect(parse.context).to.equal('context312');
expect(parse.event).to.equal('willAppear');
expect(parse.payload.coordinates.column).to.equal(1);
expect(parse.payload.coordinates.row).to.equal(1);
expect(parse.payload.isInMultiAction).to.be.false;
});
it('returns the right values for the changed options', () => {
const event = new WillAppearEvent('action312', 'context312', {
column: 3,
device: 'lala',
isInMultiAction: true,
row: 4,
settings: { bar: 'baz', foo: true },
});
const parse: WillAppearType = JSON.parse(JSON.stringify(event));
expect(parse.payload.coordinates.column).to.equal(3);
expect(parse.payload.coordinates.row).to.equal(4);
expect(parse.payload.isInMultiAction).to.be.true;
expect((parse.payload.settings as Record<string, boolean>).foo).to.be.true;
expect((parse.payload.settings as Record<string, string>).bar).to.equal('baz');
});
});
|
3e13d23e6960a43ecc9886d40b29493647a5427e
|
TypeScript
|
Chortech/chortech-backend
|
/common/src/events/base-pulisher.ts
| 2.5625
| 3
|
import { Stan } from "node-nats-streaming";
import { Event } from "./base-event";
export abstract class Publisher<T extends Event> {
abstract subject: T["subject"];
private client: Stan;
constructor(client: Stan) {
this.client = client;
}
publish(data: T["data"]): Promise<string> {
return new Promise((res, rej) => {
this.client.publish(this.subject, JSON.stringify(data), (err, id) => {
if (err) return rej(err);
console.log(`Event ${this.subject}:${id} published.`);
res(id);
});
});
}
}
|
66e857b8abc322c59a5d8f91e5e972c4058013f6
|
TypeScript
|
tobidot/diffuse_light_plattformer
|
/src/game/RendererWebGL.ts
| 2.75
| 3
|
import { MapRenderer } from "./Map";
import Field from "./Field";
import Camera from "./Camera";
class RayResult {
public x: number = 0;
public y: number = 0;
public z: number = 0;
public distance: number = 0;
}
/*
export default class RendererWebGL implements MapRenderer {
private resolution_width: number;
private resolution_height: number;
private map_width: number;
private map_height: number;
private image_data: ImageData;
private current_fields_array: Array<Field>;
private camera_x: number;
private camera_y: number;
private camera_zoom: number;
private camera: Camera;
constructor(resolution_width: number, resolution_height: number, map_width: number, map_height: number) {
this.resolution_width = resolution_width;
this.resolution_height = resolution_height;
this.map_width = map_width;
this.map_height = map_height;
this.image_data = new ImageData(resolution_width, resolution_height);
this.current_fields_array = new Array<Field>();
this.camera_x = 0;
this.camera_y = 0;
this.camera_zoom = 1;
this.camera = new Camera();
}
public draw(target: RenderingContext, fields: Array<Field>): void {
if (target instanceof CanvasRenderingContext2D == false) {
throw "Invalid renderer for this render target";
}
const max_ray_distance = 100;
this.current_fields_array = fields;
for (let x = 0; x < this.resolution_width; ++x) {
for (let y = 0; y < this.resolution_height; ++y) {
let ray_position =
let ray_position_x = (x - this.resolution_width / 2) / this.camera_zoom + this.camera_x;
let ray_position_y = (y - this.resolution_height / 2) / this.camera_zoom + this.camera_y;
let ray_position_z = 50;
let ray_result = this.trace_ray([ray_position_x, ray_position_y, ray_position_z], max_ray_distance);
let color = [127, 127, 127, 255];
if (ray_result !== false) {
color = this.get_color_at_position(Math.trunc(ray_result.x), Math.trunc(ray_result.y));
let ray_distance_percent = ray_result.distance / max_ray_distance
let gray_factor = ray_distance_percent * ray_distance_percent;
color[0] = color[0] * (1 - gray_factor) + 127 * gray_factor;
color[1] = color[1] * (1 - gray_factor) + 127 * gray_factor;
color[2] = color[2] * (1 - gray_factor) + 127 * gray_factor;
}
let target_base = (x + y * this.resolution_width) * 4;
this.image_data.data[target_base + 0] = color[0];
this.image_data.data[target_base + 1] = color[1];
this.image_data.data[target_base + 2] = color[2];
this.image_data.data[target_base + 3] = color[3];
}
}
(target as CanvasRenderingContext2D).putImageData(this.image_data, 0, 0);
}
public set_camera(x: number, y: number, zoom: number) {
this.camera_x = x;
this.camera_y = y;
this.camera_zoom = zoom;
}
private trace_ray(ray: [number, number, number], max_iterations: number): RayResult | false {
let iterations = 0;
let [x, y, z] = ray;
let vx = 0, vy = 0, vz = -1;
// START --- define demo diffusing object
let t = performance.now() / 1000;
let sphereX = Math.sin(t) * this.map_width / 4 + this.map_width / 2;
let sphereY = Math.cos(t) * this.map_height / 4 + this.map_height / 2;
let sphereZ = 25;
let size = 50;
let strength = 0.005;
// END --- define demo diffusing object
while (z > 0 && iterations < max_iterations) {
let dx = sphereX - x;
let dy = sphereY - y;
let dz = sphereZ - z;
let d2 = dx * dx + dy * dy + dz * dz;
if (d2 < size * size) {
let d = Math.sqrt(d2);
let close_factor = 1 - d / size;
vx += (dx * close_factor) * strength;
vy += (dy * close_factor) * strength;
vz += (dz * close_factor) * strength;
}
x += vx;
y += vy;
z += vz;
iterations++;
}
if (iterations >= max_iterations) return false;
return { x, y, z, distance: iterations };
}
private get_color_at_position(x: number, y: number): number[] {
let field = this.get_field_at_position(x, y);
if (field === false) return [0, 0, 0, 255];
if (field.type === "Rock") {
return [0, 255, 0, 255];
} else if ("Solid") {
return [255, 0, 0, 255];
}
return [0, 0, 0, 255];
}
private get_field_at_position(x: number, y: number): Field | false {
if (x < 0 || x >= this.map_width || y < 0 || y >= this.map_height) return false;
return this.current_fields_array[x + y * this.map_width];
}
}
*/
|
ea28a763069e1829b20cee55f4473db56b4e636d
|
TypeScript
|
ylerjen/classe84.front
|
/src/app/models/User.ts
| 3.265625
| 3
|
export enum EGender {
Male = 'M',
Female = 'F'
}
/**
* A user object that describe a member person
*/
export class User {
public id: string;
public last_name: string;
public maiden_name: string;
public first_name: string;
public gender: EGender;
public birthdate: Date;
public is_active: boolean;
public email: string;
public phone: string;
public mobile: string;
public fb_user_id: string;
public fb_profile_name: string;
public website: string;
public created_at: string;
public updated_at: string;
public permissions: Array<any>;
get fullname(): string {
let name = '';
if (this.first_name) {
name += `${this.first_name}`;
}
if (this.maiden_name) {
name += ` (${this.maiden_name})`;
}
if (this.last_name) {
name += ` ${this.last_name}`;
}
return name;
}
/**
* This is a comparator to sort a user list by the user fullname
*/
static sortByFullNameComparator = function(u1: User, u2: User): number {
if (u1.fullname < u2.fullname) {
return -1;
} else if (u1.fullname > u2.fullname) {
return 1;
} else {
return 0;
}
};
constructor(props: { [key: string]: any } = {}) {
this.id = props.id;
this.last_name = props.last_name;
this.maiden_name = props.maiden_name;
this.first_name = props.first_name;
this.gender = props.gender;
this.birthdate = props.birthdate;
this.is_active = props.is_active;
this.email = props.email;
this.phone = props.phone;
this.mobile = props.mobile;
this.fb_user_id = props.fb_user_id;
this.fb_profile_name = props.fb_profile_name;
this.website = props.website;
this.created_at = props.created_at;
this.updated_at = props.updated_at;
}
/**
* Calculate the age of the person at a given date
* @param [refDate=now()] is the date used to calculate the age. If none is passed, current date is used.
* @returns {number} the calculated age
*/
getAge(refDate: Date): number {
if (typeof refDate === 'undefined') {
refDate = new Date();
}
let age = refDate.getFullYear() - this.birthdate.getFullYear();
const m = refDate.getMonth() - this.birthdate.getMonth();
if (m < 0 || (m === 0 && refDate.getDate() < this.birthdate.getDate())) {
age--;
}
return age;
}
}
|
9811b2599a79b3ba84f3f697e2e95a82df958760
|
TypeScript
|
Aslanchik/tsfiddle
|
/src/models/project.ts
| 2.84375
| 3
|
// Project Type
export enum ProjectStatus { Active, Finished};
export class Project {
constructor(public id:string, public title:string, public description:string, public people:number, public projectStatus:ProjectStatus){}
}
|
f40bf178ec7397d0baaa5220e16ccf4f5ea6e37e
|
TypeScript
|
tk1cntt/drop-shipping-backend
|
/src/main/webapp/app/entities/order-history/order-history.reducer.ts
| 2.546875
| 3
|
import axios from 'axios';
import { ICrudGetAction, ICrudGetAllAction, ICrudPutAction, ICrudDeleteAction } from 'react-jhipster';
import { cleanEntity } from 'app/shared/util/entity-utils';
import { REQUEST, SUCCESS, FAILURE } from 'app/shared/reducers/action-type.util';
import { IOrderHistory, defaultValue } from 'app/shared/model/order-history.model';
export const ACTION_TYPES = {
FETCH_ORDERHISTORY_LIST: 'orderHistory/FETCH_ORDERHISTORY_LIST',
FETCH_ORDERHISTORY: 'orderHistory/FETCH_ORDERHISTORY',
CREATE_ORDERHISTORY: 'orderHistory/CREATE_ORDERHISTORY',
UPDATE_ORDERHISTORY: 'orderHistory/UPDATE_ORDERHISTORY',
DELETE_ORDERHISTORY: 'orderHistory/DELETE_ORDERHISTORY',
RESET: 'orderHistory/RESET'
};
const initialState = {
loading: false,
errorMessage: null,
entities: [] as ReadonlyArray<IOrderHistory>,
entity: defaultValue,
updating: false,
updateSuccess: false
};
export type OrderHistoryState = Readonly<typeof initialState>;
// Reducer
export default (state: OrderHistoryState = initialState, action): OrderHistoryState => {
switch (action.type) {
case REQUEST(ACTION_TYPES.FETCH_ORDERHISTORY_LIST):
case REQUEST(ACTION_TYPES.FETCH_ORDERHISTORY):
return {
...state,
errorMessage: null,
updateSuccess: false,
loading: true
};
case REQUEST(ACTION_TYPES.CREATE_ORDERHISTORY):
case REQUEST(ACTION_TYPES.UPDATE_ORDERHISTORY):
case REQUEST(ACTION_TYPES.DELETE_ORDERHISTORY):
return {
...state,
errorMessage: null,
updateSuccess: false,
updating: true
};
case FAILURE(ACTION_TYPES.FETCH_ORDERHISTORY_LIST):
case FAILURE(ACTION_TYPES.FETCH_ORDERHISTORY):
case FAILURE(ACTION_TYPES.CREATE_ORDERHISTORY):
case FAILURE(ACTION_TYPES.UPDATE_ORDERHISTORY):
case FAILURE(ACTION_TYPES.DELETE_ORDERHISTORY):
return {
...state,
loading: false,
updating: false,
updateSuccess: false,
errorMessage: action.payload
};
case SUCCESS(ACTION_TYPES.FETCH_ORDERHISTORY_LIST):
return {
...state,
loading: false,
entities: action.payload.data
};
case SUCCESS(ACTION_TYPES.FETCH_ORDERHISTORY):
return {
...state,
loading: false,
entity: action.payload.data
};
case SUCCESS(ACTION_TYPES.CREATE_ORDERHISTORY):
case SUCCESS(ACTION_TYPES.UPDATE_ORDERHISTORY):
return {
...state,
updating: false,
updateSuccess: true,
entity: action.payload.data
};
case SUCCESS(ACTION_TYPES.DELETE_ORDERHISTORY):
return {
...state,
updating: false,
updateSuccess: true,
entity: {}
};
case ACTION_TYPES.RESET:
return {
...initialState
};
default:
return state;
}
};
const apiUrl = 'api/order-histories';
// Actions
export const getEntities: ICrudGetAllAction<IOrderHistory> = (page, size, sort) => ({
type: ACTION_TYPES.FETCH_ORDERHISTORY_LIST,
payload: axios.get<IOrderHistory>(`${apiUrl}?cacheBuster=${new Date().getTime()}`)
});
export const getEntity: ICrudGetAction<IOrderHistory> = id => {
const requestUrl = `${apiUrl}/${id}`;
return {
type: ACTION_TYPES.FETCH_ORDERHISTORY,
payload: axios.get<IOrderHistory>(requestUrl)
};
};
export const createEntity: ICrudPutAction<IOrderHistory> = entity => async dispatch => {
const result = await dispatch({
type: ACTION_TYPES.CREATE_ORDERHISTORY,
payload: axios.post(apiUrl, cleanEntity(entity))
});
dispatch(getEntities());
return result;
};
export const updateEntity: ICrudPutAction<IOrderHistory> = entity => async dispatch => {
const result = await dispatch({
type: ACTION_TYPES.UPDATE_ORDERHISTORY,
payload: axios.put(apiUrl, cleanEntity(entity))
});
dispatch(getEntities());
return result;
};
export const deleteEntity: ICrudDeleteAction<IOrderHistory> = id => async dispatch => {
const requestUrl = `${apiUrl}/${id}`;
const result = await dispatch({
type: ACTION_TYPES.DELETE_ORDERHISTORY,
payload: axios.delete(requestUrl)
});
dispatch(getEntities());
return result;
};
export const reset = () => ({
type: ACTION_TYPES.RESET
});
|
82ce5753fe6c355b7400ef6a8d41f5b4dc59f2ab
|
TypeScript
|
javfres/javicv
|
/src/ts/server.ts
| 2.703125
| 3
|
import http from 'http';
import express, {Application} from 'express';
import nunjucks from 'nunjucks';
import sass from 'sass';
import { CVError } from './cverror';
import inlineSVG from './inlineSVG';
/**
* This is an express server to handle all the resources needed to render the pdf
*/
export default class Server {
// Default debug port
public static readonly DEV_PORT = 4444;
//
// Attributes
//
app: Application|null = null;
server:http.Server|null = null;
data?: object;
port = 0;
/**
* Start a express server
* @param debug If true, sets a given port instead a random one
*/
async start(debug=false) {
// Init the template library
const env = nunjucks.configure( __dirname + '/../../src/templates/', {
autoescape: true,
noCache:true
});
env.addFilter('is_string', function(obj) {
return typeof obj == 'string';
});
//
// Create the server
//
this.app = express();
if (debug) {
console.log(`http://localhost:${Server.DEV_PORT}`);
this.server = this.app.listen(Server.DEV_PORT);
} else {
this.server = this.app.listen();
}
this.initRoutes();
//
// Get the used port
//
const addr = this.server.address();
if(addr && typeof addr !== 'string'){
this.port = addr.port;
} else {
throw new CVError("Unable to launch server");
}
} // start
/**
* Stop the server
*/
async stop() {
if (this.server) {
this.server.close();
}
}
/**
* Set the data used in the template library
*/
setData(data: object) {
this.data = data;
}
/**
* Define the routes
*/
initRoutes() {
// Check the app is running
if (!this.app) {
throw new CVError("No express app");
}
// Default route
this.app.get('/', (req, res) => {
if (!this.data) {
res.send("No data");
return;
}
const html = nunjucks.render('index.njk', {
...this.data,
inlineSVG
});
res.send(html);
});
// The style
this.app.get('/style.css', async (req, res) => {
const path = __dirname + '/../../src/style/main.scss';
try {
const sassResult = await sass.compileAsync(path);
res.setHeader('Content-Type', 'text/css');
res.send(sassResult.css);
} catch (e) {
const msg = e instanceof Error ? e.message : 'SCSS Error';
res.status(500).send(msg);
}
});
// Static imgs route
this.app.use('/imgs', express.static( __dirname + '/../../src/imgs'));
}
}
|
ad809abf64bf3fee784891749c7da598e2c62e56
|
TypeScript
|
cdimascio/express-openapi-validator
|
/src/framework/modded.express.mung.ts
| 2.859375
| 3
|
/* istanbul ignore file */
/**
* Modification of richardschneider;s mung
* https://github.com/richardschneider/express-mung *
*/
'use strict';
let mung: any = {};
let faux_fin = { end: () => null };
function isScalar(v) {
return typeof v !== 'object' && !Array.isArray(v);
}
mung.onError = (err, req, res, next) => {
res
.status(500)
.set('content-language', 'en')
.json({ message: err.message })
.end();
return res;
};
mung.json = function json(fn, options) {
return function(req, res, next) {
let original = res.json;
options = options || {};
let mungError = options.mungError;
function json_hook(json) {
let originalJson = json;
res.json = original;
if (res.headersSent) return res;
if (!mungError && res.statusCode >= 500) return original.call(this, json);
// Run the munger
try {
json = fn(json, req, res);
} catch (e) {
return mung.onError(e, req, res, next);
}
if (res.headersSent) return res;
// If no returned value from fn, then assume json has been mucked with.
if (json === undefined) json = originalJson;
// If null, then 204 No Content
if (json === null) return res.status(204).end();
// If munged scalar value, then text/plain
if (originalJson !== json && isScalar(json)) {
res.set('content-type', 'text/plain');
return res.send(String(json));
}
return original.call(this, json);
}
res.json = json_hook;
next && next();
};
};
mung.jsonAsync = function json(fn, options) {
return function(req, res, next) {
let original = res.json;
options = options || {};
let mungError = options.mungError;
function json_async_hook(json) {
let originalJson = json;
res.json = original;
if (res.headersSent) return;
if (!mungError && res.statusCode >= 400) return original.call(this, json);
try {
fn(json, req, res)
.then(json => {
if (res.headersSent) return;
// If null, then 204 No Content
if (json === null) return res.status(204).end();
// If munged scalar value, then text/plain
if (json !== originalJson && isScalar(json)) {
res.set('content-type', 'text/plain');
return res.send(String(json));
}
return original.call(this, json);
})
.catch(e => mung.onError(e, req, res, next));
} catch (e) {
mung.onError(e, req, res, next);
}
return faux_fin;
}
res.json = json_async_hook;
next && next();
};
};
mung.headers = function headers(fn) {
return function(req, res, next) {
let original = res.end;
function headers_hook() {
res.end = original;
if (!res.headersSent) {
try {
fn(req, res);
} catch (e) {
return mung.onError(e, req, res, next);
}
if (res.headersSent) {
console.error(
'sending response while in mung.headers is undefined behaviour',
);
return;
}
}
return original.apply(this, arguments);
}
res.end = headers_hook;
next && next();
};
};
mung.headersAsync = function headersAsync(fn) {
return function(req, res, next) {
let original = res.end;
let onError = e => {
res.end = original;
return mung.onError(e, req, res, next);
};
function headers_async_hook() {
if (res.headersSent) return original.apply(this, null); // (this, args)
let args = arguments;
res.end = () => null;
try {
fn(req, res)
.then(() => {
res.end = original;
if (res.headersSent) return;
original.apply(this, args);
})
.catch(e => onError(e));
} catch (e) {
onError(e);
}
}
res.end = headers_async_hook;
next && next();
};
};
mung.write = function write(fn, options: any = {}) {
return function(req, res, next) {
const original = res.write;
const mungError = options.mungError;
function write_hook(chunk, encoding, callback) {
// If res.end has already been called, do nothing.
if (res.finished) {
return false;
}
// Do not mung on errors
if (!mungError && res.statusCode >= 400) {
return original.apply(res, arguments);
}
try {
let modifiedChunk = fn(
chunk,
// Since `encoding` is an optional argument to `res.write`,
// make sure it is a string and not actually the callback.
typeof encoding === 'string' ? encoding : null,
req,
res,
);
// res.finished is set to `true` once res.end has been called.
// If it is called in the mung function, stop execution here.
if (res.finished) {
return false;
}
// If no returned value from fn, then set it back to the original value
if (modifiedChunk === undefined) {
modifiedChunk = chunk;
}
return original.call(res, modifiedChunk, encoding, callback);
} catch (err) {
return mung.onError(err, req, res, next);
}
}
res.write = write_hook;
next && next();
};
};
export default mung;
|
064a17cea424c7f1bafbc6b37da945e4f9cb613c
|
TypeScript
|
borisenki/SpaceShooterGame
|
/assets/Game/Player/Bullet.ts
| 2.546875
| 3
|
const { ccclass, property } = cc._decorator;
@ccclass
export default class Bullet extends cc.Component {
@property(cc.Vec2)
direction: cc.Vec2 = null;
@property
speed: number = 1000;
onCollisionEnter(other) {
if (this.node.parent) {
this.node.parent.removeChild(this.node);
}
}
update(dt) {
this.node.y += this.speed * dt * this.direction.y;
this.node.x += this.speed * dt * this.direction.x;
}
}
|
83f10e6f2d659f12ac0c46ab9f675239e2ad3fc4
|
TypeScript
|
sunke/codenest
|
/design-patterns-ts/src/visitor.ts
| 3.703125
| 4
|
import { PatternDemo } from "./pattern";
let name = "Visitor Design Pattern";
let description = `
Represent an operation to be performed on elements of an object structure.
Visitor lets you define a new option without changing the classes of the
elements on which it operates. Visitor pattern is commonly used in parser
implementations.
`;
//----------------------------------------------------------------------------------
interface Node {
accept(visitor: Visitor);
setChildRight(node: Node): Node;
setChildLeft(node: Node): Node;
}
abstract class AbstractNode implements Node {
childRight: Node = null;
childLeft: Node = null;
abstract accept(visitor: Visitor);
setChildRight(node: Node): Node {
this.childRight = node;
return this;
}
setChildLeft(node: Node): Node {
this.childLeft = node;
return this;
}
}
class NodeA extends AbstractNode {
accept(visitor: Visitor) {
visitor.visitNodeA(this);
}
}
class NodeB extends AbstractNode {
accept(visitor: Visitor) {
visitor.visitNodeB(this);
}
}
class NodeC extends AbstractNode {
accept(visitor: Visitor) {
visitor.visitNodeC(this);
}
}
interface Visitor {
visitNodeA(node: NodeA);
visitNodeB(node: NodeB);
visitNodeC(node: NodeC);
}
class TreeVisitor implements Visitor {
visitNodeA(node: NodeA) {
console.log("Visit NodeA");
if (node.childLeft != null) {
node.childLeft.accept(this);
}
if (node.childRight != null) {
node.childRight.accept(this);
}
}
visitNodeB(node: NodeB) {
console.log("Visit NodeB")
if (node.childLeft != null) {
node.childLeft.accept(this);
}
if (node.childRight != null) {
node.childRight.accept(this);
}
}
visitNodeC(node: NodeC) {
console.log("Visit NodeC");
if (node.childLeft != null) {
node.childLeft.accept(this);
}
if (node.childRight != null) {
node.childRight.accept(this);
}
}
}
//----------------------------------------------------------------------------------
PatternDemo.show(name, description, () => {
let root = new NodeA();
root.setChildLeft(new NodeB().setChildLeft(new NodeC()).setChildRight(null))
.setChildRight(new NodeC().setChildLeft(null).setChildRight(new NodeC()));
root.accept(new TreeVisitor());
});
|
953e61c3f53c5c2194db16bc8ded4179b54030ca
|
TypeScript
|
cborac/node-discord
|
/lib/api/rateLimit/RateLimitBucket.d.ts
| 2.59375
| 3
|
import { Params, RequestFile, ReturnedData } from './Requests';
import { Bot } from '../../bot';
import { HttpMethod } from '../constants';
import { StatusCode, EndpointRoute } from '../endpoints';
export declare const ValidCodes: StatusCode[];
export declare class RateLimitBucket {
/**
* The bot instance
*/
private readonly bot;
/**
* The bot's token
*/
private readonly token;
/**
* The queue associated to this bucket
*/
private readonly queue;
/**
* The route this bucket references
*/
private readonly route;
/**
* The HTTP method this bucket references
*/
private readonly method;
/**
* The number of remaining requests this bucket has until the next reset {@link reset}
*/
remaining: number | undefined;
/**
* The number of total requests that can be made
*/
private limit;
/**
* The Unix timestamp of the next refill for this bucket
*/
private reset;
/**
* The current setTimeout that will run once the next refill is reached
*/
private timeout;
constructor(bot: Bot, token: string, route: EndpointRoute, method: HttpMethod);
/**
* Creates a new API request and sends it if the bucket is capable of doing so
* @param {string} endpoint The request endpoint
* @param {Params} params The request params / body
* @param {RequestFile[]} files The files sent in this request
* @returns {Promise<ReturnedData | undefined>}
*/
send<T = ReturnedData | undefined>(endpoint: string, params: Params, files?: RequestFile[]): Promise<T>;
/**
* Refill this bucket
*/
private refillBucket;
/**
* Validates the response. Throws an error in case it is not valid
* @param {Response} response The response received from sending an API request
* @param {ReturnedData} json The parsed response in JSON
*/
private validateResponse;
/**
* Sets the rate limit information given from the response's headers
* @param {Headers} headers The response's headers
*/
private setLimits;
}
|
0f810ec5803734227cf23522601327df7cf72dc3
|
TypeScript
|
cdaringe/rad
|
/src/util/glob.ts
| 2.6875
| 3
|
import { fs, path } from "../3p/std.ts";
import type { WithLogger } from "../logger.ts";
import { toArray } from "./iterable.ts";
type CreatePathMatcherOpts = { root: string; pattern: string };
export const createPathMatcher = ({
root,
pattern,
}: CreatePathMatcherOpts) => {
const isAbsolute = pattern.startsWith(path.sep);
const matcher = path.globToRegExp(
isAbsolute ? pattern : path.resolve(root, pattern),
{
extended: true,
globstar: true,
},
);
return matcher;
};
export const glob = (opts: CreatePathMatcherOpts & Partial<WithLogger>) => {
const { root: userRoot, logger } = opts;
const root = userRoot === "." ? Deno.cwd() : userRoot;
const matcher = createPathMatcher({ root, pattern: opts.pattern });
logger?.debug(
`creating walk matcher - root: ${root}, matcher: ${String(matcher)}`,
);
return fs.walk(root, {
match: [matcher],
});
};
export const globSimple = (pattern: string) => {
const cwd = Deno.cwd();
const isValid = pattern.includes(cwd);
if (!isValid) {
throw new Error(
`globSimple requires that the pattern be executed from withing the CWD, ${cwd}`,
);
}
return toArray(glob({
pattern: pattern.replace(cwd, "").replace(/^\//, ""),
root: ".",
}));
};
|
0104eddf42b15dcc38247ec971b22b5df044efbd
|
TypeScript
|
riderx/typescript-training
|
/src/functions/various/random.spec.ts
| 3.609375
| 4
|
describe('Collection Random Access', () => {
it('can be used to pick random items', () => {
// write a closure which accepts a collection in the 1st step
// and, with no parameters, returns random item in the 2nd step
// like this: randomItemFrom([1,2,3])()
randomItemOnceFrom// define `randomItemFrom` function here
const randomShoppingItem = randomItemFrom(shoppingData);
for (let i = 0; i < 50; i++) {
expect(shoppingData.includes(randomShoppingItem())).toBe(true);
}
const employees = db.getEmployees();
const randomEmployee = randomItemFrom(employees);
for (let i = 0; i < 50; i++) {
expect(employees.includes(randomEmployee())).toBe(true);
}
})
it('can be used to pick random items, each only once', () => {
// write a similar function as above (with the same signature)
// but this time the closure shall iterate over elements in a random manner
// returning each element only once
// (i.e. above was infinitely returning items, here it returns an item only once)
// DESIGN: decide, how you would like the consumer to be notified that the collection
// has been depleted (is empty and won't return any item from now on)
// define `randomItemOnceFrom` function here
const randomShoppingItem = randomItemOnceFrom(shoppingData);
let count, item = randomShoppingItem();
for (count = 0; item !== undefined; count++, item = randomShoppingItem()){
expect(shoppingData.includes(item)).toBe(true);
}
expect(count).toBe(shoppingData.length);
})
it('can be used to pick random items, each only once, as a generator', () => {
// same as above, but write it as an ES6 generator
// define `randomItemFromGenerator` _generator_ here
const randomShoppingItemIterator = randomItemFromGenerator(shoppingData);
let count = 0;
for (let item of randomShoppingItemIterator){
count++;
expect(shoppingData.includes(item)).toBe(true);
}
expect(count).toBe(shoppingData.length);
})
})
|
41164cfc4ea54a625323ebacd8730275661aa7ff
|
TypeScript
|
whatsaaaa/ts-monorepo
|
/packages/types/src/type-guards.ts
| 3.53125
| 4
|
import { IMessage } from "./types";
/**
* Check whether a given value is an array where
* each member is of a specified type
*
* @param arr - array to check
* @param check - type guard to use when evaluating each item
* @public
*/
export function isTypedArray<T>(
arr: unknown,
check: (x: any) => x is T
): arr is T[] {
if (!Array.isArray(arr)) return false;
return !arr.some((item) => !check(item));
}
/**
* Check whether a given value is an {@link @whatsaaaa/types#IMessage}
* @param arg - value to check
* @beta
*/
export function isMessage(arg: any): arg is IMessage {
return (
typeof arg.teamId === "string" &&
typeof arg.channelId === "string" &&
typeof arg.userId === "string" &&
typeof arg.body === "string"
);
}
|
3a4f91a2d6f9d25d770bc7e53e07cd58e51fb608
|
TypeScript
|
Duban-sg/prueba-test
|
/src/app/pipe/paginator-pipe.pipe.ts
| 2.53125
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'paginatorPipe'
})
export class PaginatorPipePipe implements PipeTransform {
transform(Students: any[], paginationIndex:number,paginationSize:number): any {
let start = (paginationIndex*paginationSize);
let finished = start+paginationSize;
if(paginationIndex==0 || paginationIndex===undefined)return Students.filter((p,index)=>index<paginationSize);
return Students.filter((p,index)=>index>=start && index<finished);
}
}
|
d516ecfe50aa78cd11de5a1b929075e1e58ceaa4
|
TypeScript
|
alexey-dc/jupyter_fourier
|
/src/deezer.ts
| 2.953125
| 3
|
// Work around Deezer CORS limitations via jsonp - see below in #jsonp
let callbackIndex = 0
const assignToWindow = (key: any, value: any) => {
/*
Sadly, typescript requires explicitly declaring globals.
https://stackoverflow.com/questions/12709074/how-do-you-explicitly-set-a-new-property-on-window-in-typescript
declare global { interface Window { variableName: any }}
So for dynamically named globals as in the jsonp implementation (see below in #jsonp),
we have to erase type information.
Another way would be to do (<any>window)[key] = value
*/
const clone: any = window
clone[key] = value
}
const deleteFromWindow = (key: any) => {
const clone: any = window
delete clone[key]
}
class Deezer {
async getTrack(id: string) {
return await this.restGetCall('track', id)
}
async restGetCall(endpoint: string, resource: string) {
const url: string = `https://api.deezer.com/${endpoint}/${resource}`
return await this.jsonp(url)
}
jsonp(url: string) {
// bypass CORS via jsonp w/o jquery
// https://stackoverflow.com/questions/22780430/javascript-xmlhttprequest-using-jsonp
// https://learn.jquery.com/ajax/working-with-jsonp/
// Jsonp is definitely not the greatest way to go about CORS
// https://blog.fullstacktraining.com/why-jsonp-shouldnt-be-used/
// However, it seems like that's the only style deezer supports
// https://github.com/deezer/code-snippets/blob/master/deezer-sdk-js/simple-deezer-api-request.js
// Usually they imply a web use case, and have examples with the DZ module (which isn't
// great for reference, since it only exists in minified form) - in our case,
// dynamically linking it as a script would be the same as doing jsonp regardless.
return new Promise((resolve, reject) => {
const callbackId = (++callbackIndex) % 1000
const callbackName = `jsonp_callback_${callbackId}`
const callback = function(data: any) {
deleteFromWindow(callbackName)
document.body.removeChild(script)
resolve(data)
}
assignToWindow(callbackName, callback)
const script = document.createElement('script')
script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName + "&output=jsonp"
document.body.appendChild(script)
})
}
}
export default Deezer
|
2eda1a5e3a81c0cc0c2c0424396ccb54e936b3f9
|
TypeScript
|
Siteimprove/alfa
|
/packages/alfa-selective/test/selective.spec.ts
| 3.53125
| 4
|
import { test } from "@siteimprove/alfa-test";
import { Refinement } from "@siteimprove/alfa-refinement";
import { Selective } from "../src/selective";
const isFoo: Refinement<string, "foo"> = (string): string is "foo" =>
string === "foo";
const isBar: Refinement<string, "bar"> = (string): string is "bar" =>
string === "bar";
test("#if() conditionally applies a function to a selective value", (t) => {
Selective.of("foo")
.if(isFoo, (value) => {
t.equal(value, "foo");
})
.if(isBar, () => {
t.fail();
});
});
test(`#else() applies a function to a selective value that matched no other
conditions`, (t) => {
Selective.of("bar")
.if(isFoo, () => {
t.fail();
})
.else((value) => {
t.equal(value, "bar");
});
});
test("#get() returns the value of a selective", (t) => {
t.equal(
Selective.of("foo")
.if(isFoo, () => "was foo")
.get(),
"was foo"
);
t.equal(
Selective.of("bar")
.if(isFoo, () => "was foo")
.get(),
"bar"
);
});
test(`#map() applies a function to a matched selective value`, (t) => {
t.equal(
Selective.of("foo")
.if(isFoo, () => "was foo")
.map((string) => string.toUpperCase())
.get(),
"WAS FOO"
);
});
test(`#apply() applies a selective function to a selective value`, (t) => {
t.equal(
Selective.of("foo")
.if(isFoo, () => 2)
.apply(Selective.of("bar").if(isBar, () => (n: number) => n * 2))
.get(),
4
);
});
test(`#flatMap() applies a function to a matched selective value and flattens
the result`, (t) => {
t.equal(
Selective.of("foo")
.if(isFoo, () => "was foo")
.flatMap((wasFoo) =>
Selective.of("bar")
.if(isBar, () => "was bar")
.map((wasBar) => `${wasFoo} and ${wasBar}`)
)
.get(),
"was foo and was bar"
);
});
test(`#flatten() unwraps a nested selective value`, (t) => {
t.equal(
Selective.of("foo")
.else(() => Selective.of("bar"))
.flatten()
.get(),
"bar"
);
});
|
f36f86dfbff0c177b21e7e85c14547a60f3cdb7d
|
TypeScript
|
samritigupta/LeaverageTypeScript
|
/Classes/Prototypical_Inheritance/app.ts
| 3.828125
| 4
|
/*
JavaScript is a bit confusing for developers experienced in class-based languages (like Java or C++),
as it is dynamic and does not provide a class implementation per se (the class keyword is introduced in ES2015, but is syntactical sugar, JavaScript remains prototype-based).
When it comes to inheritance, JavaScript only has one construct: objects.
Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype, and acts as the final link in this prototype chain.
Nearly all objects in JavaScript are instances of Object which sits on the top of a prototype chain.
Inheriting Property: JavaScript objects are dynamic "bags" of properties (referred to as own properties).
JavaScript objects have a link to a prototype object. When trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached.
JavaScript does not have "methods" in the form that class-based languages define them.
In JavaScript, any function can be added to an object in the form of a property. An inherited function acts just as any other property
*/
function TodoService() {
this.todos = [];
}
// add properties in TodoService function's prototype
TodoService.prototype.getAll = function() {
return this.todos;
}
var service = new TodoService();
service.getAll()
|
9239cdae6e8d453ebc16c1981de3f9b48b6ddfe6
|
TypeScript
|
markoradu/test-app
|
/src/app/core/auth/auth.reducer.ts
| 2.90625
| 3
|
import { IAccount } from 'src/app/shared/interfaces/account.model';
import {
AuthActions,
AUTHENTICATE,
UNAUTHENTICATE,
PROTECTED_URL,
} from './auth.actions';
export interface State {
isAuthenticated: boolean;
currentUser?: IAccount | null;
protectedUrl: string | null;
}
const initialState: State = {
isAuthenticated: false,
currentUser: null,
protectedUrl: null,
};
export function authReducer(
state: State = initialState,
action: AuthActions
): State {
switch (action.type) {
case AUTHENTICATE:
return {
...state,
isAuthenticated: true,
currentUser: action.payload as IAccount,
protectedUrl: null,
};
case UNAUTHENTICATE: {
localStorage.removeItem('token');
return {
...state,
isAuthenticated: false,
currentUser: null,
};
}
case PROTECTED_URL: {
return {
...state,
protectedUrl: action?.payload as string,
};
}
default:
return state;
}
}
export const getIsAuthenticated = (state: State) => state.isAuthenticated;
export const getCurrentUser = (state: State) => state.currentUser;
export const getProtectedUrl = (state: State) => state.protectedUrl;
|
537d31d1630772adde43ac761b73d412cf5db17d
|
TypeScript
|
fhereduardo90/nodejs-clean-architecture
|
/src/application/use-cases/users/find-one-user.case.ts
| 2.546875
| 3
|
import { IUserRepository } from '../../contracts/repositories/user.repository'
import { UserDto } from './dtos'
export interface IFindOneUserCase {
execute(id: string): Promise<UserDto>
}
export class FindOneUserCase implements IFindOneUserCase {
constructor(private readonly userRepository: IUserRepository) {}
execute(id: string): Promise<UserDto> {
return this.userRepository.findOne(id)
}
}
|
3f7284e801a8a49ff3f94ab6e254c4c2f89b4eb5
|
TypeScript
|
DefinitelyTyped/DefinitelyTyped
|
/types/memwatch-next/index.d.ts
| 2.65625
| 3
|
// Type definitions for memwatch-next 0.3.0
// Project: https://github.com/marcominetti/node-memwatch
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module "memwatch-next" {
type EventCallback = (data: LeakInformation | StatsInformation | Object) => void;
/**
* Compare the state of your heap between two points in time, telling you what has been allocated, and what has been released.
*/
export class HeapDiff {
/**
* Compute the diff.
*/
end: () => void;
}
/**
* Stats information.
* @interface
*/
export interface StatsInformation {
current_base: number;
estimated_base: number;
heap_compactions: number;
max: number;
min: number;
num_full_gc: number;
num_inc_gc: number;
usage_trend: number;
}
/**
* Leak information.
* @interface
*/
export interface LeakInformation {
/**
* End date.
*/
end: Date,
/**
* Growth.
*/
growth: number;
/**
* Reason leak.
*/
reason: string;
/**
* Start date.
*/
start: Date;
}
/**
* Subscribe to a event.
* @param {string} eventName A event name.
* @param {EventCallback} callback A callback;
*/
export function on(eventName: string, callback: EventCallback): void;
}
|
e2576a43cc10657d09af42a984be350e7c58bbb9
|
TypeScript
|
davidrensh/ng2_mycodebak
|
/ExStore/src/app/ce.ts
| 2.53125
| 3
|
import { Directive, HostListener, Input, ElementRef, OnInit, OnChanges, SimpleChanges, EventEmitter, Output } from '@angular/core';
function selectElementContents(el) {
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
@Directive({
selector: '[ceModel]'
})
export class PlHolderDirective implements OnInit, OnChanges {
@Input('ceDefault') ceDefault: string;
@Input('ceModel') ceModel: string;
@Output('ceChange') ceChange = new EventEmitter();
constructor(private elRef: ElementRef) { }
@HostListener('keyup', ['$event'])
onChange($event: any) {
const value = this.elRef.nativeElement.innerText;
if (value === '') {
this.setPHolderColr(true);
} else {
this.setPHolderColr(false);
}
this.ceModel = value;
this.ceChange.emit(value);
}
@HostListener('click', ['$event'])
@HostListener('focus', ['$event'])
onFocus($event: any) {
const value = this.elRef.nativeElement.innerText;
if (value === this.ceDefault) {
this.elRef.nativeElement.innerText = '';
}
selectElementContents(this.elRef.nativeElement);
}
@HostListener('blur', ['$event'])
onFocusout($event: any) {
let value = this.elRef.nativeElement.innerText;
value = value.replace(/(\r\n|\n|\r)/gm, '');
if (value === '') {
this.elRef.nativeElement.innerText = this.ceDefault;
}
}
/*
* Set the color based on actual or default placeholder color
*/
setPHolderColr(isDefault: boolean) {
if (this.elRef.nativeElement.hasAttribute('placeholder')) {
this.elRef.nativeElement.style.color = (isDefault) ? '#C2C2C2' : '#000';
}
}
ngOnInit() {
if (this.ceModel) {
this.elRef.nativeElement.innerText = this.ceModel;
} else {
this.elRef.nativeElement.innerText = this.ceDefault;
this.setPHolderColr(true);
}
}
/*
* Below will be triggered if source is modified in aside section
*/
ngOnChanges(changes: SimpleChanges) {
const cv = changes['ceModel'].currentValue;
if (this.elRef.nativeElement.innerText !== cv) {
this.elRef.nativeElement.innerText = cv;
if (cv === '') {
this.elRef.nativeElement.innerText = this.ceDefault;
}
}
}
}
|
54eaae7751bbc6feb5b5fb6c9b8fdeb30f36b027
|
TypeScript
|
neoskop/nem
|
/src/provider/view-directory.ts
| 2.703125
| 3
|
import { VIEWS } from '../tokens';
import { Provider } from '@neoskop/injector';
/**
* Provide an additional view directory
* @usage
* ```
*
* nem({
* providers: [
* viewDirectory('./views')
* ]
* }).bootstrap(ExampleModule).listen(8000);
*
*
* @NemModule({
* providers: [
* viewDirectory('./views/example')
* ]
* })
* export class ExampleModule {}
* ```
*/
export function viewDirectory(dir : string) : Provider {
return { provide: VIEWS, useValue: dir, multi: true }
}
|
2000c74aa7170742c82e1d141b78ca7ba6819335
|
TypeScript
|
voil/github-trending-app
|
/platform/src/support/utils.ts
| 2.984375
| 3
|
import { orderBy } from "lodash";
import { RepositoryType } from "../store/repositories.reducer";
import { FiltersType } from "../store/filters.reducer";
/**
* Helper function to create url filters.
* @param FiltersType filters
* @return String
*/
export function hCreateUrlFilters(filters: FiltersType): string {
const urlParams: Array<string> = [];
urlParams.push(filters.since !== "none" ? `since=${filters.since}` : "");
urlParams.push(
filters.language !== "all" ? `language=${filters.language}` : ""
);
return urlParams.filter((item: string) => item !== "").join("&");
}
/**
* Helper function to sort records by stars
* @param Array<RepositoryType> records
* @param FiltersType filters
* @return String
*/
export function hSortResponseByStars(
records: Array<RepositoryType>,
filters: FiltersType
): Array<RepositoryType> {
return filters.sortRating === "none"
? records
: orderBy(records, "stars", filters.sortRating as boolean | "asc" | "desc");
}
|