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
|
|---|---|---|---|---|---|---|
13b7f91bfb6640188cddb2c730423817ca715694
|
TypeScript
|
lMINERl/ts-react
|
/src/redux/actions/DataActions.ts
| 2.828125
| 3
|
import { DataModel } from '../../models/DataModel';
export interface Action {
type?: DataAction;
// tslint:disable-next-line: no-any
payload?: any;
}
// actions const
export enum DataAction {
GET_ALL_DATA = 'GET_ALL_DATA',
GET_DATA_BY_NAME = 'GET_DATA_BY_NAME',
DELETE_DATA_BY_ID = 'DELETE_DATA_BY_ID',
ADD_DATA = 'ADD_DATA',
ERROR = 'ERROR'
}
// Actions
export const getAllData = (response: DataModel[]): Action => {
return {
type: DataAction.GET_ALL_DATA,
payload: response
};
};
export const getDataByName = (name: string): Action => {
return {
type: DataAction.GET_DATA_BY_NAME,
payload: name
};
};
export const deleteDataById = (id: number): Action => {
return {
type: DataAction.DELETE_DATA_BY_ID,
payload: id
};
};
export const addDataToList = (data: DataModel): Action => {
return {
type: DataAction.ADD_DATA,
payload: data
};
};
|
ab6585ef866c9bae238fe925e41c85f9e0660db1
|
TypeScript
|
ucdavis/uccsc-mobile-functions
|
/functions/src/notifications/index.ts
| 2.625
| 3
|
import * as functions from "firebase-functions";
import * as Expo from "expo-server-sdk";
import FirebaseClient from "../services/firebase";
import ExpoClient from "../services/expo";
const db = FirebaseClient.firestore();
export const addNotificationToken = functions.https.onRequest(
async (req, res) => {
try {
// parse out data
const data = req.body;
// save to db
const doc = await db.collection('devices').add({
token: data.token,
user: data.user
});
// return id snapshot
res.json(doc);
} catch (error) {
console.error(error);
res.json(error);
}
}
);
export const sendNotification = functions.https.onRequest(async (req, res) => {
try {
// fetch devices
const devices = await db.collection('devices').get();
// map tokens to messages
const messages = [];
devices.forEach(device => {
const data = device.data();
// Each push token looks like ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]
const token = data.token.value;
// Check that all your push tokens appear to be valid Expo push tokens
if (!Expo.isExpoPushToken(token)) {
console.error(`Push token ${token} is not a valid Expo push token`);
return false;
}
// Construct a message (see https://docs.expo.io/versions/latest/guides/push-notifications.html)
messages.push({
to: token,
sound: "default",
body: "This is a test notification",
data: { withSome: "data" }
});
return false;
});
// The Expo push notification service accepts batches of notifications so
// that you don't need to send 1000 requests to send 1000 notifications. We
// recommend you batch your notifications to reduce the number of requests
// and to compress them (notifications with similar content will get
// compressed).
const chunks = ExpoClient.chunkPushNotifications(messages);
// Send the chunks to the Expo push notification service. There are
// different strategies you could use. A simple one is to send one chunk at a
// time, which nicely spreads the load out over time:
const receipts = [];
for (const chunk of chunks) {
try {
const receipt = await ExpoClient.sendPushNotificationsAsync(chunk);
console.log(receipt);
} catch (error) {
console.error(error);
}
}
res.json(receipts);
} catch (error) {
console.error(error);
res.json(error);
}
});
|
a108178a2ed4aba6209fbe976e383b7926e4dec2
|
TypeScript
|
gradebook/utils
|
/packages/fast-pluralize/src/fast-pluralize.ts
| 3.46875
| 3
|
// Ending pairs to use, in order of precedence
const endings = [
['sis', 'sis'],
['zzes', 'z'],
['ies', 'y'],
['s', ''],
];
const OVERRIDES: Record<string, string> = {
bonuses: 'bonus',
};
export function singularize(phrase: string): string {
phrase = phrase.trim();
const phraseLower = phrase.toLowerCase();
if (Object.hasOwnProperty.call(OVERRIDES, phraseLower)) {
const newPhrase = OVERRIDES[phraseLower];
// Try to preserve case
if (phraseLower.startsWith(newPhrase)) {
return phrase.slice(0, newPhrase.length);
}
return newPhrase;
}
// Loop through each pair and replace
for (const [plural, singular] of endings) {
if (phrase.endsWith(plural)) {
return phrase.slice(0, phrase.length - plural.length) + singular;
}
}
return phrase;
}
|
fe7ea7060076189e0073bb51c69045d95dd8b049
|
TypeScript
|
kemalbekcan/Pokemon
|
/src/reducers/pokeReducers.ts
| 2.640625
| 3
|
import {
GET_POKE_SUCCESS,
GET_POKE_STATS,
POKE_FAILED,
POKE_STATS_FAILED,
POKE_ABILITIES_SUCCESS,
POKE_ABILITIES_FAILED,
ADD_LIKE_SUCCESS,
ADD_UNLIKE_SUCCESS,
LIKE_FAILED,
CATCH_POKEMON_SUCCESS,
DELETE_CATCH_POKEMON,
ALL_DELETE_CATCH_POKEMON
} from '../actions/types';
interface IIinitialState {
loading: boolean;
pokemons: any;
successMessage: string | null;
failedMessage: string | null;
stats: any;
abilities: any;
favourite: any;
pokeCatch: any;
}
const initialState: IIinitialState = {
loading: true,
pokemons: [],
successMessage: null,
failedMessage: null,
stats: [],
abilities: [],
favourite: [],
pokeCatch: [],
}
interface IPokeActions {
type: typeof GET_POKE_SUCCESS;
payload: any;
}
interface IPokeFailed {
type: typeof POKE_FAILED;
payload: string;
}
interface IPokeGetImage {
type: typeof GET_POKE_STATS;
payload: any;
}
interface IPokeErrFailed {
type: typeof POKE_STATS_FAILED;
payload: string;
}
interface IPokeAbilities {
type: typeof POKE_ABILITIES_SUCCESS;
payload: string;
}
interface IPokeAbilitiesFailed {
type: typeof POKE_ABILITIES_FAILED;
payload: string;
}
interface IPokeLikeSuccess {
type: typeof ADD_LIKE_SUCCESS;
payload: string;
}
interface IPokeUnlikeSuccess {
type: typeof ADD_UNLIKE_SUCCESS;
payload: any;
}
interface IPokeFavFailed {
type: typeof LIKE_FAILED;
payload: string;
}
interface IPokeCatchSuccess {
type: typeof CATCH_POKEMON_SUCCESS;
payload: string;
}
interface IPokeDeleteCatchSuccess {
type: typeof DELETE_CATCH_POKEMON;
payload: any;
}
interface IPokeAllDeleteCatchSuccess {
type: typeof ALL_DELETE_CATCH_POKEMON;
payload: any;
}
export type pokeActions = IPokeActions | IPokeFailed | IPokeGetImage | IPokeErrFailed | IPokeAbilities | IPokeAbilitiesFailed | IPokeLikeSuccess | IPokeUnlikeSuccess | IPokeFavFailed | IPokeCatchSuccess | IPokeDeleteCatchSuccess | IPokeAllDeleteCatchSuccess;
const pokeReducers = (state: IIinitialState = initialState, action: pokeActions) => {
switch (action.type) {
case GET_POKE_SUCCESS:
return {
...state,
pokemons: action.payload,
successMessage: "Success",
loading: false,
}
case ADD_LIKE_SUCCESS:
localStorage.setItem("like", JSON.stringify([action.payload, ...state.favourite]))
return {
...state,
favourite: [action.payload, ...state.favourite],
loading: false,
}
case ADD_UNLIKE_SUCCESS:
localStorage.setItem("like", JSON.stringify(state.favourite.filter((fav: any) => fav.id !== action.payload.id)))
return {
...state,
favourite: state.favourite.filter((fav: any) => fav.id !== action.payload.id),
loading: false
}
case LIKE_FAILED:
return {
...state,
failedMessage: 'Something went wrong',
loading: false
}
case GET_POKE_STATS:
return {
...state,
stats: action.payload,
loading: false
}
case POKE_FAILED:
return {
...state,
failedMessage: 'Something went wrong !',
loading: false,
}
case POKE_STATS_FAILED:
return {
...state,
failedMessage: 'Image upload error !',
loading: false
}
case POKE_ABILITIES_SUCCESS:
return {
...state,
abilities: action.payload,
loading: false,
}
case POKE_ABILITIES_FAILED:
return {
...state,
failedMessage: 'Something went wrong !',
loading: false,
}
case CATCH_POKEMON_SUCCESS:
return {
...state,
pokeCatch: [action.payload, ...state.pokeCatch],
loading: false,
}
case DELETE_CATCH_POKEMON:
return {
...state,
pokeCatch: state.pokeCatch.filter((item: any) => item.pokemon !== action.payload.pokemon),
loading: false
}
case ALL_DELETE_CATCH_POKEMON:
return {
...state,
pokeCatch: [],
loading: false
}
default:
return state;
}
}
export default pokeReducers;
|
f7560f53cd384e66b1de8a4897c586035178431e
|
TypeScript
|
vbmeo/AngularP3
|
/tre/src/app/gestone-utenti/gestone-utenti.component.ts
| 2.59375
| 3
|
import { Component, OnInit } from '@angular/core';
import {Utenti} from '../Model/Utenti.model';
@Component({
selector: 'app-gestone-utenti',
templateUrl: './gestone-utenti.component.html',
styleUrls: ['./gestone-utenti.component.css']
})
export class GestoneUtentiComponent implements OnInit {
//listaUtenti : Utenti[];
utenteNuovo: Utenti;
listaUtenti = new Array<Utenti>();
constructor() { }
ngOnInit() {
this.listaUtenti.push(new Utenti('mauro','Bologna'));
this.listaUtenti.push(new Utenti('Paolino','Bentivoglio'));
this.listaUtenti.push(new Utenti('Mister x','Bologna'));
}
addUtente(nome:string,citta:string){
var utente:Utenti = new Utenti(nome,citta);
this.listaUtenti.push(utente);
}
deleteUtente(indice:number){
console.log('indice '+indice);
//cicla array e togli elementao con id passato
//non funziona bene rivedere
for( var i = 0; i < this.listaUtenti.length; i++){
if ( this.listaUtenti[i].id === indice) {
this.listaUtenti.splice(i, 1);
console.log('Cancellato '+this.listaUtenti.splice(i, 1));
}
}
}
}
|
acab9b255ee2221a6c03a752fadc64957a9b67b9
|
TypeScript
|
CN-Shopkeeper/ol_workshop
|
/src/components/page-maps/utils/styled-by-area.ts
| 2.734375
| 3
|
import { getArea } from "ol/sphere";
import colormap from "colormap";
import { Style, Fill, Stroke } from "ol/style";
import RenderFeature from "ol/render/Feature.js";
import Feature from "ol/Feature.js";
import Geometry from "ol/geom/Geometry.js";
import { clamp } from "../utils/clamp-area";
const min = 1e8; // the smallest area
const max = 2e13; // the biggest area
const steps = 50;
// 一个颜色区间,共有50种颜色
const ramp = colormap({
colormap: "blackbody",
nshades: steps
});
// 根据面积找到其颜色下标
function getColor(feature: RenderFeature | Feature<Geometry>) {
const area = getArea(feature.getGeometry() as Geometry);
const f = Math.pow(clamp((area - min) / (max - min), 0, 1), 1 / 2);
const index = Math.round(f * (steps - 1));
return ramp[index];
}
function styleByArea(feature: RenderFeature | Feature<Geometry>): Style {
return new Style({
fill: new Fill({
color: getColor(feature)
}),
stroke: new Stroke({
color: "rgba(255,255,255,0.8)"
})
});
}
export { styleByArea };
|
af1e21ac4c417edac952bbb56f1064e45188d22e
|
TypeScript
|
erinduncan/Vet-Application
|
/Front End/vet-app/src/utilites/index.ts
| 2.5625
| 3
|
import { combineReducers } from "redux";
import { userReducer } from "../reducers/login-reducer";
import { clientReducer } from "../reducers/client-reducer";
import { employeeReducer } from "../reducers/employee-reducer";
import { petReducer } from "../reducers/pet-reducer";
export interface IUserState {
currentUser: any;
loggedIn: boolean;
loginMessage: string;
}
export interface IRegisterState {
newUser: any;
registerMessage: string;
}
export interface IClientState {
clients: any,
client: any,
clientMessage: string,
id: number
}
export interface IPetState {
pets: any,
pet: any,
petMessage: string,
id: number
}
export interface IEmployeeState {
employees: any,
employee: any,
employeeMessage: string,
id: number
}
export interface IState {
userState: IUserState;
clientState: IClientState;
employeeState: IEmployeeState;
petState: IPetState;
}
export const state = combineReducers<IState>({
userState: userReducer,
clientState: clientReducer,
employeeState: employeeReducer,
petState: petReducer
});
|
b26ad1628552c1726f8705579d6a6d6f84e22d5b
|
TypeScript
|
riganti/dotvvm
|
/src/Framework/Framework/Resources/Scripts/utils/dom.ts
| 2.75
| 3
|
export const getElementByDotvvmId = (id: string) => {
return <HTMLElement> document.querySelector(`[data-dotvvm-id='${id}']`);
}
/**
* @deprecated Use addEventListener directly
*/
export function attachEvent(target: any, name: string, callback: (ev: PointerEvent) => any, useCapture: boolean = false) {
target.addEventListener(name, callback, useCapture);
}
export const isElementDisabled = (element: HTMLElement | null | undefined) =>
element &&
["A", "INPUT", "BUTTON"].indexOf(element.tagName) > -1 &&
element.hasAttribute("disabled")
export function setIdFragment(idFragment: string | null | undefined) {
if (idFragment != null) {
// first clear the fragment to scroll onto the element even when the hash is equal to idFragment
location.hash = "";
location.hash = idFragment;
}
}
|
ca8d4064c0a5687cd979383efd435e56cdf36e41
|
TypeScript
|
Loebas/Opdracht-Webapp-4
|
/gameapp/src/app/game.ts
| 2.78125
| 3
|
export class Game {
constructor(
private _id: number,
private _naam: string,
private _minSpelers: number,
private _maxSpelers: number,
private _difficulty: number,
) { }
get id(): number {
return this._id;
}
get naam(): string {
return this._naam;
}
get minSpelers(): number {
return this._minSpelers;
}
get maxSpelers(): number {
return this._maxSpelers;
}
get difficulty(): number {
return this._difficulty;
}
static fromJSON(json: any): Game {
const g = new Game(json.id, json.spelNaam, json.minSpelers, json.maxSpelers, json.difficulty)
return g;
}
}
|
7953dedf929dd8fe3f5911fadb1de23743159af0
|
TypeScript
|
typexs/typexs-ng
|
/archive/packages/base/messages/IMessage.ts
| 2.703125
| 3
|
export enum MessageType {
SUCCESS = 'SUCCESS',
ERROR = 'ERROR',
INFO = 'INFO',
WARNING = 'WARNING'
}
export interface IMessage {
type: MessageType;
topic?: any;
content: any;
}
|
0c0ad8ca052ddf2ffda67362c4c77cd73608b954
|
TypeScript
|
mpicciolli/mean-stack-typescript-project-template
|
/server/utility.ts
| 3.34375
| 3
|
export class Enum {
static getNames(e:any):Array<string> {
var a:Array<string> = [];
for (var val in e) {
if (isNaN(val)) {
a.push(val);
}
}
return a;
}
static getValues(e:any):Array<number> {
var a:Array<number> = [];
for (var val in e) {
if (!isNaN(val)) {
a.push(parseInt(val, 10));
}
}
return a;
}
static getValue(e:any, name:string):number {
return e[name];
}
static getName(e:any, val:number):string {
return e[val];
}
}
|
10fd0e2e1ad14fef61a1dcb1e69c34dda270c994
|
TypeScript
|
singzinc/dotNet
|
/TypeScript/typescript_example2/example1.ts
| 3.03125
| 3
|
function greeter (person: String){
return "Hello, " + person;
}
var user = "test user 1";
console.log("this is test : " + greeter(user));
|
1531663789591d73d3be6ba7cb4048e0ef58f52e
|
TypeScript
|
MaximStrnad/prgGame
|
/src/scripts/core/classes/Grid.ts
| 2.90625
| 3
|
import Cell from "./Cell"
export default class Grid {
cells: Cell[];
cellsVeritacally: number;
cellsHorizonataly: number;
totalCells: number;
p: p5;
size: number;
constructor(p: p5, width: number, height:number, size: number) {
this.p = p;
this.cellsHorizonataly = Math.floor(width/size);
this.cellsVeritacally = Math.floor(height/size);
this.totalCells = this.cellsHorizonataly * this.cellsVeritacally;
this.cells = [];
this.size = size;
for(let i = 0; i <= this.totalCells; i++){
const color: p5.Vector = p.createVector(32,234,232);
let x = i % this.cellsHorizonataly === 0 ? this.size * this.cellsHorizonataly : i % this.cellsHorizonataly * this.size;
let y = i % this.cellsVeritacally === 0 ? this.size * (i / this.cellsVeritacally) : i % this.cellsVeritacally * this.size;
const pos: p5.Vector = p.createVector(x, y);
const size: p5.Vector = p.createVector(40,40);
this.cells.push(new Cell(this.p, pos, size, null, color));
}
}
public render () {
this.p.rect(304,304,32,32);
this.p.fill(32,43,134);
}
}
|
4b55216b91c1244a944fb411f285308197cbf052
|
TypeScript
|
lawvs/Algorithm-Training
|
/leetcode/315.count-of-smaller-numbers-after-self.ts
| 3.25
| 3
|
function countSmaller(nums: number[]): number[] {
const sortedNums: number[] = []
for (let i = nums.length - 1; i >= 0; i--) {
const curNum = nums[i]
sortedNums.push(curNum)
let cnt = 0
// insertion sort
let j = sortedNums.length - 2
for (; j >= 0 && sortedNums[j] >= curNum; j--) {
sortedNums[j + 1] = sortedNums[j]
cnt++
}
sortedNums[j + 1] = curNum
nums[i] = sortedNums.length - cnt - 1
}
// console.log(sortedNums)
return nums
}
|
26a9f676ce8ec3602ba6fdd1e98c724fd7176ca9
|
TypeScript
|
iksaku/djambi
|
/src/api/piece/Militant.ts
| 2.515625
| 3
|
import { Piece } from './Piece'
export class Militant extends Piece {
public get type(): string {
return 'Militant'
}
public get maxMovementDistance(): number {
return 3
}
}
|
f5c1da9a0003558ee1e5160c5fdbeb65e386d051
|
TypeScript
|
ptwu/candidate-decider-google-form
|
/src/firebase-auth.ts
| 3.125
| 3
|
import firebase from 'firebase/app';
import 'firebase/auth';
export type AppUser = {
readonly displayName: string;
readonly email: string;
readonly token: string;
};
/**
* Returns the promise of an app user from the given raw firebase user.
*
* @param firebaseUser a raw firebase user or null.
* @return the promise of an app user or null if there is no such user..
*/
export async function toAppUser(firebaseUser: firebase.User | null): Promise<AppUser | null> {
if (firebaseUser == null) {
return null;
}
const { displayName, email } = firebaseUser;
if (typeof displayName !== 'string' || typeof email !== 'string') {
throw new Error('Bad user!');
}
const token: string = await firebaseUser.getIdToken(true);
return { displayName, email, token };
}
let appUser: AppUser | null = null;
firebase.auth().onAuthStateChanged(async user => {
appUser = await toAppUser(user);
});
export const hasUser = (): boolean => appUser != null;
export function cacheAppUser(user: AppUser): void {
appUser = user;
}
/**
* Returns the global app user.
*
* If the user is not cached yet, it will not try to get one from firebase.
* Instead, it will throw an error.
*/
export function getAppUser(): AppUser {
const user = appUser;
if (user == null) {
throw new Error('App is not initialized.');
}
return user;
}
|
5d9dee32340452b8eb3057248596aae18d5244da
|
TypeScript
|
dlgmltjr0925/marrakech
|
/libs/market_namespace.ts
| 2.578125
| 3
|
import { MarketListObject } from '../api/market/market.dto';
import { Server } from 'socket.io';
import SocketNamespace from './socket_namespace';
export interface ConnectUser {
socketId: string;
userId: number;
roomId: number;
}
export interface DisconnectUser extends ConnectUser {}
export interface MarketMessage {
roomId: number;
status:
| 'JOIN_DEALER'
| 'LEAVE_DEALER'
| 'JOIN_SPECTATOR'
| 'LEAVE_SPECTATOR'
| 'REJECT'
| 'BAN';
market?: MarketListObject;
socketId?: string;
}
export default class MarketNamespace extends SocketNamespace {
constructor(io: Server) {
super(io, /^\/market\/\d+$/);
this.addEventListener('connect', (socket) => {
const token = socket.handshake.auth.token;
const userId = this.getUserIdByToken(token);
if (!userId) return;
const room = socket.nsp.name.replace('/market/', 'market');
socket.join(room);
console.info(`[socket][${room}] joined - ${socket.id}`);
const connectUser: ConnectUser = {
socketId: socket.id,
userId,
roomId: parseInt(room.replace('market', '')),
};
this.ns.emit('connectUser', connectUser);
});
this.addEventListener('connect', (socket) => {
socket.on('updatePlayGame', (msg: string) => {
console.log(msg);
});
});
this.addEventListener('connect', (socket) => {
socket.on('updateMarket', (marketMessage: MarketMessage) => {
const room = `market${marketMessage.roomId}`;
this.ns.to(room).emit('market', marketMessage);
});
});
this.addEventListener('disconnect', (socket) => {
const token = socket.handshake.auth.token;
const userId = this.getUserIdByToken(token);
if (!userId) return;
const room = socket.nsp.name.replace('/market/', 'market');
const disconnectUser: ConnectUser = {
socketId: socket.id,
userId,
roomId: parseInt(room.replace('market', '')),
};
this.ns.emit('disconnectUser', disconnectUser);
});
}
getUserIdByToken(token: string | null) {
if (!token) return null;
token = Buffer.from(token.replace('Basic ', ''), 'base64')
.toString('utf8')
.split(':')[0];
return parseInt(token);
}
}
|
8a68c9084264d19743701b62372c2aa221931e63
|
TypeScript
|
NanimonoDemonai/kani.tech
|
/src/components/hooks/store.ts
| 2.515625
| 3
|
import {
configureStore as configureReduxToolkitStore,
combineReducers,
Store,
} from "@reduxjs/toolkit";
import {
TypedUseSelectorHook,
useDispatch as defaultDispatch,
useSelector as defaultSelector,
useStore,
} from "react-redux";
import { pageMetaReducer } from "./slices/pageMetaSlice";
import { pageOptionReducer } from "./slices/pageOptionSlice";
import { AsyncReducer, RootState, StaticReducer } from "./types";
const staticReducer: StaticReducer = {
pageMeta: pageMetaReducer,
pageOption: pageOptionReducer,
};
const asyncReducer: Partial<AsyncReducer> = {};
export const store = configureReduxToolkitStore({
reducer: staticReducer,
});
export const useInjectReducer = (state: Partial<AsyncReducer>): void => {
const store = useStore();
injectReducer(store, state);
};
export const injectReducer = (
store: Store,
state: Partial<AsyncReducer>
): void => {
Object.entries(state).forEach(([key, value]) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
asyncReducer[key] = value;
});
store.replaceReducer(
combineReducers({
...staticReducer,
...asyncReducer,
})
);
};
export type Dispatch = typeof store.dispatch;
export const useDispatch = (): Dispatch => defaultDispatch<Dispatch>();
export const useSelector: TypedUseSelectorHook<RootState> = defaultSelector;
export type AsyncThunkConfig = {
state: RootState;
dispatch: Dispatch;
};
|
90a50e89fb48e96a2bd6046a0a74cc3cbe61f4b9
|
TypeScript
|
Mati365/ts-c-compiler
|
/packages/compiler-rpn/src/utils/MathExpression.ts
| 2.921875
| 3
|
import * as R from 'ramda';
import { parseNumberToken } from '@compiler/lexer/utils/parseNumberToken';
import { isQuote } from '@compiler/lexer/utils/matchCharacter';
import { reduceTextToBitset } from '@compiler/core/utils';
import { MathOperator } from './MathOperators';
import { MathError, MathErrorCode } from './MathError';
export type MathPostfixTokens = (string | MathOperator)[];
export type MathParserConfig = {
keywordResolver?: (name: string) => number;
};
/**
* Converts array of postifx tokens into single string
*/
export function joinPostifxTokens(tokens: MathPostfixTokens): string {
return R.reduce(
(acc, token) => {
const char = token instanceof MathOperator ? token.char : token;
return acc ? `${acc} ${char}` : char;
},
'',
tokens,
);
}
/**
* Replaces all quotes in string to ascii numbers
*/
export function replaceQuotesWithNumbers(expression: string): string {
for (let i = 0; i < expression.length; ++i) {
const c = expression[i];
if (isQuote(c)) {
let quoteBuffer = '';
for (
let j = i + 1;
j < expression.length && !isQuote(expression[j]);
++j
) {
quoteBuffer += expression[j];
}
expression =
expression.slice(0, i) +
reduceTextToBitset(quoteBuffer) +
expression.slice(i + quoteBuffer.length + 2);
}
}
return expression;
}
/**
* Concerts expression to RPN and calculates it
*/
export class MathExpression {
/**
* Calculates expression
*/
static evaluate(phrase: string, parserConfig?: MathParserConfig): number {
return MathExpression.reducePostfixToNumber(
MathExpression.toRPN(phrase),
parserConfig,
);
}
/**
* Transforms expression to postfix
*/
static toRPN(phrase: string): MathPostfixTokens {
const stack: MathOperator[] = [];
const buffer: MathPostfixTokens = [];
const tokens: string[] = R.reject(
R.isEmpty,
R.split(
MathOperator.MATCH_OPERATOR_REGEX,
replaceQuotesWithNumbers(phrase).replace(/\s/g, ''),
),
);
for (let i = 0; i < tokens.length; ++i) {
let c = tokens[i];
let operator = MathOperator.findOperatorByCharacter(c);
// handle <<
if (!operator) {
operator = MathOperator.findOperatorByCharacter(c + tokens[i + 1]);
if (operator) {
++i;
c += tokens[i + 1];
}
}
if (operator) {
// prefix cases with 0: (-1), +1+2
if (
(operator === MathOperator.PLUS || operator === MathOperator.MINUS) &&
(!i ||
(tokens[i - 1] &&
MathOperator.findOperatorByCharacter(tokens[i - 1]) ===
MathOperator.LEFT_BRACKET))
) {
buffer.push('0');
}
if (operator === MathOperator.RIGHT_BRACKET) {
let foundLeftBracket = false;
while (stack.length) {
const stackOperator = R.last(stack);
if (stackOperator === MathOperator.LEFT_BRACKET) {
stack.pop();
foundLeftBracket = true;
break;
}
buffer.push(stack.pop());
}
if (!foundLeftBracket) {
throw new MathError(MathErrorCode.MISSING_LEFT_BRACKET);
}
} else if (operator === MathOperator.LEFT_BRACKET) {
stack.push(operator);
} else {
// drop when right hand priority stack operator on stack < operator priority
// drop when left hand priority stack operator on stack >= operator priority
while (stack.length) {
const stackOperator = R.last(stack);
// check priority
if (
(!operator.rightHand &&
operator.priority <= stackOperator.priority) ||
(operator.rightHand && operator.priority < stackOperator.priority)
) {
buffer.push(stack.pop());
} else {
break;
}
}
stack.push(operator);
}
} else {
buffer.push(c);
}
}
while (stack.length) {
const token = stack.pop();
if (
token === MathOperator.RIGHT_BRACKET ||
token === MathOperator.LEFT_BRACKET
) {
throw new MathError(MathErrorCode.INCORRECT_BRACKETS);
}
buffer.push(token);
}
return buffer;
}
/**
* Calculates value of postfix expression
*/
static reducePostfixToNumber(
tokens: MathPostfixTokens,
parserConfig?: MathParserConfig,
): number {
const numberStack: number[] = [];
for (let i = 0; i < tokens.length; ++i) {
const token = tokens[i];
if (token instanceof MathOperator) {
// handle ++2 digit, it should be 2
// -2 should be 0-2
const missingArgs = token.argsCount - numberStack.length;
if (missingArgs > 0) {
if (token === MathOperator.PLUS || token === MathOperator.MINUS) {
R.times(() => {
numberStack.unshift(0);
}, missingArgs);
} else {
throw new MathError(MathErrorCode.MISSING_OPERANDS);
}
}
const args = numberStack.splice(
numberStack.length - token.argsCount,
token.argsCount,
);
numberStack.push(token.resolver(args));
} else {
const nestedLabel = token && token[0] === '.';
let number = nestedLabel ? NaN : +token;
if (Number.isNaN(number)) {
// parsing using custom parser is slower than just `+${digit}`
// so it is second parse method
const parsedNumber = !nestedLabel && parseNumberToken(token);
if (parsedNumber) {
[, number] = parsedNumber;
} else {
number = parserConfig?.keywordResolver?.(token);
if (R.isNil(number)) {
throw new MathError(MathErrorCode.UNKNOWN_KEYWORD, { token });
}
}
}
numberStack.push(number);
}
}
return R.last(numberStack) ?? null;
}
}
|
3ec82c66c35f9a0defff644844f1e85e66b53285
|
TypeScript
|
kinjalik/screeps-algorithm
|
/src/utils/RoomUtils.ts
| 2.640625
| 3
|
function getNotEmptyContainers(room: Room) {
const containers = <StructureContainer[]>room.find(FIND_STRUCTURES, {
filter: (struct: Structure): Boolean =>
struct.structureType == STRUCTURE_CONTAINER
});
containers.sort((a, b) => a.store.getUsedCapacity() - b.store.getUsedCapacity());
return containers;
}
export {
getNotEmptyContainers
}
|
4ef51f043b0d40b1fd07e7be3161a66996a4cca2
|
TypeScript
|
ErickTamayo/react-native-breeze
|
/src/plugins/lineHeight.ts
| 2.546875
| 3
|
import { PluginFunction, PluginPattern } from "./types";
export type PluginGroups = {
key: string;
};
export const pattern: PluginPattern = ({ keys }) => {
return new RegExp(`^leading-(?<key>${keys("lineHeight")})$`);
};
export const plugin: PluginFunction<PluginGroups> = ({ groups, theme }) => {
const { key } = groups;
const value = theme(["lineHeight", key]);
return { lineHeight: value };
};
|
c5b83bfe9272eaecc3f221b6214dfc3abb11fed5
|
TypeScript
|
WMs784/host
|
/main.ts
| 2.703125
| 3
|
let index = 0;
let host_num = 1;
let list = [ArrowNames.North,ArrowNames.NorthEast,ArrowNames.East,ArrowNames.SouthEast,
ArrowNames.South,ArrowNames.SouthWest,ArrowNames.West,ArrowNames.NorthWest];
let map = [ArrowNames.North,ArrowNames.South,ArrowNames.East,ArrowNames.West,ArrowNames.NorthEast];
let map2 = [1,2,3,4,5]
radio.setGroup(1);
radio.onReceivedString(function (rs: string) {
let n = parseInt(rs.slice(1));
if(rs[0] =='i'){//目的地番号の場合
for(let i = 0;i < 8;i++){
if(map[n] == list[i]){//正しい矢印がlistのどこに載ってるかを探す
radio.sendString(map2[n].toString()+host_num.toString()+'i'+i.toString());//iを文字列に変換しidをつけて送信
index = i;
}
}
if(rs[0]=='d'){//方角の場合
let cd = (n+45*index)%360;//目的地の方向を計算
let cd1 = cd.toString();//文字列に変換
radio.sendString(map2[n].toString()+ host_num.toString()+'d'+cd1);//idをつけて送信
basic.showNumber(cd);
}
}
})
|
afed491a1f198e66dcb9cdf5e270801a305a7c11
|
TypeScript
|
luohuidong/electron-music
|
/src/renderer/api/playList/requestPlaylistDetail.ts
| 2.84375
| 3
|
import { get } from "../http";
interface Artist {
name: string;
id: number;
}
/** 专辑 */
interface Album {
id: number;
name: string;
}
/** 歌单歌曲数据 */
interface Songs {
name: string;
id: number;
ar: Artist[];
al: Album;
}
/** 歌单歌曲 id */
interface SongIds {
id: number;
}
/** 歌单详情数据 */
interface PlayListDetailData {
tracks: Songs[];
trackIds: SongIds[];
id: number; // 歌单 id
tags: string[]; // 标签
}
/**
* 获取歌单详情
* @param playListId 歌单 id
*/
export async function requestPlaylistDetail(
playListId: number
): Promise<PlayListDetailData> {
try {
const config = {
url: "/playlist/detail",
params: {
id: playListId,
},
};
const { data } = await get(config);
const { code, playlist } = data;
if (code !== 200) {
throw new Error("获取歌单详情失败");
}
return playlist;
} catch (error) {
throw new Error("获取歌单详情失败");
}
}
|
6bc308a750f3b966f982aa0a520105cdce0979a1
|
TypeScript
|
ar-nelson/jaspr
|
/src/PrettyPrint.ts
| 3
| 3
|
import {Jaspr, Deferred, isArray, isObject, isMagic} from './Jaspr'
import {reservedChar} from './Parser'
import chalk from 'chalk'
import {join, sum, identity} from 'lodash'
const defaultIndent = 2
const maxLength = 80
const maxEntries = 36
const maxDepth = 36
function spaces(n: number) {
let s = ''
for (let i = 0; i < n; i++) s += ' '
return s
}
const escapes: {[e: string]: string} = {
'\n': '\\n',
'\r': '\\r',
'\f': '\\f',
'\v': '\\v',
'“': '\\“',
'”': '\\”',
'\\': '\\\\'
}
function quoteString(
str: string,
truncateAt = Infinity,
quoteColor: (s: string) => string = identity,
escapeColor: (s: string) => string = identity,
ellipsisColor: (s: string) => string = identity
): string {
let out = quoteColor('“'), len = 1
for (let c of str) {
if (escapes.hasOwnProperty(c)) {
len++
c = escapeColor(escapes[c])
}
if (len >= truncateAt) {
out += ellipsisColor('…')
break
}
out += c
len++
}
return out + quoteColor('”')
}
abstract class Form {
abstract length(): number
abstract toStringInline(color?: boolean): string
abstract toStringBlock(color?: boolean, offset?: number, hanging?: number): string
toString(color = true, offset = 0, hanging?: number) {
if (this.length() < maxLength - offset) {
return this.toStringInline(color)
} else {
return this.toStringBlock(color, offset, hanging)
}
}
}
class ArrayForm extends Form {
elements: Form[]
constructor(elements: Form[]) {
super()
this.elements = elements
}
length() {
return 2 + sum(this.elements.map(x => x.length())) +
(this.elements.length > 0 ? this.elements.length - 1 : 0)
}
toStringInline(color = true) {
return (color ? chalk.cyan('[') : '[') +
join(this.elements.map(x => x.toStringInline(color)), ' ') +
(color ? chalk.cyan(']') : ']')
}
toStringBlock(color = true, offset = 0, hanging = offset) {
const token: (x: string) => string = color ? chalk.cyan : identity
return token('[') + '\n' +
join(this.elements.map(x =>
spaces(hanging + defaultIndent) +
x.toString(color, hanging + defaultIndent)),
token(',') + '\n') +
'\n' + spaces(hanging) + token(']')
}
}
class ObjectForm extends Form {
entries: {
key: string,
unquoted: boolean,
len: number,
form: Form
}[]
constructor(entries: [string, Form][]) {
super()
this.entries = entries.map(([key, form]) => {
if (key === '' || reservedChar.test(key)) {
return {key, unquoted: false, len: quoteString(key).length, form}
} else {
return {key, unquoted: true, len: key.length, form}
}
})
}
length() {
return 2 + sum(this.entries.map(({len, form}) => len + 1 + form.length())) +
(this.entries.length > 0 ? this.entries.length - 1 : 0)
}
toStringInline(color = true) {
const token: (x: string) => string = color ? chalk.green : identity
return token('{') +
join(this.entries.map(({key, unquoted, form: value}) => {
if (unquoted) {
return key + token(':') + value.toStringInline(color)
} else {
return quoteString(key, undefined,
token, token, color ? chalk.gray : identity) +
token(':') + value.toStringInline(color)
}
}), ' ') + token('}')
}
toStringBlock(color = true, offset = 0, hanging = offset) {
const token: (x: string) => string = color ? chalk.green : identity
return token('{') + '\n' +
join(this.entries.map(({key, len, unquoted, form: value}) => {
const keyStr = spaces(hanging + defaultIndent) +
(unquoted ? key : quoteString(key, undefined,
token, token, color ? chalk.gray : identity)) +
token(':') + ' '
if (hanging + defaultIndent + len + 2 + value.length() < maxLength) {
return keyStr + value.toStringInline(color)
} else {
return keyStr + value.toString(color,
hanging + defaultIndent + len + 2,
hanging + defaultIndent)
}
}), token(',') + '\n') +
'\n' + spaces(hanging) + token('}')
}
}
class StringForm extends Form {
str: string
unquoted: boolean
len: number
constructor(str: string) {
super()
this.str = str
if (str === '' || reservedChar.test(str)) {
this.unquoted = false
this.len = quoteString(str).length
} else {
this.unquoted = true
this.len = str.length
}
}
length() { return this.len }
toStringInline(color = true) {
if (this.unquoted) return this.str
else return quoteString(this.str, undefined,
color ? chalk.gray : identity,
color ? chalk.yellow : identity,
color ? chalk.gray : identity)
}
toStringBlock(color = true, offset = 0, hanging = -1) {
let out = '', len = maxLength - offset
if (hanging >= 0 && offset + this.str.length > maxLength) {
out += '\n' + spaces(hanging)
len = maxLength - hanging
}
if (this.unquoted && this.str.length <= len) return out + this.str
else return out + quoteString(this.str, len,
color ? chalk.gray : identity,
color ? chalk.yellow : identity,
color ? chalk.gray : identity)
}
}
class ConstantForm extends Form {
str: string
color: (s: string) => string
constructor(str: string, color: (s: string) => string = identity) {
super()
this.str = str
this.color = color
}
length() { return this.str.length }
toStringInline(color = true) { return color ? this.color(this.str) : this.str }
toStringBlock(color = true, offset = 0, hanging = -1) {
if (hanging >= 0 && offset + this.str.length > maxLength) {
return '\n' + spaces(hanging) + (color ? this.color(this.str) : this.str)
}
return color ? this.color(this.str) : this.str
}
}
function buildForms(it: Jaspr | Deferred, depth = 0): Form {
if (depth >= maxDepth) {
return new ConstantForm('... (too deep)', chalk.gray)
} else if (it === null) {
return new ConstantForm('null', chalk.magentaBright)
} else if (it === true) {
return new ConstantForm('true', chalk.greenBright)
} else if (it === false) {
return new ConstantForm('false', chalk.redBright)
} else if (typeof it === 'number') {
return new ConstantForm('' + it, chalk.cyanBright)
} else if (typeof it === 'string') {
return new StringForm(it)
} else if (it instanceof Deferred) {
if (it.value !== undefined) {
return buildForms(it.value, depth)
} else {
return new ConstantForm(it.toString(), chalk.yellow)
}
} else if (isArray(it)) {
return new ArrayForm(it.map(e => buildForms(e, depth + 1)))
} else if (isMagic(it)) {
return new ConstantForm('(magic)', chalk.yellowBright)
} else if (isObject(it)) {
return new ObjectForm(
Object.keys(it).map(k => <any>[k, buildForms(it[k], depth + 2)]))
} else {
return new ConstantForm('' + it, chalk.yellow)
}
}
export default function prettyPrint(it: Jaspr, color = true) {
return buildForms(it).toString(color)
}
|
3df317b9707460b4d9f7f05f47b82b0688d157c6
|
TypeScript
|
thomas-crane/sgml
|
/src/syntax/syntax-token.ts
| 3.015625
| 3
|
import { SyntaxKind } from './syntax-kind';
import { SyntaxNode } from './syntax-node';
import { SyntaxTrivia } from './syntax-trivia';
import { TextSpan } from './text-span';
export class SyntaxToken extends SyntaxNode {
readonly children = [];
constructor(
readonly kind: SyntaxKind,
readonly span: TextSpan,
/**
* The value of this token.
*/
readonly value: string,
/**
* Syntax trivia which appears before this token in the source.
*/
readonly leadingTrivia: SyntaxTrivia[] = [],
/**
* Syntax trivia which appears after this token and on the
* same line as this token in the source.
*/
readonly trailingTrivia: SyntaxTrivia[] = [],
) {
super();
}
}
|
5b7d1aa84968f1519b1ed529142b08fe70e872e5
|
TypeScript
|
discordjs/discord.js
|
/packages/builders/src/interactions/slashCommands/options/boolean.ts
| 2.8125
| 3
|
import { ApplicationCommandOptionType, type APIApplicationCommandBooleanOption } from 'discord-api-types/v10';
import { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';
/**
* A slash command boolean option.
*/
export class SlashCommandBooleanOption extends ApplicationCommandOptionBase {
/**
* The type of this option.
*/
public readonly type = ApplicationCommandOptionType.Boolean as const;
/**
* {@inheritDoc ApplicationCommandOptionBase.toJSON}
*/
public toJSON(): APIApplicationCommandBooleanOption {
this.runRequiredValidations();
return { ...this };
}
}
|
3a409adc9d7e8a98dce303d1ec9cc9e54c21e733
|
TypeScript
|
jackfranklin/fetch-engine
|
/src/utils/composeEvery.test.ts
| 2.71875
| 3
|
/// <reference path="../.d.test.ts" />
"use strict";
import test = require("ava");
import composeEvery from "./composeEvery";
test("composeEvery is requireable", (t: TestAssertions) => {
t.ok(composeEvery);
});
test(
"it composes identity functions to produce passed value",
(t: TestAssertions) => {
const id = x => x;
const f = composeEvery([id, id]);
t.is(f(true), true);
t.is(f(false), false);
}
);
test(
"it composes value generating functions",
(t: TestAssertions) => {
const yes = () => true;
const no = () => false;
t.is(composeEvery([yes, yes])(true), true);
t.is(composeEvery([yes, yes])(false), true);
t.is(composeEvery([yes, no ])(true), false);
t.is(composeEvery([yes, no ])(false), false);
t.is(composeEvery([no, yes])(true), false);
t.is(composeEvery([no, yes])(false), false);
t.is(composeEvery([no, no ])(true), false);
t.is(composeEvery([no, no ])(false), false);
}
);
|
0adae82b8121a2ced87b3d0ecc3953a890ee036d
|
TypeScript
|
ariesjia/react-use-form
|
/src/reducer.ts
| 2.78125
| 3
|
import {omit} from "./utils/omit";
import {FiledType} from "./filed-type";
import { getResetValue } from "./index";
export const actions = {
UPDATE_FIELD: 'UPDATE_FIELD',
SET_ERRORS: 'SET_ERRORS',
RESET: 'REST',
}
const getErrors = function(keys, fields, errors) {
const fieldsError = fields || {}
return Array.isArray(keys) ? keys.reduce((prev, key) => {
return fieldsError[key] ? {
...prev,
[key]: fieldsError[key],
} : omit(prev, [key])
}, errors) : fieldsError
}
export const reducer = function(state, action) {
const payload = action.payload
switch (action.type) {
case actions.UPDATE_FIELD:
return {
...state,
fields: {
...state.fields,
[payload.name]: {
...state.fields[payload.name],
...payload.data,
},
}
}
case actions.SET_ERRORS:
return {
...state,
errors: getErrors(
payload.keys,
payload.fieldsError,
state.errors
)
}
case actions.RESET:
const keys = payload.keys && payload.keys.length ? payload.keys : Object.keys(state.fields)
const fieldOptions = payload.fieldOptions || {}
const fields = state.fields
const resetFields = Object.keys(fields).reduce((prev, name) => {
const field = fields[name]
const option = fieldOptions[name] || {}
const shouldReset = keys.includes(name)
return shouldReset ? {
...prev,
[name]: {
...field,
value: getResetValue(option.type || FiledType.text),
}
} : prev
}, {})
return {
...state,
fields: {
...fields,
...resetFields
},
errors: getErrors(
keys,
{},
state.errors
)
}
default:
return state
}
}
|
f483606996d3dbaefff5f86442e49d7cd7ceb8f7
|
TypeScript
|
usb777/typescript
|
/OOP/classes/Animal.ts
| 3.578125
| 4
|
/**
4 Pillars of OOP:
1. Abstraction: abstract classes and Interfaces
2. Inheritence: extends and implements-- class className <name_of_Interface>
3. Encapsulation: restrict access keywords:=== public, private, protected, -default- === and Getter-Setter methods
4. Polymorphism: many-forms - in same class or file -
=== a. Same name function-method with different parameters (Overload)
=== b. Same name function-method from Parent-to-Child with same parameters, but different Logic (Override)
*/
interface Body
{
skelet: string
}
export default class Animal<Body> // class with interface
{
z:string ="hello Animal" ; // default
private tail:boolean;
private voice:string;
private legs : number;
private skelet:string="horde" // from Interface bpdy
protected eye:string ="2 yeys";
constructor ()
{
this.tail = true;
this.voice = "rrrrrr";
this.legs = 4;
}
public getRun(params:boolean)
{
if (params) console.log("Fast running");
else { console.log("slow running");}
}
public setTail(tail:boolean): void
{
this.tail = tail;
}
public getTail():boolean
{
return this.tail;
}
// Setter and Getter for voice fields banch
public setVoice(voice:string): void
{
this.voice = voice;
}
public getVoice():string
{
return this.voice;
}
// Setter and Getter for legs fields banch
public setLegs(legs:number): void
{
this.legs = legs;
}
public getLegs():number
{
return this.legs;
}
public toString() : string
{ return "tail = "+this.tail+" voice = "+this.voice+ " legs = "+ this.legs; }
}
|
95afe612278e26f908b8a3593051f918a63f911c
|
TypeScript
|
zWaR/typescript-patterns
|
/src/abstract-factory/try-abstract-factory.ts
| 2.515625
| 3
|
import { NYPizzaStore } from './creators';
import { PizzaBase } from './domain';
class TryAbstractFactory {
public static run() {
const nyStore: NYPizzaStore = new NYPizzaStore();
const nyPizza: PizzaBase = nyStore.orderPizza('cheese');
console.log(`NY pizza ${nyPizza.getName()} ordered`);
}
}
TryAbstractFactory.run();
|
0eab71d8fd00fb511f55640358211200cf1389fb
|
TypeScript
|
jamiesunderland/rest-my-case
|
/test/HttpStringHelper.spec.ts
| 2.84375
| 3
|
import HttpConfig from '../src/HttpConfig';
import HttpStringHelper from '../src/HttpStringHelper';
import { clientCase } from './mocks';
describe('HttpStringHelper', () => {
let httpStringHelper: HttpStringHelper;
let config;
beforeEach(() => {
config = new HttpConfig();
config.port = 8080;
httpStringHelper = new HttpStringHelper(config);
});
describe('.formatUriPrefix', () => {
test("when the uri is prefixed with a /", () => {
let uri = "/test";
expect(httpStringHelper.formatUriPrefix(uri)).toEqual("test");
});
test("when the uri is suffixed with a /", () => {
let uri = "/test";
expect(httpStringHelper.formatUriPrefix(uri)).toEqual("test");
});
test("when the uri is suffixed with a / and prefixed with a /", () => {
let uri = "/test/";
expect(httpStringHelper.formatUriPrefix(uri)).toEqual("test");
});
test("when the uri is has no prefix or suffic of /", () => {
let uri = "test";
expect(httpStringHelper.formatUriPrefix(uri)).toEqual("test");
});
});
describe('.requestUrl', () => {
let uri = "test";
let uriPrefix = "api";
let queryString = "";
test('when the port does not equal 80 or 443', () => {
config.port = 80;
expect(httpStringHelper.requestUrl(uri, uriPrefix, queryString))
.toEqual("http://localhost/api/test");
});
test('when the port does equal 80', () => {
config.port = 8080;
expect(httpStringHelper.requestUrl(uri, uriPrefix, queryString))
.toEqual("http://localhost:8080/api/test");
});
});
describe('.getQuery', () => {
test('when the query is a string it returns the uri encoded string', () => {
let query = "test=test value"
expect(httpStringHelper.getQuery(query))
.toEqual("?test=test%20value");
});
test('when the query is an object it case converts and stringifies', () => {
let queryString = "?key_one=1&key_two=two&key_three={\"key_four\":[{\"key_five\":5},{\"key_six\":6}]}";
expect(httpStringHelper.getQuery(clientCase))
.toEqual(queryString);
});
});
});
|
18e8183d1b47a0d0c866466d03321cdf508df3a9
|
TypeScript
|
kirontoo/QRMyWifi
|
/src/lib/util.ts
| 2.71875
| 3
|
import QRCode from "qrcode";
export interface WifiCredentials {
network: string;
password: string;
encryption: string;
hidden: boolean;
}
export const sampleWifiCred: WifiCredentials = {
network: "sampleSSID",
password: "samplePassword",
encryption: "WPA",
hidden: false,
};
export const generateQRCode = ({
network,
password,
encryption,
hidden,
}: WifiCredentials) => {
// if entries are not filled, don't generate
if (network === "" && password === "") {
return;
}
const QRCanvas = document.getElementById("canvas");
// remove any existing canvases
let existingCanvas = document.getElementsByTagName("canvas");
if (existingCanvas.length > 0) {
QRCanvas!.removeChild(existingCanvas[0]);
}
// generate QR code
let credentials = `WIFI:S:${network};T:${encryption};P:${password};`;
credentials += hidden ? "H:true" : "H:false";
QRCode.toCanvas(credentials, { scale: 4, width: 300 }, function (err, qr) {
if (err) {
console.error(err);
return;
}
qr.id = "qrcode";
QRCanvas!.appendChild(qr);
});
};
|
102e3c7c761fc079cbdcd36f6859ff47cf866dda
|
TypeScript
|
chenjsh36/media-carrier
|
/src/utils/dataTransform.ts
| 2.875
| 3
|
import { get } from 'lodash';
import Request from './request';
export function arrayBuffer2Blob(arrayBuffer: any, type: string ) {
const blob = new Blob([arrayBuffer], { type });
return blob;
}
export function arrayBuffer2File(arrayBuffer: any, name: string, options?: { type?: string; lastModified?: number } ) {
const file = new File([arrayBuffer], name, options);
return file;
}
export function blob2ArrayBuffer(blob: Blob): Promise<ArrayBuffer> {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onload = function() {
resolve(fileReader.result as ArrayBuffer);
};
fileReader.onerror = function(evt) {
const err1 = get(evt, 'target.error.code', 'NO CODE');
const err2 = get(fileReader, 'error.code', 'NO CODE');
reject(`fileReader read blob error: ${err1} or ${err2}`);
};
fileReader.readAsArrayBuffer(blob);
});
}
export function blob2ObjectURL(blob: Blob): string {
const url = URL.createObjectURL(blob);
return url;
}
export function blob2AudioEelemnt(blob: Blob): HTMLAudioElement {
const url = blob2ObjectURL(blob);
return new Audio(url);
}
export function blob2VideoElement(blob: Blob): HTMLVideoElement {
const url = blob2ObjectURL(blob);
const video = document.createElement('video');
video.src = url;
return video;
}
type FileType = 'arrayBuffer' | 'file';
export async function reqMedia(url: string, fileType: FileType = 'arrayBuffer' ): Promise<ArrayBuffer | Blob> {
if (!url) return Promise.resolve(null);
return Request({
url,
method: 'get',
responseType: 'arraybuffer',
}).then((res: any) => {
const arrayBuffer = res.data;
const contentType = res.headers['content-type'] || '';
let ret = arrayBuffer;
if (fileType === 'file') {
ret = arrayBuffer2File(ret, 'result', { type: contentType });
}
return ret;
})
};
export default {
arrayBuffer2Blob,
arrayBuffer2File,
blob2ArrayBuffer,
blob2AudioEelemnt,
blob2VideoElement,
blob2ObjectURL,
reqMedia,
}
|
34023c3232b7402d8dd79079554efb68aeddbcbe
|
TypeScript
|
jonathapriebe/NodeJS-Interview
|
/src/models/customer.ts
| 2.828125
| 3
|
import mongoose, { Document, Model } from 'mongoose';
export interface Customer {
_id?: string;
name: string;
gender: string;
dt_birthday: Date;
age: number;
city_id: string;
}
const schema = new mongoose.Schema(
{
name: { type: String, required: true },
gender: { type: String, required: true },
dt_birthday: { type: Date, required: true },
age: { type: Number, required: true },
city_id: { type: String, required: true },
},
{
toJSON: {
transform: (_, ret): void => {
ret.id = ret._id;
delete ret._id;
delete ret.__v;
},
},
}
);
interface CustomerModel extends Omit<Customer, '_id'>, Document {}
export const Customer: Model<CustomerModel> = mongoose.model(
'Customer',
schema
);
|
590822eca99ff891cecbc7a66aaca8104516cf89
|
TypeScript
|
mcortesi/battle4tronia-server
|
/src/db/message-store.ts
| 2.671875
| 3
|
import db from '../connections/postgres';
import { MessageType, MessagePlayerOpened, MessageDealerAccepted, MessagePlayerClosed } from '../model/message';
import { Address } from '../tron/types';
export function fromPG(record: any): MessagePlayerOpened | MessageDealerAccepted | MessagePlayerClosed {
const obj = record.text;
switch(obj.type) {
case MessageType.PLAYER_OPENED: {
return {
playerAddress: record.player_address,
channelId: record.channel_id,
round: record.round,
publicKey: record.public_key,
type: record.type,
bet: obj.bet,
player: obj.player,
playerRandomHash1: obj.playerRandomHash1,
playerRandomHash2: obj.playerRandomHash2,
playerRandomHash3: obj.playerRandomHash3,
signature: obj.signature
};
}
case MessageType.DELEAR_ACCEPTED: {
return {
messagePlayerOpened: obj.messagePlayerOpened,
type: obj.type,
dealerRandomNumber1: obj.dealerRandomNumber1,
dealerRandomNumber2: obj.dealerRandomNumber2,
dealerRandomNumber3: obj.dealerRandomNumber3,
signature: obj.signature
};
}
case MessageType.PLAYER_CLOSED: {
return {
messageDealerAccepted: obj.messageDealerAccepted,
type: obj.type,
playerUpdated: obj.playerUpdated,
playerRandomNumber1: obj.playerRandomNumber1,
playerRandomNumber2: obj.playerRandomNumber2,
playerRandomNumber3: obj.playerRandomNumber3,
signature: obj.signature
};
}
default: throw("Unrecognized message type");
}
}
export async function getLastMessage(playerAddress: Address): Promise<null | MessagePlayerOpened | MessageDealerAccepted | MessagePlayerClosed> {
const res = await db.oneOrNone<any>(
'select * from messages where player_address = $(playerAddress) order by created_date desc limit 1',
{
playerAddress,
}
);
return res != null ? fromPG(res) : null;
}
export function insertMessage(
playerAddress: Address,
channelId: number,
round: number,
type: string,
text: string
): Promise<boolean> {
return db.result(
`INSERT INTO messages(
player_address,
channel_id,
round,
type,
text
) VALUES (
$(playerAddress),
$(channelId),
$(round),
$(type),
$(text)
) ON CONFLICT DO NOTHING`,
{
playerAddress,
channelId,
round,
type,
text
},
cb => cb.rowCount === 1
);
}
|
9d3e81d2c3302648f1ee2f107eb35d35ef6f3b49
|
TypeScript
|
BraTTik/redux-paint
|
/src/modules/strokes/actions.ts
| 2.5625
| 3
|
import { Stroke } from '../../types';
export const END_STROKE = 'END_STROKE';
export type StrokesAction = {
type: typeof END_STROKE;
payload: { stroke : Stroke, historyLimit : number}
}
export const endStroke = (stroke : Stroke, historyLimit: number) => {
return {type: END_STROKE, payload: {stroke, historyLimit} };
}
|
bb5a5d1bc71022bb159ad5f5d0eb0b39d7aeb599
|
TypeScript
|
abondoa/gq-cli
|
/cliParser.ts
| 2.65625
| 3
|
import * as commandLineArgs from 'command-line-args';
import * as commandLineUsage from 'command-line-usage';
import { Context } from 'gq';
const contextJson = (input: string) => new Context(JSON.parse(input));
const optionDefinitions = [
{
name: 'application-environment',
alias: 'a',
type: String,
// tslint:disable-next-line: max-line-length
description:
'Name of the application environment to load. There must be a file named <application-environment>.json in the <root> folder'
},
{
name: 'context',
alias: 'c',
type: contextJson,
multiple: true,
defaultOption: true,
// tslint:disable-next-line: max-line-length
description:
'The context(s), in form of JSON object(s), which you want to test the feature flags of'
},
{
name: 'root',
alias: 'r',
type: String,
description: 'The root folder to search for the application environment'
},
{
name: 'help',
alias: 'h',
type: Boolean,
description: 'Shows this help text'
}
];
export function parseCliArgs() {
return commandLineArgs(optionDefinitions);
}
export function showCliHelp() {
console.log(
commandLineUsage([
{
header: 'GQ',
content: 'A feature flag thingy'
},
{
header: 'Synopsis',
content: [
// tslint:disable-next-line: max-line-length
`$ gq --root {underline folder} --application-environment {underline string} [--context] {underline contextjson} ...`,
'$ gq --help'
]
},
{
header: 'Options',
optionList: optionDefinitions
}
])
);
}
|
abd018ca65151a313f9bf75e52412b4fafcbfd98
|
TypeScript
|
FinOCE/Konzu
|
/models/Client.ts
| 2.53125
| 3
|
import {Client as DJSClient, ClientOptions, Collection} from 'discord.js'
import glob from 'glob-promise'
import {parse} from 'path'
import Event from './Event'
import Command from './Command'
import Button from './Button'
import Menu from './Menu'
/**
* Create a client.
*/
export default class Client extends DJSClient {
public config: Record<string, any>
public commands: Collection<string, Command>
public buttons: Collection<string, Button>
public menus: Collection<string, Menu>
constructor(options: ClientOptions) {
super(options)
this.config = require('../config.json')
this.commands = new Collection<string, Command>()
this.buttons = new Collection<string, Button>()
this.menus = new Collection<string, Menu>()
{(async () => {
await this.initialiseEvents()
await this.login(process.env.token)
await this.initialiseCommands()
await this.initialiseButtons()
await this.initialiseMenus()
console.log('Konzu is ready for lunch!')
})()}
}
/**
* Initialise bot events.
*/
private async initialiseEvents(): Promise<void> {
let files = await glob('./events/*+(js|.ts)')
for (let file of files) {
let {name} = parse(file)
let event: Event = new (require(`.${file}`).default)(this)
this.on(name, (...args) => event.run(...args))
}
}
/**
* Initialise slash commands.
*/
private async initialiseCommands(): Promise<void> {
let files = await glob('./commands/*+(js|.ts)')
for (let file of files) {
let {name} = parse(file)
let command: Command = new (require(`.${file}`).default)(this)
this.commands.set(name, command)
let {description, options, permissions, defaultPermission} = command
this.guilds.cache.get(this.config.snowflakes.server)?.commands.create({
name,
description,
options,
defaultPermission
}).then(cmd => {
if (permissions) cmd.permissions.set({permissions})
})
}
}
/**
* Initialise button interactions.
*/
private async initialiseButtons(): Promise<void> {
let files = await glob('./buttons/*+(js|.ts)')
for (let file of files) {
let {name} = parse(file)
let button: Button = new (require(`.${file}`).default)(this)
this.buttons.set(name, button)
}
}
/**
* Initialise select menu interactions.
*/
private async initialiseMenus(): Promise<void> {
let files = await glob('./menus/*+(js|.ts)')
for (let file of files) {
let {name} = parse(file)
let button: Menu = new (require(`.${file}`).default)(this)
this.menus.set(name, button)
}
}
}
|
24c33714667157bccd9847047300a439d0f1c4fc
|
TypeScript
|
includeVitor/react-boilerplate
|
/src/store/modules/notify/index.ts
| 3.1875
| 3
|
import { Action } from "redux"
import { toast } from "react-toastify";
import { IToastState, Toast } from "./types"
//Actions
const INFO = 'toast/info'
const SUCCESS = 'toast/success'
const WARNING = 'toast/warning'
const ERROR = 'toast/error'
interface InfoAction extends Action<typeof INFO> {
payload: Toast
}
interface SuccessAction extends Action<typeof SUCCESS> {
payload: Toast
}
interface WarningAction extends Action<typeof WARNING> {
payload: Toast
}
interface ErrorAction extends Action<typeof ERROR> {
payload: Toast
}
export const info = (toast: Toast): InfoAction => ({
type: INFO,
payload: toast
})
export const success = (toast: Toast): SuccessAction => ({
type: SUCCESS,
payload: toast
})
export const warning = (toast : Toast): WarningAction => ({
type:WARNING,
payload: toast
})
export const error = (toast: Toast): ErrorAction => ({
type: ERROR,
payload: toast
})
const initialState: IToastState = {
time : 5000,
message: ""
}
//Reduces
const toastReducer = (
state: IToastState = initialState,
action: InfoAction | SuccessAction | WarningAction | ErrorAction
) => {
switch(action.type){
case INFO:
toast.info(action.payload.message, {autoClose: action.payload.time})
return{
...state
}
case SUCCESS:
toast.success(action.payload.message, {autoClose: action.payload.time})
return{
...state
}
case WARNING:
toast.warning(action.payload.message, {autoClose: action.payload.time})
return{
...state
}
case ERROR:
toast.error(action.payload.message, {autoClose: action.payload.time})
return{
...state
}
default:
return state
}
}
export default toastReducer
|
46b9c960d8609b568f20bf9510cc92bb84ca052b
|
TypeScript
|
caio2009/asahi-api
|
/src/modules/ceasa/infra/typeorm/repositories/StockRepository.ts
| 2.5625
| 3
|
import IStockItemDTO from "@modules/ceasa/dtos/IStockItemDTO";
import IStockRepository from "@modules/ceasa/repositories/IStockRepository";
import { getConnection } from "typeorm";
import stockQueries from '@modules/ceasa/queries/stockQueries';
import IStockItemDetailsDTO from "@modules/ceasa/dtos/IStockItemDetailsDTO";
import AppError from "@shared/errors/AppError";
class StockRepository implements IStockRepository {
async findAll(): Promise<IStockItemDTO[]> {
const rows = await getConnection().manager.query(stockQueries.findAll);
return rows.map((row: any) => {
const stockItem = { ...row.stock_item };
stockItem.cultivation.image = stockItem.cultivation.image
? `${process.env.API_URL}/uploads/${stockItem.cultivation.image}`
: null;
return stockItem as IStockItemDTO;
})
}
async findStockItemDetails(data: {
cultivationId: string,
classificationId: string,
unitId: string
}): Promise<IStockItemDetailsDTO> {
const { cultivationId, classificationId, unitId } = data;
const rows = await getConnection().manager.query(stockQueries.findStockItemDetails, [cultivationId, classificationId, unitId]);
const row = rows[0];
if (!row) throw new AppError(404, 'Stock Item not found!');
const stockItemDetails: IStockItemDetailsDTO = {
inStock: row.in_stock,
cultivation: row.cultivation,
classification: row.classification,
unit: row.unit,
origins: row.origins
};
return stockItemDetails
}
}
export default StockRepository;
|
adef18417bce9dcf8527f633ad0547fece4600b5
|
TypeScript
|
zf-wuxia/client-dev
|
/assets/Framework/Core/iFunction.ts
| 2.8125
| 3
|
import { PoolManager } from "../Manager/PoolManager";
import { iStore } from "./iStore";
export class iFunction extends iStore {
public once: boolean = true;
public target: any;
public func: Function;
public params: any[];
public get size(): number {
return this.func ? this.func.length : 0;
}
public execute(args?: any[]): any {
if (this.func != null) {
let pp = [];
if (this.params != null && this.params.length > 0) {
pp = pp.concat(this.params);
}
if (args != null && args.length > 0) {
pp = pp.concat(args);
}
return this.func.apply(this.target, pp);
}
if (this.once) {
this.dispose();
}
}
public dispose(): void {
this.once = true;
this.func = null;
this.target = null;
this.params = null;
super.dispose();
}
public static Compare(a: iFunction, b: iFunction): boolean {
return a.target == b.target && a.func == b.func;
}
public static FindIndexOf(func: iFunction, funcs: iFunction[]): number {
for (let i = 0; i < funcs.length; i++) {
if (this.Compare(func, funcs[i])) {
return i;
}
}
return -1;
}
public static Get(func: Function, target?: any, args?: any[], once: boolean = true): iFunction {
let result: iFunction = PoolManager.getInstance().get(iFunction);
result.func = func;
result.once = once;
result.target = target;
result.params = args;
return result;
}
}
|
f4c52452081e504ba8e7dcce6df58aa91a4fcd81
|
TypeScript
|
BeteTech/typesciptPratice
|
/59/validator/LettersOnlyValidator.ts
| 2.84375
| 3
|
import { StringValidator } from './validation'
const LetterReg = /^[A-Za-z]+$/
export class LetterOnlyValidator implements StringValidator {
isAcceptable(s: string): boolean {
return LetterReg.test(s)
}
}
|
16162613c2bbbf004d9d2c0c2348c4928af54334
|
TypeScript
|
dipiash/cloudpayments
|
/src/Client/ClientRequestAbstract.ts
| 2.59375
| 3
|
import fetch from "node-fetch";
import {ClientResponse} from "./ClientResponse";
import {BaseResponse} from "../Api";
import {join} from "path";
import {ClientAbstract} from "./ClientAbstract";
export class ClientRequestAbstract extends ClientAbstract {
/**
* HTTP Client
*
* @returns {(url: (string | Request), init?: RequestInit) => Promise<Response>}
*/
public get client(): typeof fetch {
return fetch;
}
/**
*
*/
public async ping(): Promise<ClientResponse<BaseResponse>> {
const response = await this.client(this.getEndpoint().concat(join("/test")), {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({}),
});
return new ClientResponse(await response.json());
}
/**
* Create request to an API endpoint.
*
* @param {string} url
* @param {Object} data
* @param {string} requestId
* @returns {Promise<ClientResponse<BaseResponse>>}
*/
protected async call<R extends BaseResponse>(url: string, data?: object, requestId?: string): Promise<R> {
const authorization = Buffer.from(`${this.options.publicId}:${this.options.privateKey}`, "utf-8").toString(
"base64",
);
const headers: { [key: string]: string } = {
"Content-Type": "application/json",
Authorization: `Basic ${authorization}`,
};
if (requestId) {
headers["X-Request-ID"] = requestId;
}
const response = await this.client(this.getEndpoint().concat(join("/", url)), {
headers,
method: "POST",
body: data ? JSON.stringify(data) : undefined,
});
return await response.json();
}
}
|
1b707df312e14cb5881a58b6113de892d37c1254
|
TypeScript
|
Luncert/csdn
|
/dashboards/src/com/ItemList.ts
| 2.546875
| 3
|
import { r, rc } from '../util/react-helper';
import { Component, Props } from './Component';
const styles = <any> require('./ItemList.css');
interface CusProps extends Props {
width: String;
height: String;
fixScroll: number;
onScrollOverTop: () => void;
onScrollOverBottom: () => void;
}
/**
* * props
* * width
* * height
* * fixScroll: 设置是否锁定滚动条,即自动显示最新数据,0:false,1:锁定顶部,2:锁定底部
* * onScrollOverTop: 设定滚动到顶部时的动作
* * onScrollOverBottom: 设定滚动到底部时的动作
*/
export default class ItemList extends Component {
props: CusProps;
root: HTMLElement;
componentWillUnmount() {
this.root.onscroll = null;
}
componentDidMount() {
const { onScrollOverTop, onScrollOverBottom } = this.props;
let beforeScrollTop = this.root.scrollTop;
this.root.onscroll = () => {
let direction = this.root.scrollTop - beforeScrollTop;
if (direction > 0 && Math.ceil(this.root.scrollTop) >=
this.root.scrollHeight - this.root.clientHeight) {
onScrollOverBottom && onScrollOverBottom();
}
else if (direction < 0 && Math.ceil(this.root.scrollTop) == 0) {
onScrollOverTop && onScrollOverTop();
}
beforeScrollTop = this.root.scrollTop;
};
this.fixScroll();
}
componentDidUpdate() {
this.fixScroll();
}
private fixScroll() {
switch(this.props.fixScroll) {
case 1:
this.root.scrollTop = 0;
break;
case 2:
this.root.scrollTop = this.root.scrollHeight;
break;
}
}
render() {
const { width, height, style={}, children } = this.props;
style['width'] = width;
style['height'] = height;
return r('div', {
className: styles.root,
style: style,
ref: (node: HTMLElement) => this.root = node
},
children
);
}
}
|
ad97a98e7b58ca2592b7c9664dadc2628880baee
|
TypeScript
|
snyk/snyk-nuget-plugin
|
/test/helpers/temp-fixture.ts
| 3
| 3
|
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
export interface File {
name: string;
contents: string;
}
// Running tests in parallel can cause race conditions for fixtures at-rest, if two tests are `dotnet publish`'ing
// to the same fixture folder. So we supply a generator for populating fixtures in temporary folders to keep the test
// stateless while ensuring parallelization.
export function setup(files: File[]): string {
const tempDir = fs.mkdtempSync(
path.join(os.tmpdir(), 'dotnet-test-publish-'),
);
let tempFilePath: string;
files.forEach((file) => {
tempFilePath = path.join(tempDir, file.name);
fs.writeFileSync(tempFilePath, file.contents);
});
return tempDir;
}
export function tearDown(dir: string) {
if (!dir) {
// No tempDir to tear down. Assuming the test failed somewhere.
// Jest won't throw an error anyway if the operation fails.
return;
}
try {
fs.rmSync(dir, { recursive: true });
} catch (error: unknown) {
// Ignore it, test was tearing down anyway, and it seems Windows boxes especially don't like this.
}
}
|
76db39a6e19c5cd1b541494c7d1d778dbdc0c7d3
|
TypeScript
|
abhishekkhandait/ui-study
|
/src/data/BaseNode.ts
| 3.109375
| 3
|
import deepcopy from '../util/deepcopy'
export default class BaseNode {
public name!: string | null
public _parent!: BaseNode | null
constructor(
name: string | null = null,
attrs: {[s: string]: any} | null = null
) {
this.name = name
Object.defineProperties(this, {
_parent: {
writable: true,
enumerable: false
}
})
if (attrs) {
this.setAttrs(attrs)
}
}
public clone(): BaseNode {
return new BaseNode(this.name, deepcopy(this.getAttrs()))
}
public getAttrs(): {[s: string]: any} {
const attrs = Object.assign({}, this)
delete attrs.name
return attrs
}
public setAttrs(attrs: {[s: string]: any}) {
const self = this as {[s: string]: any}
for (const key of Object.keys(attrs)) {
self[key] = attrs[key]
}
}
public serialize() {
const attrs = this.getAttrs()
const obj: any[] = ['']
const className = this.constructor.name
if (className !== 'IndexedNode') {
obj[0] += `:${className}`
}
if (this.name) {
obj[0] += `#${this.name}`
}
if (Object.keys(attrs).length > 0) {
obj.push(attrs)
}
return obj
}
public toJSON() {
return this.serialize()
}
}
|
55a29a25f11d404b16f4e2e1525eed3ef6470dcb
|
TypeScript
|
brenopgarcia/nestjs-smart-ranking
|
/src/jogadores/jogadores.service.ts
| 2.609375
| 3
|
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { CreatePlayerDto } from './dtos/criar-jogador.dto';
import { Jogador } from './interfaces/jogador.interface';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
@Injectable()
export class JogadoresService {
// private jogadores: Jogador[] = [];
constructor(
@InjectModel('Jogador') private readonly jogadorModule: Model<Jogador>,
) {}
private readonly logger = new Logger(JogadoresService.name);
async createAndUpdatePlayer(createPlayerDto: CreatePlayerDto): Promise<void> {
const { email } = createPlayerDto;
// const playerExists = this.jogadores.find(
// (jogador) => jogador.email === email,
// );
try {
const playerExists = await this.jogadorModule.findOne({ email }).exec();
if (playerExists) {
this.update(createPlayerDto);
} else {
this.create(createPlayerDto);
}
} catch (error) {
return error;
}
}
async findPlayers(): Promise<Jogador[]> {
// return this.jogadores;
return await this.jogadorModule.find().exec();
}
async findByEmail(email: string): Promise<Jogador> {
// const playerExists = this.jogadores.find(
// (jogador) => jogador.email === email,
// );
const playerExists = await this.jogadorModule.findOne({ email }).exec();
if (!playerExists) {
throw new NotFoundException(`No player found with e-mail ${email}`);
}
return playerExists;
}
async delete(email: string): Promise<any> {
// const playerExists = this.jogadores.find(
// (jogador) => jogador.email === email,
// );
// if (!playerExists) {
// throw new NotFoundException(`No player found with e-mail ${email}`);
// }
// this.jogadores = this.jogadores.filter(
// (jogador) => jogador.email !== playerExists.email,
// );
return await this.jogadorModule.remove({ email }).exec();
}
private async create(createPlayerDto: CreatePlayerDto): Promise<Jogador> {
const player = new this.jogadorModule(createPlayerDto);
await player.save();
return player;
// const { nome, telefoneCelular, email } = createPlayerDto;
// const jogador: Jogador = {
// _id: uuid.v4(),
// nome,
// telefoneCelular,
// email,
// ranking: null,
// posicaoRanking: null,
// urlFotoJogador: null,
// };
// this.logger.log(`createPlayerDto: ${JSON.stringify(jogador)}`);
// this.jogadores.push(jogador);
}
private async update(createPlayerDto: CreatePlayerDto): Promise<Jogador> {
// const { nome } = createPlayerDto;
// playerExists.nome = nome;
return await this.jogadorModule
.findOneAndUpdate(
{ email: createPlayerDto.email },
{ $set: createPlayerDto },
)
.exec();
}
}
|
ec97a19f73de3b836620540614cb70a31b6d12ac
|
TypeScript
|
gionji/ese459_solarlamp
|
/main.ts
| 2.609375
| 3
|
function big_light_on () {
basic.showLeds(`
# # # # #
# # # # #
# # # # #
# # # # #
. . . . .
`)
}
function small_light_on () {
basic.showLeds(`
. . . . .
. . . . .
. . . . .
. . . . .
# # # # #
`)
}
function EVT_night () {
if (status == NIGHT) {
status = NIGHT
} else if (status == DAY) {
small_light_off()
status = NIGHT
} else {
}
}
function timer_reset () {
timer_value = 0
is_timer_on = 0
}
function EVT_timer_end () {
if (status == NIGHT) {
big_light_off()
small_light_on()
timer_stop()
status = NIGHT
} else if (status == DAY) {
error()
status = DAY
} else {
}
}
function small_light_off () {
basic.showLeds(`
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
`)
}
function update_timer () {
if (is_timer_on == 1) {
is_timer_on += 1
if (timer_value == timer_max) {
// turn the TIMER off and reset it's value to 0
is_timer_on = 0
timer_value = 0
EVT_timer_end()
}
}
}
function check_presence () {
if (Environment.PIR(DigitalPin.P0)) {
EVT_presence_detected()
}
}
function big_light_off () {
basic.showLeds(`
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
`)
}
function timer_stop () {
is_timer_on = timer_max
}
function EVT_daylight () {
if (status == NIGHT) {
big_light_off()
small_light_off()
timer_stop()
status = DAY
} else if (status == DAY) {
status = DAY
} else {
}
}
function error () {
}
function check_external_light () {
if (Environment.ReadLightIntensity(AnalogPin.P1) > 100) {
EVT_daylight()
} else {
EVT_night()
}
}
function EVT_presence_detected () {
if (status == NIGHT) {
small_light_off()
big_light_on()
timer_reset()
status = NIGHT
} else if (status == DAY) {
status = DAY
} else {
}
}
let status = 0
let is_timer_on = 0
let timer_value = 0
let DAY = 0
let NIGHT = 0
let timer_max = 0
timer_max = 10
NIGHT = 0
DAY = 1
timer_value = 0
is_timer_on = 0
// 0 = NIGHT
// 1 = DAY
status = DAY
basic.forever(function () {
update_timer()
check_external_light()
check_presence()
basic.pause(1000)
})
|
3a23ca219d88da856bb3a7f63b82dd6c4a3af31e
|
TypeScript
|
mungojam/use-persisted-state
|
/src/createGlobalState.ts
| 3.3125
| 3
|
type Callback<T> = (arg0: T) => void;
const globalState: Record<string, {callbacks: Callback<any>[], value: any}> = {};
export interface GlobalStateRegistration<T> {
deregister: () => void,
emit: (value: T) => void
}
const createGlobalState = <T>(key: string, thisCallback: Callback<T>, initialValue?: T): GlobalStateRegistration<T> => {
if (!globalState[key]) {
globalState[key] = { callbacks: [], value: initialValue };
}
globalState[key].callbacks.push(thisCallback);
return {
deregister() {
const arr = globalState[key].callbacks;
const index = arr.indexOf(thisCallback);
if (index > -1) {
arr.splice(index, 1);
}
},
emit(value: T) {
if (globalState[key].value !== value) {
globalState[key].value = value;
globalState[key].callbacks.forEach((callback) => {
if (thisCallback !== callback) {
callback(value);
}
});
}
},
};
};
export default createGlobalState;
|
9403f8e6d4e6cf722fd4ec9de03434ed17b7d96c
|
TypeScript
|
sumight/ts-react-mobx-demo
|
/src/rules.ts
| 3.03125
| 3
|
export function required (value:any, label:string):Promise<{message:string, passed:boolean}> {
if (
value === ''
|| value === null
|| value === undefined
|| JSON.stringify(value) === '[]'
) {
return Promise.resolve({
message: '请填写'+label,
passed: false
})
}
return Promise.resolve({
message: '',
passed: true
})
}
export const doubled = (value:any, label:string):Promise<{message:string, passed:boolean}> => {
return new Promise(resolve => {
setTimeout(() => {
if(value === 'pp') {
resolve({
message: '名字重复',
passed: false
})
}
else {
resolve({
message: '',
passed: true
})
}
}, 1000)
})
}
export function isNumber (value:any, label:string) {
if (isNaN(value)) {
return Promise.resolve({
message: '请输入数字',
passed: false
})
} else {
return Promise.resolve({
message: '',
passed: true
})
}
}
|
d0f66c3fb6e8fab0d748a7201ffe2aa0eb137f50
|
TypeScript
|
vveronika/memory-app
|
/src/helpers/helperFunctions.ts
| 3.25
| 3
|
import { Score } from "types";
export const shuffleArray = (arr: any[]) => {
return arr.sort(() => Math.random() - 0.5);
};
export function compareScores(a: Score, b: Score) {
const scoreA = a.score;
const scoreB = b.score;
let comparison = 0;
if (scoreA > scoreB) {
comparison = 1;
} else if (scoreA < scoreB) {
comparison = -1;
}
return comparison;
}
|
7c86558506cfe65b0434dc172f0592fd4b73e7a2
|
TypeScript
|
ravendb/ravendb-nodejs-client
|
/src/Documents/Queries/Suggestions/SuggestionBuilder.ts
| 2.890625
| 3
|
import { ISuggestionBuilder } from "./ISuggestionBuilder";
import { ISuggestionOperations } from "./ISuggestionOperations";
import { SuggestionWithTerm } from "./SuggestionWithTerm";
import { SuggestionWithTerms } from "./SuggestionWithTerms";
import { throwError } from "../../../Exceptions";
import { TypeUtil } from "../../../Utility/TypeUtil";
import { SuggestionOptions } from "./SuggestionOptions";
import { SuggestionBase } from "./SuggestionBase";
import { Field } from "../../../Types";
export class SuggestionBuilder<T> implements ISuggestionBuilder<T>, ISuggestionOperations<T> {
private _term: SuggestionWithTerm;
private _terms: SuggestionWithTerms;
public withDisplayName(displayName: string): ISuggestionOperations<T> {
this.suggestion.displayField = displayName;
return this;
}
public byField(fieldName: Field<T>, term: string): ISuggestionOperations<T>;
public byField(fieldName: Field<T>, terms: string[]): ISuggestionOperations<T>;
public byField(fieldName: Field<T>, termOrTerms: string | string[]): ISuggestionOperations<T> {
if (!fieldName) {
throwError("InvalidArgumentException", "fieldName cannot be null");
}
if (!termOrTerms) {
throwError("InvalidArgumentException", "term cannot be null");
}
if (TypeUtil.isArray(termOrTerms)) {
if (!termOrTerms.length) {
throwError("InvalidArgumentException", "Terms cannot be an empty collection");
}
this._terms = new SuggestionWithTerms(fieldName);
this._terms.terms = termOrTerms;
} else {
this._term = new SuggestionWithTerm(fieldName);
this._term.term = termOrTerms;
}
return this;
}
public withOptions(options: SuggestionOptions): ISuggestionOperations<T> {
this.suggestion.options = options;
return this;
}
public get suggestion(): SuggestionBase {
if (this._term) {
return this._term;
}
return this._terms;
}
}
|
622c6f10262c9a1d94e1af7c0eb019c08842b9d9
|
TypeScript
|
jacobdavis1/fileshare-website
|
/src/app/_models/File.ts
| 2.640625
| 3
|
export interface File {
fileSize: number;
name: string;
isDirectory: boolean;
}
|
09666125a1baec2e986eb03f736a5668db8a8246
|
TypeScript
|
green-fox-academy/gergocsima
|
/week-02/day-01/05-factorial.ts
| 3.9375
| 4
|
// - Create a function called `factorio`
// that returns it's input's factorial
export { }
let inputNr: number = 5;
function factorio(inputNr: number) {
let summ: number = 1;
for (let i: number = inputNr; i >0; i--) {
summ = summ * i;
/*console.log(summ);*/
}
return summ;
}
console.log('The factorial of ',inputNr,'is :',factorio(inputNr));
|
2658e5c4ce2adfa2527598f2311458f578e029a1
|
TypeScript
|
Equiem/gql-compat
|
/src/reportBreakingChanges.ts
| 2.71875
| 3
|
import chalk from "chalk";
import { BreakingChange } from "graphql";
import shell from "shelljs";
import { formatBreakingChanges } from "./formatBreakingChanges";
/**
* Formats the given breaking changes in ignore format.
*/
export const reportBreakingChanges = (breaking: BreakingChange[], ignored: BreakingChange[]): void => {
const ignoredLen = ignored.length;
const breakingLen = breaking.length;
if (ignoredLen > 0) {
shell.echo(`👀 ${chalk.bold.yellow(`${ignoredLen} breaking change${ignoredLen > 1 ? "s were" : " was"} ignored`)}`);
shell.echo(formatBreakingChanges(ignored));
}
if (breakingLen === 0) {
shell.echo(`👍 ${chalk.bold.green("The new schema does not introduce any unintentional breaking changes")}`);
}
else {
shell.echo(`💥 ${chalk.bold.red(`${breakingLen} breaking change${breakingLen > 1 ? "s were" : " was"} detected`)}`);
shell.echo(formatBreakingChanges(breaking));
}
};
|
de30bf0f07dc99f6b144e40b325aef8237d33ee1
|
TypeScript
|
marciomarquessouza/repeat-please-pron-server
|
/src/auth/user.repository.ts
| 2.765625
| 3
|
import { EntityRepository, Repository } from 'typeorm';
import { User } from './user.entity';
import * as bcrypt from 'bcrypt';
import { SignUpCredentialsDto } from './dto/signup-credentials.dto';
import {
ConflictException,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
import { SignInCredentialsDto } from './dto/signin-credentials.dto';
import { UserGroup } from './user-group.enum';
@EntityRepository(User)
export class UserRepository extends Repository<User> {
private async hashPassword(password: string, salt: string): Promise<string> {
return bcrypt.hash(password, salt);
}
async signUp(
signUpCredentialsDto: SignUpCredentialsDto,
): Promise<{ id: number }> {
const { email, password, name } = signUpCredentialsDto;
const user = this.create();
user.email = email;
user.group = UserGroup.FREE_USER;
user.name = name || '';
user.salt = await bcrypt.genSalt();
user.password = await this.hashPassword(password, user.salt);
try {
await user.save();
return { id: user.id };
} catch (error) {
if (error.code === '23505') {
throw new ConflictException(
`Email "(${user.email})" is already in use`,
);
}
throw new InternalServerErrorException();
}
}
async validatePassword(
signInCredentialsDto: SignInCredentialsDto,
): Promise<string> {
const { email, password } = signInCredentialsDto;
const user = await this.findOne({ where: { email } });
if (!user) {
throw new NotFoundException(`User "${email}" not found`);
}
try {
const isPaswordValid = await user.validatePassword(password);
return isPaswordValid ? user.email : null;
} catch (error) {
throw new Error(error.message);
}
}
}
|
6688a0abf72f4e0b3aa20556a4a2cbbdd10badc8
|
TypeScript
|
lucasavila00/INF221PRE2A
|
/__OWN_tests__/black.ts
| 3.0625
| 3
|
import { processByFilename } from "../src/lib";
describe("Teste de caixa preta", () => {
test("Funciona dentro do tempo esperado (<1s)", async () => {
const MULT = 100;
const MULT_ARR = Array.from(Array(100).keys());
expect.assertions(MULT);
return Promise.all(
MULT_ARR.map(_ => {
const init = new Date().getTime();
return processByFilename("./samples/1.txt").then(
i => {
const end = new Date().getTime();
expect(end - init).toBeLessThan(1000);
}
);
})
);
});
test("Funciona corretamente com o exemplo 1", () => {
expect.assertions(1);
return expect(
processByFilename("./samples/1.txt")
).resolves.toBe(2);
});
test("Funciona corretamente com o exemplo 2", () => {
expect.assertions(1);
return expect(
processByFilename("./samples/2.txt")
).resolves.toBe(2);
});
test("Retorna uma mensagem de erro humana se o arquivo não existir ou se o dado passado for inválido", () => {
const examples = [
"./samples/nao_existe.txt",
0,
"",
null,
undefined,
1,
1.0,
void 0
];
expect.assertions(examples.length);
return Promise.all(
examples.map(e => {
return expect(
processByFilename(e as any)
).rejects.toBe(
"Não foi possível abrir o arquivo de dados. \
Confira se o arquvio existe e se caminho informado está correto."
);
})
);
});
});
|
124ed9b3ac8a57943da4619f64e0f46e40a95656
|
TypeScript
|
jay-gothi/wallet-web-components
|
/src/infra/http/fetch-http-client.ts
| 2.546875
| 3
|
import { HttpAuthHeader } from "../../data/protocols/http/http-auth-header";
import { HttpGetClient } from "../../data/protocols/http/http-get-client";
import { HttpPostClient } from "../../data/protocols/http/http-post-client";
import { HttpPutClient } from "../../data/protocols/http/http-put-client";
import { decrypt } from "../../utils/utils";
export class FetchHttpClient implements HttpPostClient, HttpGetClient, HttpPutClient, HttpAuthHeader{
private static instance: FetchHttpClient;
private static token: string;
/**
* Singleton class private contructor
*/
private constructor() { }
/**
* Singleton class create instance
*/
public static getInstance(): FetchHttpClient {
if (!FetchHttpClient.instance) {
FetchHttpClient.instance = new FetchHttpClient();
FetchHttpClient.token = FetchHttpClient.instance.getAuthToken();
}
return FetchHttpClient.instance;
}
/**
* Get auth token
*
* @returns string | null
*/
getAuthToken(): string {
if (process.env.REACT_APP_WALLET_COMPONENT_AUTH_TOKEN) {
let ltoken = localStorage.getItem(process.env.REACT_APP_WALLET_COMPONENT_AUTH_TOKEN);
if (ltoken && ltoken != "") {
return decrypt(JSON.parse(ltoken));
}
return "";
}
return "";
};
/**
* Post request
* @param params
* @returns
*/
async post(params: HttpPostClient.Params): Promise<any> {
let response: Response;
try {
response = await fetch(params.url, {
method: 'POST',
body: JSON.stringify(params.body),
headers: this.prepareAuthHeader(params.headers)
});
} catch (error) {
response = error.json();
}
return response.json();
}
async put(params: HttpPutClient.Params): Promise<any> {
let response: Response;
try {
response = await fetch(params.url, {
method: 'PUT',
body: JSON.stringify(params.body),
headers: this.prepareAuthHeader(params.headers)
});
} catch (error) {
response = error.json();
}
return response.json();
}
async get(params: HttpGetClient.Params): Promise<any> {
let response: Response;
try {
response = await fetch(params.url + new URLSearchParams(params.query), {
headers: this.prepareAuthHeader(params.headers)
});
} catch (error) {
response = error.json();
}
return response.json();
}
/**
* Prepare auth headers
*
* @param headers
* @returns
*/
prepareAuthHeader(headers?: {[key: string]: string | null}) {
if (!FetchHttpClient.token)
FetchHttpClient.token = FetchHttpClient.instance.getAuthToken();
if (headers && FetchHttpClient.token && FetchHttpClient.token != "")
headers[process.env.REACT_APP_WALLET_COMPONENT_AUTH_HEADER] = FetchHttpClient.token
return headers;
}
}
|
85b998f13c124bbc21cdc34a3e543e654e81768d
|
TypeScript
|
ocreeva/incremental
|
/src/types/model/IGameContext.ts
| 2.8125
| 3
|
import type { AsyncModelMessage, ModelMessage } from '@/constants/worker';
import type { EntityId } from '@/types';
import type { MessageService } from '@/types/worker';
import type IGameSynchronization from './IGameSynchronization';
import type IOperationModel from './IOperationModel';
import type IRoutineModel from './IRoutineModel';
import type ISubroutineModel from './ISubroutineModel';
/**
* Represents contextual information about the state of the game.
*/
declare interface IGameContext {
/** A worker message service. */
readonly messageService: MessageService<ModelMessage, AsyncModelMessage>;
/** The operation models. */
readonly operations: Map<EntityId, IOperationModel>;
/** The routine model. */
readonly routine: IRoutineModel;
/** The subroutine models. */
readonly subroutines: Map<EntityId, ISubroutineModel>;
/** The game's synchronization. */
readonly synchronization: IGameSynchronization;
/**
* Get an operation by ID.
*
* @param operationId - The operation's ID.
*
* @returns The operation.
*
* @remarks
* Wrapper around 'operations.get' with an assert for existence.
*/
getOperation(operationId: EntityId): IOperationModel;
/**
* Get a subroutine by ID.
*
* @param subroutineId - The subroutine's ID.
*
* @returns The subroutine.
*
* @remarks
* Wrapper around 'subroutines.get' with an assert for existence.
*/
getSubroutine(subroutineId: EntityId): ISubroutineModel;
}
export default IGameContext;
|
87b912209cec78ad6f2a59f3f6b0ee868d17d68a
|
TypeScript
|
Mitsu325/Angular_Course_Loiane
|
/data-binding/src/app/data-binding/data-binding.component.ts
| 2.609375
| 3
|
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-data-binding',
templateUrl: './data-binding.component.html',
styleUrls: ['./data-binding.component.css']
})
export class DataBindingComponent implements OnInit {
url: string = 'https://github.com/Mitsu325';
like: boolean = true;
urlImage: string = 'https://cdn.pixabay.com/photo/2015/09/09/16/05/forest-931706_960_720.jpg';
urlImage2: string = 'https://cdn.pixabay.com/photo/2015/11/04/20/59/milky-way-1023340_960_720.jpg';
valorAtual: string = '';
valorSalvo: string = '';
isMouseOver: boolean = false;
nome: string = 'abc';
person: any = {
name: 'Paty',
age: 23
}
nomeDoCurso: string = 'Angular';
getValue() {
return 1;
}
getLike() {
return true;
}
clickButton() {
alert('Botão clicado!');
}
onKeyUp(event: KeyboardEvent) {
this.valorAtual = (<HTMLInputElement>event.target).value;
}
saveValue(value) {
this.valorSalvo = value;
}
onMouseOverOut() {
this.isMouseOver = !this.isMouseOver;
}
constructor() { }
ngOnInit(): void {
}
}
|
0142b3a81e7a91680bb59daec0cfda244a4d4864
|
TypeScript
|
Jackzinho/desafio-driva
|
/src/errors/MissingParamError.ts
| 2.53125
| 3
|
import { CustomError } from './CustomError'
export class MissingParamError extends CustomError {
constructor(paramName: string) {
super(`Missing param: ${paramName}`, 400)
this.name = 'MissingParamError'
}
}
|
011d44a686af2967fbb3517a483321dd46421916
|
TypeScript
|
yeonjuan/md-replacer
|
/lib/stack.ts
| 3.453125
| 3
|
class Stack<Type> {
private elements: Type[] = [];
public static create<Type>() {
return new Stack<Type>();
}
public isEmpty() {
return this.elements.length <= 0;
}
public push(elem: Type) {
this.elements.push(elem);
}
public pop() {
return this.elements.pop();
}
public top() {
return this.elements[this.elements.length - 1];
}
}
export = Stack.create;
|
4cdcc7b91c81b27fd909db6a18907b38956e2d6c
|
TypeScript
|
Nikita9950/companyTS
|
/Client.ts
| 3.203125
| 3
|
class Client implements IClient {
protected readonly _name: string
protected _employee: IEmployee
public constructor(name: string, employee: IEmployee) {
this._name = name
this._employee = employee
}
public get name(): string {
return this._name
}
public get employee(): IEmployee {
return this._employee
}
public set employee(employee) {
this._employee = employee
}
}
|
0610f41358a69fd0735487768376473399b7b462
|
TypeScript
|
jfresco/exchange-client
|
/src/model/trade.ts
| 2.875
| 3
|
import { sortBy, slice, last, dropRight, reverse } from 'lodash'
export default function Trade (orderBooks: OrderBooksByExchanges) {
// Unified order book: contains all asks and bits of all the exchanges
const unified: Unified = {
asks: [],
bids: []
}
Object.keys(orderBooks).forEach(exchange => {
const withExchange = (order: Order): OrderWithExchange => ({
...order,
exchange
})
unified.asks = [
...unified.asks,
...orderBooks[exchange].asks.orders.map(withExchange)
]
unified.bids = [
...unified.bids,
...orderBooks[exchange].bids.orders.map(withExchange)
]
})
// Get the orders needed to sell the base currency in order to get the `expectedVolume`
function sellByAmount(expectedVolume: number) {
// Get the index of the last item that, with its predecessors, accumulates at least the `expectedVolume`
function getIndexForAccum(bids: OrderWithExchange[]) {
let i = 0
for (let accum = 0; accum < expectedVolume && i < bids.length; i++) {
const ask = bids[i]
accum += ask.price * ask.volume
}
return i
}
// Get working orders
function getBestBids() {
const bids = reverse(sortBy(unified.bids, 'price'))
const index = getIndexForAccum(bids)
return slice(bids, 0, index)
}
function applyCorrectionToLastBid(orders: OrderWithExchange[]) {
// A correction should be made to the last item of the array, assuming that the sum is passed from
// `expectedVolume`.
// XXX: I'm assuming here that the amount to sell to a bidder can be altered
const untouched = dropRight(orders)
const lastBid = last(orders)
if (!lastBid) {
return []
}
// Get the sum of all the orders except the last
const sum = untouched.reduce((accum, x) => accum + x.volume * x.price, 0)
// Calculate the volume needed for the last order to complete the expected volume
lastBid.volume = (expectedVolume - sum) / lastBid.price
// Return all orders
return [...untouched, lastBid]
}
return applyCorrectionToLastBid(getBestBids())
}
return {
sellByAmount
}
}
|
672f7b615a662de0171ae86e9a8b4a2bc47e716c
|
TypeScript
|
JohannesLichtenberger/componentish
|
/src/generic/helpers/renderChildren.ts
| 2.75
| 3
|
import { GenericNode } from "../interfaces/ComponentNodes/GenericNode";
import { TransformerCollection } from "../interfaces/transformer/TransformerCollection";
/**
* render all child nodes of a given node
* @param {GenericNode} node
* @param {TransformerCollection} transformers
* @param {number} [level=0]
* @returns
*/
const renderChildren = (node: GenericNode, transformers: TransformerCollection, level: number = 0) => {
let markup = "";
if (node.children) {
for (const childNode of node.children) {
const nodeTransformer =
childNode.controlType in transformers ? childNode.controlType : "GenericElementNode";
markup += transformers[nodeTransformer].generateMarkup(childNode, level);
}
}
return markup;
};
export { renderChildren };
|
cc12dd3a0474021a92d4280c2b122c27dbb21094
|
TypeScript
|
sezna/sky
|
/tests/runtime/if-expr.test.ts
| 3.03125
| 3
|
import { runtime } from '../../src/runtime';
import { makeSyntaxTree } from '../../src/lexer/parser';
import { tokenize } from '../../src/lexer/tokenizer';
import { isLeft } from 'fp-ts/lib/Either';
describe('if expr tests', () => {
it('should correctly assign its result to a variable #1', () => {
let program = `fn main(): number {
number x = if 200 < 5 then 5 else 2;
return x;
}`;
let steps = makeSyntaxTree(tokenize(program));
if (isLeft(steps)) {
console.log('Error: ', steps.left.reason);
// for typescript's type inference
expect(true).toBe(false);
return;
}
let result = runtime(steps.right);
if (isLeft(result)) {
console.log('Error: ', result.left.reason);
// for typescript's type inference
expect(true).toBe(false);
return;
}
expect(result.right.mainReturn.returnValue).toBe(2);
});
it('should correctly assign its result to a variable #2', () => {
let program = `fn main(): number {
number x = if 200 > 5 then 6 else 3;
return x;
}`;
let steps = makeSyntaxTree(tokenize(program));
if (isLeft(steps)) {
console.log('Error: ', steps.left.reason);
// for typescript's type inference
expect(true).toBe(false);
return;
}
let result = runtime(steps.right);
if (isLeft(result)) {
console.log('Error: ', result.left.reason);
// for typescript's type inference
expect(true).toBe(false);
return;
}
expect(result.right.mainReturn.returnValue).toBe(6);
});
/* TODO
it('should handle if expressions using brackets alike to those without', () => {
let program = `fn main(): song {
number x = if 200 > 5 then { 6 } else { 3 };
}`;
let steps = makeSyntaxTree(tokenize(program));
if (isLeft(steps)) {
console.log('Error: ', steps.left.reason);
// for typescript's type inference
expect(true).toBe(false);
return;
}
let result = runtime(steps.right);
if (isLeft(result)) {
console.log('Error: ', result.left.reason);
// for typescript's type inference
expect(true).toBe(false);
return;
}
expect(result.right.variableEnvironment['x'].value).toBe(6);
});
it('should handle if expressions with multiple statements and an implicit return', () => {
let program = `fn main(): number {
number x = if 200 > 5 then {
number y = 20;
number z = 10;
5
} else {
pitch c = c#2;
number z = 10;
3
};
return 0;
}`;
let steps = makeSyntaxTree(tokenize(program));
if (isLeft(steps)) {
console.log('Error: ', steps.left.reason);
// for typescript's type inference
expect(true).toBe(false);
return;
}
let result = runtime(steps.right);
if (isLeft(result)) {
console.log('Error: ', result.left.reason);
// for typescript's type inference
expect(true).toBe(false);
return;
}
expect(result.right.variableEnvironment['x'].value).toBe(6);
});
*/
});
|
cd1a4c396b3ccce5fcfcc4b0e32f2de532d500ce
|
TypeScript
|
dzfranco/games-api
|
/server/api/interfaces/persistence/ipublisher.persistence.ts
| 2.578125
| 3
|
import { Publisher } from '../../../common/models/publisher/publisher';
import { IGame } from '../../../common/models/game/igame';
export interface IPublisherPersistence {
/**
* @description Gets a game publisher
* @param {IGame} game
* @return
* @memberof PublisherPersistence
*/
getGamePublisher(game: IGame): Promise<Publisher>;
}
|
f264b6e142be2ed1625a25462c633a01824bf29c
|
TypeScript
|
vietnh-vmo/nest-demo
|
/src/guards/auth.guard.ts
| 2.578125
| 3
|
import {
HttpStatus,
Injectable,
CanActivate,
ExecutionContext,
} from '@nestjs/common';
import { decodeToken } from '../utils/jwt';
import { UserError } from '../helpers/error.helpers';
import { UserService } from '../modules/users/user.service';
import { StatusCodes } from '../modules/_base/base.interface';
@Injectable()
export class RequireAuth implements CanActivate {
constructor(private readonly userService: UserService) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const req = context.switchToHttp().getRequest();
if (!req.headers || !req.headers.authorization)
throw new UserError(StatusCodes.UNAUTHORIZED, HttpStatus.UNAUTHORIZED);
const decoded = await this.validateToken(req.headers.authorization);
if (!decoded || !decoded.userId)
throw new UserError(StatusCodes.INVALID_TOKEN, HttpStatus.FORBIDDEN);
const user = await this.userService.getOne({ id: decoded.userId });
if (user) req.user = user;
else throw new UserError(StatusCodes.INVALID_TOKEN, HttpStatus.FORBIDDEN);
return true;
}
async validateToken(auth: string) {
try {
if (auth.split(' ')[0] !== 'Bearer')
throw new UserError(StatusCodes.INVALID_TOKEN, HttpStatus.FORBIDDEN);
const token = auth.split(' ')[1];
const decoded = await decodeToken(token);
return decoded;
} catch (error) {
console.log('validateToken error: ', error);
throw new UserError(StatusCodes.INVALID_TOKEN, HttpStatus.FORBIDDEN);
}
}
}
|
285644eaf1f270cd48227794bf841bf6536e4723
|
TypeScript
|
jsblanco/EmployeeTXTdb-Server
|
/ts/helpers/digestDbEntries.ts
| 2.96875
| 3
|
module.exports = (employeeData: string): employeeArr => {
const userDb: employeeArr = [];
employeeData
.toString()
.split("\n")
.forEach((user: string, index: number) => {
if (user.length>0){
let userData = user.split(",");
userDb[index] = {
id: parseInt(userData[0]),
firstName: userData[1],
lastName: userData[2],
address: userData[3],
phoneNumber: userData[4],
email: userData[5],
birthDate: userData[6],}
};
});
return userDb;
}
|
cab4404b33e78de4fdf4fcaa8f4cba98df1a692d
|
TypeScript
|
fengluandll/self-talk
|
/src/infrastructure/firebase/firebase-authentication-controller.ts
| 2.75
| 3
|
import "firebase/auth";
import firebase from "firebase/app";
import { IAuthenticationController } from "../../application/authentication-controller";
import { sleep } from "../../domain/utilities";
export class FirebaseAuthenticationController
implements IAuthenticationController {
private signedIn: boolean | null = null;
constructor() {
firebase.auth().onAuthStateChanged((user: firebase.User | null): void => {
this.signedIn = !!user;
});
}
public async signIn(): Promise<void> {
await firebase
.auth()
.signInWithRedirect(new firebase.auth.GoogleAuthProvider());
}
public async signOut(): Promise<boolean> {
await firebase.auth().signOut();
return this.isSignedIn();
}
public async isSignedIn(): Promise<boolean> {
while (this.signedIn === null) {
await sleep(10);
}
return this.signedIn;
}
}
|
754111d7b53a606522fe223f03ac53fd27192f7f
|
TypeScript
|
chouchouxsl/ts-study-notes
|
/01-ts基本类型/基础类型.ts
| 4.28125
| 4
|
// Boolean
namespace Bool {
let falg: boolean = true
falg = false
}
// Number
namespace Num {
let num: number = 1
num = 12
}
// String
namespace Str {
let str: string = '哈哈哈哈'
str = '嘻嘻嘻嘻'
}
// Array
namespace Arr {
let strArr: string[] = ['哈哈哈哈', '嘻嘻嘻嘻']
let numArr: Array<number> = [123, 34, 54]
}
// Any
namespace Any {
let notSure: any = 666
notSure = 'semlinker'
notSure = false
notSure = [123213, 'ssad']
// 可以赋值给有类型的 有风险
let num: number = notSure
}
// Unknown
namespace Unknown {
let notSure: unknown = 666
notSure = 'semlinker'
notSure = false
notSure = [123213, 'ssad']
// 不可以赋值给有类型的
// let num:number = notSure
}
// Tuple
namespace Tuple {
// 数组一般由同种类型的值组成,但有时我们需要在单个变量中存储不同类型的值,这时候我们就可以使用元组
// 数量不可以多不可以少 类型必须一一对应
let arr: [number, string, boolean] = [1, '2', false]
type Tuple = [number, string]
let tuArr: Tuple = [1, 'xx']
}
// Void
namespace Void {
// 表示函数没有返回值
function fn(x: number): void {}
// 需要注意的是,声明一个 void 类型的变量没有什么作用,因为在严格模式下,它的值只能为 undefined:
let unusable: void = undefined
}
// Null 和 Undefined
namespace Bare {
// TypeScript 里,undefined 和 null 两者有各自的类型分别为 undefined 和 null。
let u: undefined = undefined
let n: null = null
}
// Object
namespace Object {
// object 类型是:TypeScript 2.2 引入的新类型,它用于表示非原始类型。
// 对象的描述 一般都是通过接口进行描述
}
// Never
namespace Never {
//never 类型表示的是那些永不存在的值的类型。 例如,never 类型是那些总是会抛出异常或根本就不会有返回值的函数表达式或箭头函数表达式的返回值类型。
// 返回never的函数必须存在无法达到的终点
function error(message: string): never {
throw new Error(message)
}
function infiniteLoop(): never {
while (true) {}
}
}
|
73f2732558fc913ea53833fc721bc462fe655b2b
|
TypeScript
|
corbane/g3
|
/worker/math/funcs.ts
| 3.234375
| 3
|
declare function lerp <T extends LVec2|LVec3|LVec4> (vin: T, vout: T, v: number): T
declare function remap (vin: LVec2, vout: LVec2, v: number) : number
//declare function length (a: LVec2|LVec3|LVec4)
declare function len (a: LVec2|LVec3|LVec4) : number
declare function distance <T extends LVec2|LVec3|LVec4> (a: T, b: T): number
declare function dot <T extends LVec2|LVec3|LVec4> (a: T, b: T): number
declare function cross (a: LVec3, b: LVec3) : LVec3
declare function normalize <T extends LVec2|LVec3|LVec4> (a: T) : T
;{
type Tin = LVec2|LVec3|LVec4
const remap = function (vin: LVec2, vout: LVec2, t: number)
{
const num = (t - vin[0]) / (vin[1]-vin[0])
return vout[0] + num * (vout[1]-vout[0])
}
const lerp = function <T extends Tin> (vin: T, vout: T, v: number)
{
switch (vin.length)
{
case 2: return vec2.lerp (vec2(), vin as LVec2, vout as LVec2, v) as T
case 3: return vec3.lerp (vec3(), vin as LVec3, vout as LVec3, v) as T
case 4: return vec4.lerp (vec4(), vin as LVec4, vout as LVec4, v) as T
default: throw "Invalid arguments"
}
}
Internal.definePublicMethods ({
lerp,
remap
})
}
;{ // Geometric Functions
type Tin = LVec2|LVec3|LVec4
const length = function (a: Tin)
{
switch (a.length)
{
case 2: return vec2._length (a as LVec2)
case 3: return vec3._length (a as LVec3)
case 4: return vec4._length (a as LVec4)
default: throw "Invalid arguments"
}
}
const distance = function <T extends Tin> (a: T, b: T)
{
switch (a.length)
{
case 2: return vec2.distance (a as LVec2, b as LVec2)
case 3: return vec3.distance (a as LVec3, b as LVec3)
case 4: return vec4.distance (a as LVec4, b as LVec4)
default: throw "Invalid arguments"
}
}
const dot = function <T extends Tin> (a: T, b: T)
{
switch (a.length)
{
case 2: return vec2.dot (a as LVec2, b as LVec2)
case 3: return vec3.dot (a as LVec3, b as LVec3)
case 4: return vec4.dot (a as LVec4, b as LVec4)
default: throw "Invalid arguments"
}
}
const cross = function (a: LVec3, b: LVec3)
{
return vec3.cross (vec3 (), a as LVec3, b as LVec3)
}
const normalize = function <T extends Tin> (a: T): T
{
switch (a.length)
{
case 2: return vec2.normalize (a as LVec2, a as LVec2) as T
case 3: return vec3.normalize (a as LVec3, a as LVec3) as T
case 4: return vec4.normalize (a as LVec4, a as LVec4) as T
default: throw "Invalid arguments"
}
}
/*
T faceforward(T N, T I, T Nref); returns N if dot(Nref, I) < 0, else -N
T reflect(T I, T N); reflection direction I - 2 * dot(N,I) * N
T refract(T I, T N, float eta); refraction vector
*/
Internal.definePublicMethods ({
len: length,
distance,
dot,
cross,
normalize
})
}
// http://www.shaderific.com/glsl-functions
;{ // Component-wise operation
const template1 = function <T extends number|LVecN> (fn: (n: number) => number)
{
return function (a: T): T
{
switch (a.length)
{
case 1:
return fn (a as number) as T
case 2:
const v2 = Object.create (a as LVecN)
v2[0] = fn ((a as LVec2)[0])
v2[1] = fn ((a as LVec2)[1])
return v2
case 3:
const v3 = Object.create (a as LVecN)
v3[0] = fn ((a as LVec3)[0])
v3[1] = fn ((a as LVec3)[1])
v3[2] = fn ((a as LVec3)[2])
return v3
case 4:
const v4 = Object.create (a as LVecN)
v4[0] = fn ((a as LVec4)[0])
v4[1] = fn ((a as LVec4)[1])
v4[2] = fn ((a as LVec4)[2])
v4[3] = fn ((a as LVec4)[4])
return v4
}
throw "Invalid arguments"
}
}
const template1OutB = function <T extends number|LVecN> (fn: (n: number) => boolean)
{
return function (a: T): boolean | LVecB
{
switch (a.length)
{
case 1:
return fn (a as number) as boolean
case 2:
const v2 = Object.create (a as LVecN)
v2[0] = fn ((a as LVec2)[0])
v2[1] = fn ((a as LVec2)[1])
return v2
case 3:
const v3 = Object.create (a as LVecN)
v3[0] = fn ((a as LVec3)[0])
v3[1] = fn ((a as LVec3)[1])
v3[2] = fn ((a as LVec3)[2])
return v3
case 4:
const v4 = Object.create (a as LVecN)
v4[0] = fn ((a as LVec4)[0])
v4[1] = fn ((a as LVec4)[1])
v4[2] = fn ((a as LVec4)[2])
v4[3] = fn ((a as LVec4)[4])
return v4
}
throw "Invalid argument"
}
}
const template2 = function <T extends number|LVecN> (fn: (n1: number, n2: number) => number)
{
return function (a: T, b: T): T
{
switch (a.length)
{
case 1:
return fn (a as number, b as number) as T
case 2:
const v2 = Object.create (a as LVecN)
v2[0] = fn ( (a as LVec2)[0] , (b as LVec2)[0] )
v2[1] = fn ( (a as LVec2)[1] , (b as LVec2)[1] )
return v2
case 3:
const v3 = Object.create (a as LVecN)
v3[0] = fn ( (a as LVec3)[0] , (b as LVec3)[0] )
v3[1] = fn ( (a as LVec3)[1] , (b as LVec3)[1] )
v3[2] = fn ( (a as LVec3)[2] , (b as LVec3)[2] )
return v3
case 4:
const v4 = Object.create (a as LVecN)
v4[0] = fn ( (a as LVec4)[0] , (b as LVec4)[0] )
v4[1] = fn ( (a as LVec4)[1] , (b as LVec4)[1] )
v4[2] = fn ( (a as LVec4)[2] , (b as LVec4)[2] )
v4[3] = fn ( (a as LVec4)[4] , (b as LVec4)[4] )
return v4
}
throw "Invalid arguments"
}
}
const template3 = function <T extends number|LVecN> (fn: (n1: number, n2: number, n3: number) => number)
{
return function (a: T, b: T, c: T): T
{
switch (a.length)
{
case 1:
return fn (a as number, b as number, c as number) as T
case 2:
const v2 = Object.create (a as LVecN)
v2[0] = fn ( (a as LVec2)[0] , (b as LVec2)[0] , (c as LVec2)[0] )
v2[1] = fn ( (a as LVec2)[1] , (b as LVec2)[1] , (c as LVec2)[1] )
return v2
case 3:
const v3 = Object.create (a as LVecN)
v3[0] = fn ( (a as LVec3)[0] , (b as LVec3)[0] , (c as LVec3)[0] )
v3[1] = fn ( (a as LVec3)[1] , (b as LVec3)[1] , (c as LVec3)[1] )
v3[2] = fn ( (a as LVec3)[2] , (b as LVec3)[2] , (c as LVec3)[2] )
return v3
case 4:
const v4 = Object.create (a as LVecN)
v4[0] = fn ( (a as LVec4)[0] , (b as LVec4)[0] , (c as LVec4)[0] )
v4[1] = fn ( (a as LVec4)[1] , (b as LVec4)[1] , (c as LVec4)[1] )
v4[2] = fn ( (a as LVec4)[2] , (b as LVec4)[2] , (c as LVec4)[2] )
v4[3] = fn ( (a as LVec4)[4] , (b as LVec4)[4] , (c as LVec4)[4] )
return v4
}
throw "Invalid arguments"
}
}
// # Angle & Trigonometry Functions [8.1]
Internal.definePublicMethods (
{
sin : template1 (Math.cos),
cos : template1 (Math.cos),
tan : template1 (Math.tan),
asin : template1 (Math.asin),
acos : template1 (Math.acos),
atan : template1 (Math.atan),
/* GLES 3.0 */
sinh : template1 (Math.sinh),
cosh : template1 (Math.cosh),
tanh : template1 (Math.tanh),
asinh : template1 (Math.asinh),
acosh : template1 (Math.acosh),
atanh : template1 (Math.atanh)
})
// # Exponential Functions [8.2]
Internal.definePublicMethods (
{
pow : template2 (Math.pow),
exp : template1 (Math.exp),
log : template1 (Math.log),
exp2 : template1 ((n) => Math.pow (2, n)),
log2 : template1 (Math.log2),
sqrt : template1 (Math.sqrt)
//inversesqrt
})
// # Common Functions [8.3]
Internal.definePublicMethods (
{
abs : template1 (Math.abs),
sign : template1 (Math.sign),
floor : template1 (Math.floor),
trunc : template1 (Math.trunc),
round : template1 (Math.round),
//roundEven
ceil : template1 (Math.ceil),
fract : template1 ((n) => n - Math.floor (n)),
mod : template2 ((a, b) => a % b),
min : template2 (Math.min),
max : template2 (Math.max),
clamp : template3 ((a, b, c) => Math.min (Math.max (a, b), c)),
//mix == lerp ?
step : template2 ((a, b) => b < a ? 0 : 1),
//smoothstep
isnan : template1OutB (isNaN),
isinf : template1OutB ((a) => a == Infinity)
// floatBitsToInt
// intBitsToFloat
})
}
// # Angle & Trigonometry Functions [8.1]
// In case of a vector the operation is calculated separately for every component.
declare function sin <T extends number|LVecN> (radian: T) : T
declare function cos <T extends number|LVecN> (radian: T) : T
declare function tan <T extends number|LVecN> (radian: T) : T
declare function asin <T extends number|LVecN> (radian: T) : T
declare function acos <T extends number|LVecN> (radian: T) : T
declare function atan <T extends number|LVecN> (radian: T) : T
/* GLES 3.0 */
declare function sinh <T extends number> (radian: T) : T
declare function sinh <T extends LVecN> (radian: T) : T
declare function cosh <T extends number> (radian: T) : T
declare function cosh <T extends LVecN> (radian: T) : T
declare function tanh <T extends number> (radian: T) : T
declare function tanh <T extends LVecN> (radian: T) : T
declare function asinh <T extends number> (radian: T) : T
declare function asinh <T extends LVecN> (radian: T) : T
declare function acosh <T extends number> (radian: T) : T
declare function acosh <T extends LVecN> (radian: T) : T
declare function atanh <T extends number> (radian: T) : T
declare function atanh <T extends LVecN> (radian: T) : T
// # Exponential Functions [8.2]
// In case of a vector the operation is calculated separately for every component.
declare function pow <T extends number> (n1: T, n2: T) : T
declare function pow <T extends LVecN> (n1: T, n2: T) : T
declare function exp <T extends number> (n: T) : T
declare function exp <T extends LVecN> (n: T) : T
declare function log <T extends number> (n: T) : T
declare function log <T extends LVecN> (n: T) : T
declare function exp2 <T extends number> (n: T) : T
declare function exp2 <T extends LVecN> (n: T) : T
declare function log2 <T extends number> (n: T) : T
declare function log2 <T extends LVecN> (n: T) : T
declare function sqrt <T extends number> (n: T) : T
declare function sqrt <T extends LVecN> (n: T) : T
//inversesqrt
// # Common Functions [8.3]
// In case of a vector the operation is calculated separately for every component.
declare function abs <T extends number|LVecN> (n: T) : T
declare function sign <T extends number|LVecN> (n: T) : T
declare function floor <T extends number|LVecN> (n: T) : T
declare function trunc <T extends number|LVecN> (n: T) : T
declare function round <T extends number|LVecN> (n: T) : T
declare function ceil <T extends number|LVecN> (n: T) : T
declare function fract <T extends number|LVecN> (n: T) : T
declare function mod <T extends number|LVecN> (n1: T, n2: T) : T
declare function min <T extends number|LVecN> (n1: T, n2: T) : T
declare function max <T extends number|LVecN> (n1: T, n2: T) : T
declare function clamp <T extends number|LVecN> (n1: T, n2: T, a: T) : T
declare function step <T extends number|LVecN> (n1: T, n2: T) : T
declare function isnan <T extends number|LVecN> (n: T) : boolean | LVecB
declare function isinf <T extends number|LVecN> (n: T) : boolean | LVecB
|
2f62e4fab3aeb3d634fbcf8e9781cb106515e65d
|
TypeScript
|
NiluK/api
|
/packages/api/src/promise/Combinator.ts
| 2.921875
| 3
|
// Copyright 2017-2018 @polkadot/api authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { isFunction } from '@polkadot/util';
export type CombinatorCallback = (value: Array<any>) => any;
export type CombinatorFunction = (cb: (value: any) => void) => any;
export default class Combinator {
protected _allHasFired: boolean = false;
protected _callback: CombinatorCallback;
protected _fired: Array<boolean> = [];
protected _results: Array<any> = [];
constructor (fns: Array<CombinatorFunction>, callback: CombinatorCallback) {
this._callback = callback;
fns.forEach((fn, index) => {
this._fired.push(false);
fn(this.createCallback(index));
});
}
protected allHasFired (): boolean {
if (!this._allHasFired) {
this._allHasFired = this._fired.filter((hasFired) => !hasFired).length === 0;
}
return this._allHasFired;
}
protected createCallback (index: number) {
return (value: any): void => {
this._fired[index] = true;
this._results[index] = value;
this.triggerUpdate();
};
}
protected triggerUpdate (): void {
if (!isFunction(this._callback) || !this.allHasFired()) {
return;
}
try {
this._callback(this._results);
} catch (error) {
// swallow, we don't want the handler to trip us up
}
}
}
|
e5fa2fe3006456ef58598026425537b16149a039
|
TypeScript
|
KilianSL/project-rhino
|
/src/utils/redux/reducers.ts
| 2.84375
| 3
|
import {combineReducers, createStore, Action } from 'redux';
// App metadata
const app = (state={name:""}, action: Action) => { // action has its type explicitely defined because it is not given a default to infer from
return {
name: 'Project Rhino'
}
};
const createPostDialog = (state={open: false}, action : Action) => {
switch (action.type) {
case "TOGGLE_CREATE_POST_DIALOG":
console.log("Post Window Visible: ", !state.open);
return {open : !state.open};
default:
return state;
}
}
const reducer = combineReducers({app, createPostDialog});
const store = createStore(reducer);
export default store;
|
6f32e84183255f2511c99ed454bd1d260ecf36a7
|
TypeScript
|
PositivePerson/VakerVideoEditor
|
/src/redux/user/user.reducer.ts
| 2.9375
| 3
|
import { SIGNIN } from './user.types';
export interface IUserState {
tokenData: object;
jwtToken: string | null;
isLoggedIn: boolean;
}
const initialState: IUserState = {
tokenData: {},
isLoggedIn: false,
jwtToken: null,
};
const ACTION_HANDLERS: any = {
[SIGNIN]: (state: any, { tokenData, jwtToken, isLoggedIn }: any) => ({
...state,
tokenData,
jwtToken,
isLoggedIn,
}),
};
export default function userReducer(state = initialState, action: any) {
const handler = ACTION_HANDLERS[action.type];
return handler ? handler(state, action) : state;
}
|
7331de4927511295e4714b0eb461b08466350e6e
|
TypeScript
|
Ihnatiev/BackEmpList2
|
/api/test/unit tests/controller tests/employees.ts
| 2.59375
| 3
|
import { Http } from './http';
export class Employees {
private _http: Http;
constructor() {
this._http = new Http();
}
public async findAll() {
// we actually don't need this intermediate step,
// we could just
// return this._http.get('employees');
// but then this method would be too dumb and not very interesting
const employees = await this._http.get('employees');
return employees;
}
}
|
7645005093154c179919fb33da0f61644f639828
|
TypeScript
|
mocheer/map
|
/src/providers/GaoDeProvider.ts
| 2.828125
| 3
|
/**
* author mocheer
*/
import {AbstractMapProvider} from './AbstractMapProvider';
import {Coordinate} from '../core/Coordinate';
import {IMapProvider} from './IMapProvider';
/**
* 高德瓦片地图数据源提供程序
*/
export class GaoDeProvider extends AbstractMapProvider implements IMapProvider {
type: string;
/**
* 各类数据源URL模板,根据镜像服务器编号、数据源类型、投影坐标等,可生成最终的瓦片URL数组
*/
urlTemplate: any;
/**
* 高德地图数据源构造函数
* @param minZoom 数据源最小缩放级别
* @param maxZoom 数据源最大缩放级别
*/
constructor() {
super();
}
/**
* 返回特定投影坐标处的瓦片URL数组。
* @param coord 投影坐标
* @return 坐标对应的瓦片数组。
*/
getTileUrls(coord: Coordinate): any[] {
if (coord.row < 0 || coord.row >= Math.pow(2, coord.zoom)) {
return null;
}
var sourceCoord: Coordinate = this.sourceCoordinate(coord);
var server: number = coord.row%4 +1;//随机镜像服务器编号
var url: any = this.urlTemplate;
if(typeof url === "object"){
return url.map(value => {
return value.format(server, sourceCoord.column, sourceCoord.row, sourceCoord.zoom)
})
}
var result = url.format(server, sourceCoord.column, sourceCoord.row, sourceCoord.zoom)
return [result];
}
/**
* @return 高德数据源字符串描述信息
*/
toString(): string {
return "GaoDeProvider_" + this.type;
}
}
/**
* 高德电子图(交通图)
*/
export class GaoDeProvider_ROAD extends GaoDeProvider {
type: string = "ROAD";
urlTemplate: any = "http://webrd0{0}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={1}&y={2}&z={3}";
constructor() {
super();
}
}
/**
* 高德卫星图(st:SATELLITE)
*/
export class GaoDeProvider_AERIAL extends GaoDeProvider {
type: string = "AERIAL";
urlTemplate: any = ["http://webst0{0}.is.autonavi.com/appmaptile?scale=1&style=6&x={1}&y={2}&z={3}","http://webst0{0}.is.autonavi.com/appmaptile?scale=1&style=8&x={1}&y={2}&z={3}"];
constructor() {
super();
}
}
|
a4e68d96227a9cdacd92c407cf1454a9759c43b1
|
TypeScript
|
zhuxinyu-znb/ts-laboratory
|
/6-1.泛型与Type区别.ts
| 4.625
| 5
|
//总结:
// 1.能用 interface 实现,就用 interface , 如果不能就用 type
// 2.https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases
// 类型别名 创建新类型就用interface 组合类型就用type
//相同点
/**
* 1.都可以描述一个对象或者函数
* 2.都允许拓展(extends)
*/
//不同点
/**
* 1.type 可以而 interface 不行
* 1-1 type 可以声明基本类型别名,联合类型,元组等类型
* 1-2 type 语句中还可以使用 typeof 获取实例的 类型进行赋值
* 2.interface 可以而 type 不行
* 2-1 interface 能够声明合并
*/
//----------相同点1-----------
// interface User {
// name: string
// age: number
// }
// interface SetUser {
// (name: string, age: number): void;
// }
//---------------------
// type User = {
// name: string
// age: number
// };
// type SetUser = (name: string, age: number)=> void;
// const fn:SetUser = (name: string, age: number)=>{
// console.log(`name${name} -> ${age}`);
// }
// fn("老袁",30);
//----------相同点2-------------
// interface Name {
// name: string;
// }
// interface User extends Name {
// age: number;
// }
// type Name = {
// name: string;
// };
// type User = Name & { age: number };
//----比较繁杂的类型转化-------
// type Name = {
// name: string;
// };
// interface User extends Name {
// age: number;
// }
// interface Name {
// name: string;
// }
// type User = Name & {
// age: number;
// };
//---不同点1---
// type 可以而 interface 不行
// type 可以声明基本类型别名,联合类型,元组等类型
// 基本类型别名
// type Name = string
// // 联合类型
// interface Dog {
// wong();
// }
// interface Cat {
// miao();
// }
// type Pet = Dog | Cat
// // 具体定义数组每个位置的类型
// type PetList = [Dog, Pet]
//type 语句中还可以使用 typeof 获取实例的 类型进行赋值
// 当你想获取一个变量的类型时,使用 typeof
// let div = document.createElement('div');
// type B = typeof div
//其他
// type StringOrNumber = string | number;
// type Text = string | { text: string };
// type NameLookup = Dictionary<string, Person>;
// type Callback<T> = (data: T) => void;
// type Pair<T> = [T, T];
// type Coordinates = Pair<number>;
// type Tree<T> = T | { left: Tree<T>, right: Tree<T> };
//---不同点2---
// interface 可以而 type 不行
// interface 能够声明合并
// interface User {
// name: string
// age: number
// }
// interface User {
// sex: string
// }
/*
User 接口为 {
name: string
age: number
sex: string
}
*/
|
a418bdf2a9584677e35bf31616e9f8f2f73366ef
|
TypeScript
|
jrwalt4/arga
|
/src/types/collections/sorted-array.d.ts
| 2.96875
| 3
|
declare module "collections/sorted-array" {
import GenericCollection = require('collections/generic-collection');
import PropertyChanges = require('collections/listen/property-changes');
import RangeChanges = require('collections/listen/range-changes');
export = SortedArray;
let SortedArray: SortedArrayConstructor
interface SortedArrayConstructor {
/**
* Hack so require('sorted-array').SortedArray
* will work in MontageJS
*/
SortedArray: SortedArrayConstructor
(values?: any[], equals?: (a, b) => boolean, compare?: (a, b) => number, getDefault?: () => any): SortedArray<any>
<T>(values?: T[], equals?: (a: T, b: T) => boolean, compare?: (a: T, b: T) => number, getDefault?: () => T): SortedArray<T>
new (values?: any[], equals?: (a, b) => boolean, compare?: (a, b) => number, getDefault?: () => any): SortedArray<any>
new <T>(values?: T[], equals?: (a: T, b: T) => boolean, compare?: (a: T, b: T) => number, getDefault?: () => T): SortedArray<T>
from<T>(values?: T[]): SortedArray<T>
}
interface SortedArray<T> extends
GenericCollection<number, T>,
PropertyChanges<SortedArray<T>>,
RangeChanges<T> {
isSorted: true
length:number
array:T[]
has(value: any): boolean
get(value: any): T
add(value: T): boolean
delete(value: any): boolean
deleteAll(value: any, equals?:(a:T, b:T)=>boolean): number
indexOf(value:any):T
/**
* Replaces a length of values from a starting position
* with the given values
*/
swap(start: number, length: number, values?: T[])
lastIndexOf(value: any): number
//find(value:any, equals?:ContentEquals, start?:number):T
/**
* Finds the first equivalent value
* @param equivalent value
* @param equivalence test
* @param start index to begin search
*/
findValue(value: any, equals?: (a:T, b:T)=>boolean, start?: number): T
findLastValue(value: any, equals?: (a:T, b:T)=>boolean, start?: number): T
/**
* Returns one, arbitrary value from this collection,
* or <i>undefined</i> if there are none.
*/
one(): T
clear()
toJSON(): string
equals(value: any, equals?: (a:T, b:T)=>boolean): boolean
compare(value: any, compare?: (a:T, b:T)=>number): number
/**
* Creates a shallow clone of this collection.
*/
constructClone(values?: T[]): this
}
}
|
8df7e0b3d70caae84328e3c6e9e4b68d217fe5c1
|
TypeScript
|
sanity-io/sanity
|
/packages/sanity/src/core/theme/types.ts
| 2.546875
| 3
|
import type {RootTheme, ThemeColorSchemeKey} from '@sanity/ui'
/** @public */
export interface StudioTheme extends RootTheme {
/** @internal */
__dark?: boolean
/** @internal */
__legacy?: boolean
}
/**
* Used to specify light or dark mode, or to respect system settings (prefers-color-scheme media query) use 'system'
* @public
*/
export type StudioThemeColorSchemeKey = ThemeColorSchemeKey | 'system'
|
7f7955a1167cf91eb303bea8b4fd2827f6a0adc8
|
TypeScript
|
Snuggle/Ba
|
/src/commands/reactions.ts
| 2.859375
| 3
|
import { Command } from './command'
import { Emote } from '../models/emote'
import { CommandInteraction } from 'discord.js'
/**
* Prints a list of all emotes which are active for today.
*/
export const ReactionsCommand: Command = {
data: {
name: 'reactions',
description: 'Prints a list of all currently active emotes.',
defaultPermission: true
},
execute: async (interaction: CommandInteraction): Promise<void> => {
const emotes = await Emote.forToday()
let returnMessage = 'Today\'s active emotes are:\n'
emotes.forEach((emote) => {
returnMessage += `• ${emote.formattedEmoji()} (\`${emote.name}\`)\n`
})
await interaction.reply(returnMessage)
}
}
|
65d6ea07d633fdd2dc917e2db87f94db20702c2f
|
TypeScript
|
acrois/falling-sand
|
/src/index.ts
| 2.609375
| 3
|
import { Canvas } from "./canvas";
import { Sand } from "./sand";
import { Particle } from "./particle";
import * as Color from 'color';
let canvas = new Canvas(<HTMLCanvasElement>document.getElementById('sand'));
let sand = new Sand(canvas);
let w: any = window;
w.sand = sand;
let targetFPS = 60;
sand.start(targetFPS);
function initialize() {
// Register an event listener to call the resizeCanvas() function
// each time the window is resized.
window.addEventListener('resize', resizeCanvas, false);
window.addEventListener('mousemove', mouseParticle, false);
window.addEventListener('mousedown', mouseParticle, false);
window.addEventListener('mouseup', mouseParticle, false);
window.addEventListener('click', mouseParticle, false);
resizeCanvas();
}
function resizeCanvas() {
canvas.resize(Math.min(480, window.innerWidth), Math.min(240, window.innerHeight));
}
function mouseParticle(e: MouseEvent) {
if (!e.buttons) {
return false;
}
/*
MouseEvent {isTrusted: true, screenX: 608, screenY: 501, clientX: 608, clientY: 430, …}
altKey: false
bubbles: true
button: 0
buttons: 1
cancelBubble: false
cancelable: true
clientX: 608
clientY: 430
composed: true
ctrlKey: false
currentTarget: null
defaultPrevented: false
detail: 0
eventPhase: 0
fromElement: null
isTrusted: true
layerX: 608
layerY: 430
metaKey: false
movementX: -3
movementY: -1
offsetX: 608
offsetY: 430
pageX: 608
pageY: 430
path: (5) [canvas#sand, body, html, document, Window]
relatedTarget: null
returnValue: true
screenX: 608
screenY: 501
shiftKey: false
sourceCapabilities: InputDeviceCapabilities {firesTouchEvents: false}
srcElement: canvas#sand
target: canvas#sand
timeStamp: 1598.0950000230223
toElement: canvas#sand
type: "mousemove"
view: Window {parent: Window, postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, …}
which: 1
x: 608
y: 430
__proto__: MouseEvent
*/
let brushWidth = 5;
let brushHeight = 5;
sand.pause();
for (let y = e.offsetY; y < e.offsetY + brushWidth; y++) {
for (let x = e.offsetX; x < e.offsetX + brushWidth; x++) {
if (e.button == 0) {
sand.createPosition(x, y, Particle.SAND_COLOR);
}
else if (e.button == 2) {
sand.createPosition(x, y, Particle.SNOW_SPAWN_COLOR);
}
}
}
sand.start(targetFPS);
e.stopPropagation();
e.cancelBubble = true;
return false;
}
initialize();
|
cc5eed4ad901d2c6f76ea8bd67609ecff5404ebb
|
TypeScript
|
markwetzel/ts-playground
|
/src/design-patterns/factory/FactoryMethod/Custom/models/Item/Weapon/Melee/OneHandedMeleeWeapon.ts
| 2.765625
| 3
|
import { MeleeWeapon } from "./MeleeWeapon";
export abstract class OneHandedMeleeWeapon extends MeleeWeapon {
constructor(
name: string,
level: number,
attackPower: number,
weight: number
) {
super(name, level, attackPower, weight);
}
}
|
a3e077efca2b346f5d46c987b3bff27b59438898
|
TypeScript
|
bodryi/polynoms-app
|
/src/app/store/result-vectors/reducer.ts
| 3.046875
| 3
|
import * as Action from './actions';
import * as MainAction from '../main/actions';
import { RESULTS_COUNT } from '../../constants/app.constants';
export interface State {
result: Array<Array<Array<string>>>;
activeResult: Array<number>;
matrixSize: number;
}
const initialState: State = {
result: [
getEmptyVector(RESULTS_COUNT).map(() => getEmptyVector(4)),
getEmptyVector(RESULTS_COUNT).map(() => getEmptyVector(6)),
],
activeResult: [0, 0],
matrixSize: null,
};
function getEmptyVector(vectorSize: number): Array<string> {
return new Array(vectorSize).fill('');
}
function getIndex(matrixSize: number): number {
return (matrixSize - 4) / 2;
}
function deepArrayCopy(arr: Array<Array<string>>): Array<Array<string>> {
return arr && arr.map(innerArr => innerArr.slice());
}
function setVector(
state: Array<Array<Array<string>>>,
payload: Array<string>,
activeResult: number,
matrixSize: number,
): Array<Array<Array<string>>> {
const newResult = state.map(res => deepArrayCopy(res));
newResult[getIndex(matrixSize)][activeResult] = [...payload];
return newResult;
}
function setActiveResult(
state: Array<number>,
payload: number,
matrixSize: number,
) {
return state.map(
(v, index) => (index === getIndex(matrixSize) ? payload : v),
);
}
export function reducer(state = initialState, action: any): State {
switch (action.type) {
case Action.SET_ACTIVE_RESULT_VECTOR:
return {
...state,
activeResult: setActiveResult(
state.activeResult,
action.payload,
state.matrixSize,
),
};
case Action.SET_RESULT:
return {
...state,
result: setVector(
state.result,
action.payload.vector,
action.payload.index,
state.matrixSize,
),
};
case Action.CLEAR:
return {
...state,
result: setVector(
state.result,
getEmptyVector(state.matrixSize),
action.payload,
state.matrixSize,
),
};
case MainAction.SET_MATRIX_SIZE:
return {
...state,
matrixSize: action.payload,
};
default:
return state;
}
}
export const getResult = (state: State) =>
state.result[getIndex(state.matrixSize)];
export const getActiveResult = (state: State) =>
state.activeResult[getIndex(state.matrixSize)];
|
cefe1b3eda3367564ad35f0ec96486527cf9626f
|
TypeScript
|
dapplets/dapplet-extension
|
/src/contentscript/modules/widgetsCreator.ts
| 2.71875
| 3
|
import { State } from './state'
import { IWidget, WidgetConfig } from './types'
export class WidgetsCreator {
private stateStorage = new Map<string, State<any>>()
public createWidgetFactory<T>(Widget: any) {
const me = this
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = (Math.random() * 16) | 0,
v = c == 'x' ? r : (r & 0x3) | 0x8
return v.toString(16)
})
}
function createWidget(
Widget: any,
builder: any,
_insPointName: string,
config: { [state: string]: T },
order: number,
contextNode: Element,
clazz: string
): any {
if (order === undefined || order === null) {
//console.error('Empty order!');
order = 0
}
const context = builder && builder.contexts ? builder.contexts.get(contextNode) : null
const state = (() => {
const hasId = context && context.parsed.id !== undefined
if (!hasId) {
// console.error(
// 'Warning: Each parsed context in an adapter should have a unique "id" property. Restoring of widget states will be unavailable.'
// )
return new State<T>(config, null, null)
}
// ToDo: Why 'context.parsed.id' used as string. Looks like copypaste from dynamic-adater
const key = clazz + '/' + 'context.parsed.id'
if (!me.stateStorage.has(key)) {
const state = new State<T>(config, context.parsed, builder.theme)
me.stateStorage.set(key, state)
}
return me.stateStorage.get(key)
})()
let widget: any = null
widget = new Widget() as IWidget<T>
widget.state = state.state
widget.insPointName = state.INITIAL_STATE
state.changedHandler = () => widget.mount()
widget.mount() // ToDo: remove it?
return widget
}
return (config: WidgetConfig<T>) => {
const uuid = uuidv4()
return (builder: any, insPointName: string, order: number, contextNode: Element) =>
createWidget(Widget, builder, insPointName, config, order, contextNode, uuid)
}
}
}
|
1633e3fcf5f2cf3ce11c93e73fd42ce4e60acfa7
|
TypeScript
|
nouakun/react-horizontal-timeline
|
/lib/esm/types/Components/Events.d.ts
| 2.671875
| 3
|
import React from "react";
/**
* Component propTypes
*/
export declare type EventsProps = {
events: {
distance: number;
label: JSX.Element | string;
date: string;
}[];
selectedIndex: number;
handleDateClick: (index: number) => void;
labelWidth: number;
styles?: any;
isRtl: boolean;
};
/**
* The markup Information for all the events on the horizontal timeline.
*
* @param {object} props The props from parent mainly styles
* @return {StatelessFunctionalReactComponent} Markup Information for the fader
*/
declare const Events: React.FC<EventsProps>;
export default Events;
|
e5b31432cd8f740a363d9c975c5e34f361216a43
|
TypeScript
|
oscaroceguera/js-references-web
|
/src/pages/Editor/reducer.ts
| 2.734375
| 3
|
import React from 'react';
import { IInitialState } from './types';
import { IEditorActions, SET_FIELDS, UPDATE_FIELDS } from './actions';
const reducer: React.Reducer<IInitialState, IEditorActions> = (
state,
action,
) => {
switch (action.type) {
case SET_FIELDS:
return {
...state,
[action.payload.field]: action.payload.value,
};
case UPDATE_FIELDS:
const { category, title, tags, content } = action.payload;
return {
...state,
category,
title,
tags,
content,
};
default:
return state;
}
};
export default reducer;
|
3533aa8946088d6a1578c7884b8f067d62dac6e2
|
TypeScript
|
elancer-dev/f-test
|
/src/utils/reducer.ts
| 2.65625
| 3
|
import { TState, TAction } from './types';
export const initialState: TState = {
points: [
// { coord: [55.753215, 37.622504], name: 'Москва', },
// { coord: [56.185102, 36.977631], name: 'Солнечногорск', },
// { coord: [55.991390, 36.484994], name: 'село Новопетровское', },
],
}
export function reducer(state: TState = initialState, action: TAction<any, any>): TState {
if (action.handler !== undefined && typeof action.handler[action.type] === 'function') {
return action.handler[action.type](state, action.data);
} else {
return state;
}
}
|
1a0bc89cff7ce49e10a4b5c7daabb53dcbe78213
|
TypeScript
|
a-hess5/mun-tools
|
/target/flow-frontend/Authentication.d.ts
| 2.90625
| 3
|
import { MiddlewareClass, MiddlewareContext, MiddlewareNext } from './Connect';
export interface LoginResult {
error: boolean;
token?: string;
errorTitle?: string;
errorMessage?: string;
redirectUrl?: string;
defaultUrl?: string;
}
export interface LoginOptions {
loginProcessingUrl?: string;
}
export interface LogoutOptions {
logoutUrl?: string;
}
/**
* A helper method for Spring Security based form login.
* @param username
* @param password
* @param options defines additional options, e.g, the loginProcessingUrl etc.
*/
export declare function login(username: string, password: string, options?: LoginOptions): Promise<LoginResult>;
/**
* A helper method for Spring Security based form logout
* @param options defines additional options, e.g, the logoutUrl.
*/
export declare function logout(options?: LogoutOptions): Promise<void>;
/**
* It defines what to do when it detects a session is invalid. E.g.,
* show a login view.
* It takes an <code>EndpointCallContinue</code> parameter, which can be
* used to continue the endpoint call.
*/
export declare type OnInvalidSessionCallback = () => Promise<LoginResult>;
/**
* A helper class for handling invalid sessions during an endpoint call.
* E.g., you can use this to show user a login page when the session has expired.
*/
export declare class InvalidSessionMiddleware implements MiddlewareClass {
private onInvalidSessionCallback;
constructor(onInvalidSessionCallback: OnInvalidSessionCallback);
invoke(context: MiddlewareContext, next: MiddlewareNext): Promise<Response>;
}
|
d07e343863f57f0d29af53b9cc0ff67b6d717b24
|
TypeScript
|
AntonShilin/eshop
|
/src/Reducers/HeaderPanelReducer.ts
| 2.9375
| 3
|
import {
IHeaderPanelState,
HeaderPanelActions,
OpenHeaderSearchPanelTypes,
CloseHeaderSearchPanelTypes,
ToggleSmallScreenSubmenuTypes,
SelectIdGenreInSubmenuTypes,
OpenSelectedGenreTypes,
CloseSelectedGenreTypes,
} from "../Types/HeaderPanelTypes";
const headerPanelState: IHeaderPanelState = {
isOpen: false,
isToggle: false,
id: 0,
isOpenSelectedGenre: false,
};
export const headerPanelReducer = (
state: IHeaderPanelState = headerPanelState,
action: HeaderPanelActions
): IHeaderPanelState => {
switch (action.type) {
case OpenHeaderSearchPanelTypes.OPENHEADERSEARCHPANEL: {
return {
...state,
isOpen: action.value,
};
}
case CloseHeaderSearchPanelTypes.CLOSEHEADERSEARCHPANEL: {
return {
...state,
isOpen: action.value,
};
}
case ToggleSmallScreenSubmenuTypes.TOGGLESMALLSCREENSUBMENU: {
return {
...state,
isToggle: action.isToggle,
};
}
case SelectIdGenreInSubmenuTypes.SELECTIDGENREINSUBMENU: {
return {
...state,
id: action.id,
};
}
case OpenSelectedGenreTypes.OPENSELECTEDGENRE: {
return {
...state,
isOpenSelectedGenre: action.value,
};
}
case CloseSelectedGenreTypes.CLOSESELECTEDGENRE: {
return {
...state,
isOpenSelectedGenre: action.value,
};
}
default:
return state;
}
};
|
89236e4741bc4e5dbf181113e9df16edef48561e
|
TypeScript
|
Designer023/training-plan-generator
|
/src/types/index.ts
| 2.53125
| 3
|
import { DayPlan } from "./index";
import { Moment } from "moment";
export interface UserSpec {
PLAN_LENGTH: number;
PLAN_TAIL_OFF_LENGTH: number;
PLAN_RECOVER_WEEK_EVERY: number;
PLAN_START_DISTANCE: number;
PLAN_END_DISTANCE: number;
PLAN_START_DATE: string;
USER_MAX_HR: number;
USER_PACES: {
// PACES in m per sec
ENDURANCE: number;
STAMINA: number;
};
}
export interface Run {
spec: {
duration: number;
approx_distance: number;
};
effort: {
rpe: {
min: number;
max: number;
};
hr: {
min: number;
max: number;
};
hrp: {
min: number;
max: number;
};
name: string;
};
}
export interface Cross {}
export interface Activity {
type: string; // run, cross, hit, flex
category: string;
title?: string;
description?: string;
details?: Run | Cross;
}
export interface Day {
date: Moment;
humanDate: string;
}
export interface Details {
type: string;
category: string;
title: string;
}
export interface DayPlan {
date: Moment;
title: string;
category: string;
activity: string;
description?: string;
time: number | null;
distance: number | null;
effortClass?: string;
effortRPE?: number[];
effortHR?: number[];
}
export interface WeekPlan {
number: number;
startDate: Moment;
focus: string;
weekDistance: number;
weekTime: number;
description?: string;
days: DayPlan[];
}
export type Class = { new (...args: any[]): any };
export interface ProgressType {
nextLongDistance(multiplier?: number, week?: number): number;
nextBaseDistance(hold?: boolean): number;
growthRatePercent: number;
nextFlexRoutine(): any;
nextHITRoutine(): any;
nextCrossRoutine(): any;
updateWeekStats(distance?: number, time?: number): void;
resetWeekStats(): void;
createPlan(): WeekPlan[];
createWeekDays(
week: number,
focus: string,
weekStartDate: Moment
): { days: DayPlan[]; distance: number; time: number };
createWeek(w: number, focus: string): WeekPlan;
getDescription(focus: string): string;
createDayPlan(
weekStartDate: Moment,
dayOfWeek: number,
focus: string,
planStrategies: string[]
): DayPlan;
}
export interface CrossType {
group: string;
types: string[];
}
export interface ActivityGroupType {
routine: string[];
}
export interface CrossRoutineType {
category: string;
type: string;
activity: ActivityGroupType;
}
|
0faf1913cb4b497453e00c16087ac3af720a6491
|
TypeScript
|
haiertech/homes
|
/src/utilities/serverContext/database/entities/Message.ts
| 2.703125
| 3
|
import {
Column,
CreateDateColumn,
Entity,
getRepository,
UpdateDateColumn,
} from 'typeorm'
import * as types from '@/types'
import { PapyrEntity } from './PapyrEntity'
import {
DbAwareColumn,
DbAwarePGC,
sanitizeConditions,
} from '../utilities'
@Entity()
export class Message extends PapyrEntity {
@DbAwarePGC()
id!: string
@Column()
name!: string
@Column()
email!: string
@DbAwareColumn({ type: 'text' })
message!: string
@Column()
emailSent!: boolean
@CreateDateColumn()
createdAt!: Date
@UpdateDateColumn()
updatedAt!: Date
toModel(): types.Message {
return {
id: this.id.toString(),
name: this.name,
email: this.email,
message: this.message,
emailSent: this.emailSent,
updatedAt: new Date(this.updatedAt),
createdAt: new Date(this.createdAt),
}
}
static async saveFromModel(
message: types.Message
): Promise<types.Message> {
const messageRepo = getRepository<Message>('Message')
let foundMessage
if (message.id) {
foundMessage = await messageRepo.findOne({
where: sanitizeConditions({
id: message.id,
}),
})
}
if (!foundMessage) {
foundMessage = messageRepo.create()
}
foundMessage.name = message.name
foundMessage.email = message.email
foundMessage.message = message.message
foundMessage.emailSent = message.emailSent
foundMessage = await foundMessage.save()
return await foundMessage.toModel()
}
}
|