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
|
|---|---|---|---|---|---|---|
5621f4a138fc45a89ad429a0276a29f5af78612b
|
TypeScript
|
visgl/deck.gl
|
/modules/geo-layers/src/geohash-layer/geohash-layer.ts
| 2.6875
| 3
|
import {AccessorFunction, DefaultProps} from '@deck.gl/core';
import GeoCellLayer from '../geo-cell-layer/GeoCellLayer';
import {getGeohashPolygon} from './geohash-utils';
const defaultProps: DefaultProps<GeohashLayerProps> = {
getGeohash: {type: 'accessor', value: d => d.geohash}
};
/**
* Properties of `GeohashLayer`.
*/
type GeohashLayerProps<DataT = any> = {
/**
* Called for each data object to retrieve the geohash string identifier.
*
* By default, it reads `geohash` property of data object.
*/
getGeohash?: AccessorFunction<DataT, string>;
};
/** Render filled and/or stroked polygons based on the [Geohash](https://en.wikipedia.org/wiki/Geohash) geospatial indexing system. */
export default class GeohashLayer<DataT = any, ExtraProps extends {} = {}> extends GeoCellLayer<
DataT,
Required<GeohashLayerProps> & ExtraProps
> {
static layerName = 'GeohashLayer';
static defaultProps = defaultProps;
indexToBounds(): Partial<GeoCellLayer['props']> | null {
const {data, getGeohash} = this.props;
return {
data,
_normalize: false,
positionFormat: 'XY',
getPolygon: (x: DataT, objectInfo) => getGeohashPolygon(getGeohash(x, objectInfo))
};
}
}
|
121d875c0bbd9c2157fc6ddce5eb5e2e254bfe10
|
TypeScript
|
timjansen/jillian
|
/src/jel/types/Distribution.ts
| 2.953125
| 3
|
import Util from '../../util/Util';
import JelObject from '../JelObject';
import Runtime from '../Runtime';
import Context from '../Context';
import List from './List';
import Range from './Range';
import DistributionPoint from './DistributionPoint';
import ApproximateNumber from './ApproximateNumber';
import Numeric from './Numeric';
import JelBoolean from './JelBoolean';
import UnitValue from './UnitValue';
import Float from './Float';
import Fraction from './Fraction';
import TypeChecker from './TypeChecker';
import NativeJelObject from './NativeJelObject';
import Class from './Class';
import BaseTypeRegistry from '../BaseTypeRegistry';
const INVERSE_OP = {'<': '>', '<=': '>=', '>': '<', '>=': '<='};
/**
* This class is used to specify property values when there can be more than one value, especially for categories.
* It can either define min/max/typical values, or handle a large number of data points and interpolate between them.
*/
export default class Distribution extends NativeJelObject {
public points_jel_property: boolean;
public points: DistributionPoint[];
average_jel_property: boolean;
static clazz: Class|undefined;
constructor(distributionPoints: List|null, public average: Numeric|null, min: Numeric|null, max: Numeric|null, mean: Numeric|null) {
super('Distribution');
this.points = distributionPoints != null ? distributionPoints.elements.slice() : [];
if (min != null)
this.points.push(new DistributionPoint(min, 0));
if (mean != null)
this.points.push(new DistributionPoint(mean, 0.5));
if (max != null)
this.points.push(new DistributionPoint(max, 1));
if (!this.points.length)
throw new Error("Can not create distribution without any points");
this.points.sort((a: DistributionPoint, b: DistributionPoint)=> a.share-b.share);
}
get clazz(): Class {
return Distribution.clazz!;
}
add_jel_mapping: boolean;
add(ctx: Context, distributionPoints?: List, average?: Numeric, min?: Numeric, max?: Numeric, mean?: Numeric): Distribution {
const np = new Map<number, DistributionPoint>(this.points.map(p=>[p.share, p] as any));
if (distributionPoints)
distributionPoints.elements.forEach(p=>np.set(p.share, p));
if (min != null)
np.set(0, new DistributionPoint(min, 0));
if (max != null)
np.set(1, new DistributionPoint(max, 1));
if (mean != null)
np.set(0.5, new DistributionPoint(mean, 0.5));
return new Distribution(new List(np.values()), average != null ? average : this.average, null, null, null);
}
mean_jel_mapping: boolean;
mean(ctx: Context): Numeric {
return this.getValue(ctx, 0.5);
}
max_jel_mapping: boolean;
max(ctx: Context): Numeric {
return this.getValue(ctx, 1);
}
min_jel_mapping: boolean;
min(ctx: Context): Numeric {
return this.getValue(ctx, 0);
}
range_jel_mapping: boolean;
range(ctx: Context): Range {
return new Range(this.min(ctx) as any, this.max(ctx) as any);
}
getValue_jel_mapping: boolean;
getValue(ctx: Context, share: any): Numeric {
const share0 = Math.max(0, Math.min(1, TypeChecker.realNumber(share, 'share')));
let ri = 0;
for (let r of this.points) {
if (r.share == share0)
return r.value;
if (r.share > share0 || ri == this.points.length-1)
break;
ri++;
}
let li = ri - 1;
if (li < 0) {
if (this.points.length == 1)
return this.average != null ? this.average : this.points[0].value;
li++;
ri++;
}
const lp: DistributionPoint = this.points[li], rp: DistributionPoint = this.points[ri];
// P = x * (rp-lp) + lp
// P.value = x * (rp.value-lp.value) + lp.value
// P.share = x * (rp.share-lp.share) + lp.share
// x = (P.share-lp.share) / (rp.share-lp.share)
// P.value = (rp.value-lp.value) * (P.share - lp.share) / (rp.share-lp.share) + lp.value
const rpShare = Float.valueOf(rp.share), lpShare = Float.valueOf(lp.share);
return Runtime.op(ctx, '+', Runtime.op(ctx, '/', Runtime.op(ctx, '*', Runtime.op(ctx, '-', rp.value, lp.value) as any, Runtime.op(ctx, '-', Float.valueOf(share0), lpShare) as any) as any, Runtime.op(ctx, '-', rpShare, lpShare) as any) as any, lp.value) as any;
}
getShare_jel_mapping: boolean;
getShare(ctx: Context, value0: any): Promise<Float>|Float|null {
const value = TypeChecker.numeric(value0, 'value');
if (this.points.length == 1)
return Util.resolveValues((avg: JelBoolean, p0: JelBoolean)=>avg.toRealBoolean() ? 0.5 : p0.toRealBoolean() ? 1 : null, Runtime.op(ctx, '==', this.average, value), Runtime.op(ctx, '==', this.points[0].value, value));
return Util.resolveValues((lt: JelBoolean, gt: JelBoolean)=>{
if (lt.toRealBoolean() || gt.toRealBoolean())
return null;
let bestShare: Float|undefined = undefined;
let ri: number | undefined = undefined;
return Util.processPromiseList(this.points, r=>Runtime.op(ctx, '==', r.value, value), (p, r)=>{
if (p.toRealBoolean())
bestShare = r.share;
}, ()=>{
if (bestShare != undefined)
return bestShare;
return Util.processPromiseList(this.points, r=>Runtime.op(ctx, '>', r.value, value), (p, r, rstep)=>{
if (p.toRealBoolean() && ri == undefined)
ri = rstep;
}, ()=>{
ri = ri == undefined ? this.points.length-1 : ri;
let li = ri - 1;
if (li < 0) {
li++;
ri++;
}
const lp: DistributionPoint = this.points[li], rp: DistributionPoint = this.points[ri];
// linear interpolation
// P = x * (rp-lp) + lp
// P.value = x * (rp.value-lp.value) + lp.value
// P.share = x * (rp.share-lp.share) + lp.share
// x = (P.value-lp.value)/(rp.value-lp.value)
// P.share = (P.value-lp.value)*(rp.share-lp.share)/(rp.value-lp.value) + lp.share
const lpShare = Float.valueOf(lp.share), rpShare = Float.valueOf(rp.share);
return Float.toFloatWithPromise(Runtime.opWithPromises(ctx, '+', Runtime.opWithPromises(ctx, '/', Runtime.opWithPromises(ctx, '*', Runtime.opWithPromises(ctx, '-', value as any, lp.value as any), Runtime.op(ctx, '-', rpShare, lpShare)), Runtime.opWithPromises(ctx, '-', rp.value as any, lp.value as any)), lpShare));
});
});
}, Runtime.op(ctx, '<', value, this.min(ctx)), Runtime.op(ctx, '>', value, this.max(ctx)));
}
op(ctx: Context, operator: string, right: JelObject, isReversal: boolean = false): JelObject|Promise<JelObject> {
if (right instanceof Distribution) {
switch (operator) {
case '==':
case '===':
return Util.resolveValues((eq: JelBoolean)=>{
if (!eq.toRealBoolean())
return JelBoolean.FALSE;
if (this.points.length != right.points.length)
return JelBoolean.FALSE;
for (let i = 0; i < this.points.length; i++)
if (Float.toFloat(this.points[i].value) != Float.toFloat(right.points[i].value) || this.points[i].share !=right.points[i].share)
return JelBoolean.FALSE;
return JelBoolean.TRUE;
}, Runtime.op(ctx, '===', this.average, right.average));
case '>>':
case '>>=':
return Runtime.op(ctx, operator, this.min(ctx), right.max(ctx));
case '<<':
case '<<=':
return Runtime.op(ctx, operator, this.max(ctx), right.min(ctx));
case '>':
case '>=':
return Util.resolveValues((op: JelBoolean, inOp: JelBoolean)=> {
if (op.toRealBoolean())
return JelBoolean.TRUE;
if (inOp.toRealBoolean())
return JelBoolean.FALSE;
return Util.resolveValue(Runtime.op(ctx, operator, this.mean(ctx), right.mean(ctx)), (meanCmp: JelBoolean)=>JelBoolean.create(ctx, (meanCmp.state-0.5)/2+0.5));
}, Runtime.op(ctx, operator, this.min(ctx), right.max(ctx)), Runtime.op(ctx, INVERSE_OP[operator], this.min(ctx), right.max(ctx)));
case '<':
case '<=':
return Util.resolveValues((op: JelBoolean, inOp: JelBoolean)=> {
if (op.toRealBoolean())
return JelBoolean.TRUE;
if (inOp.toRealBoolean())
return JelBoolean.FALSE;
return Util.resolveValue(Runtime.op(ctx, operator, this.mean(ctx), right.mean(ctx)), (meanCmp: JelBoolean)=>JelBoolean.create(ctx, (meanCmp.state-0.5)/2+0.5));
}, Runtime.op(ctx, operator, this.max(ctx), right.min(ctx)), Runtime.op(ctx, INVERSE_OP[operator], this.max(ctx), right.min(ctx)));
}
}
else if (right instanceof Float || right instanceof Fraction || right instanceof ApproximateNumber || right instanceof UnitValue) {
switch (operator) {
case '==':
return JelBoolean.falsestWithPromises(ctx, Runtime.op(ctx, '>=', right, this.min(ctx)) as JelBoolean, Runtime.op(ctx, '<=', right, this.max(ctx)) as JelBoolean);
case '===':
return JelBoolean.falsestWithPromises(ctx, Runtime.op(ctx, '===', right, this.min(ctx)) as JelBoolean, Runtime.op(ctx, '===', right, this.max(ctx)) as JelBoolean);
case '>>':
case '>':
return Runtime.op(ctx, operator, this.min(ctx), right);
case '>=':
return Runtime.op(ctx, operator, this.max(ctx), right);
case '<':
case '<<':
return Runtime.op(ctx, operator, this.max(ctx), right);
case '<<=':
return Runtime.op(ctx, operator, this.min(ctx), right);
}
}
return super.op(ctx, operator, right, isReversal);
}
getSerializationProperties(): any[] {
return [this.points, this.average];
}
static create_jel_mapping = true;
static create(ctx: Context, ...args: any[]): Distribution {
return new Distribution(TypeChecker.optionalType('List', args[0], 'distributionPoints'),
TypeChecker.optionalNumeric(args[1], 'average'), TypeChecker.optionalNumeric(args[2], 'min'),
TypeChecker.optionalNumeric(args[3], 'max'), TypeChecker.optionalNumeric(args[4], 'mean'));
}
}
Distribution.prototype.average_jel_property = true;
Distribution.prototype.points_jel_property = true;
Distribution.prototype.mean_jel_mapping = true;
Distribution.prototype.min_jel_mapping = true;
Distribution.prototype.max_jel_mapping = true;
Distribution.prototype.range_jel_mapping = true;
Distribution.prototype.getValue_jel_mapping = true;
Distribution.prototype.getShare_jel_mapping = true;
Distribution.prototype.add_jel_mapping = true;
BaseTypeRegistry.register('Distribution', Distribution);
|
e7868c205b92185f916cd97872f1e96c5d3d8057
|
TypeScript
|
Evasionn/mars-rover
|
/src/classes/objects/Coordinate.ts
| 3.328125
| 3
|
export class Coordinate {
xCoordinate: number;
yCoordinate: number;
constructor(xCoordinate: number, yCoordinate: number) {
this.xCoordinate = xCoordinate;
this.yCoordinate = yCoordinate;
}
toString = (): string => `${this.xCoordinate} ${this.yCoordinate}`;
}
|
27bb4eb8cba811d3dcc440ad3b3ea8fdf875256f
|
TypeScript
|
MajoGrance/reservas
|
/front-end-angular/src/app/models/categoria-producto.ts
| 2.53125
| 3
|
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ServerResponse } from '../shared/interfaces';
import { CategoriaProductoService } from '../services/abm/categoria-producto.service';
const fb = new FormBuilder();
export class CategoriaProductoModel {
id: number;
nombre: string;
constructor(private service: CategoriaProductoService) { }
serialize(): object {
const obj: any = {};
if (this.id !== null && this.id !== undefined) {
obj.id = this.id;
}
if (this.nombre !== null && this.nombre !== undefined) {
obj.nombre = this.nombre;
}
return obj;
}
deserialize(input: object): this {
Object.assign(this, input);
return this;
}
async save(): Promise<ServerResponse> {
if (!this.id) {
return this.service.post(this);
} else {
return this.service.put(this);
}
}
getFormGroup(): FormGroup {
return fb.group({
id: this.id,
nombre: [this.nombre, Validators.required],
});
}
}
|
ee001ac34a05116298181463e005d4154c275b05
|
TypeScript
|
zengqinglei/creekdream-admin-ngzorro
|
/src/app/core/settings/models/app-info.ts
| 2.65625
| 3
|
/** 应用信息 */
export interface AppInfo {
[key: string]: any;
/** 应用名称 */
name?: string;
/** 描述 */
description?: string;
}
|
34b613256280ea1ef1a853f3688e49d7fbebe0f8
|
TypeScript
|
InternB/internb-backend
|
/src/modules/users/services/ShowUsersService.spec.ts
| 2.734375
| 3
|
import 'reflect-metadata';
import AppError from '@shared/errors/AppError';
import ShowUsersService from './ShowUsersService';
import FakeUsersRepository from '../repositories/fakes/FakeUsersRepository';
import User from '../infra/typeorm/entities/User';
let fakeUsersRepository: FakeUsersRepository;
let showUsersService: ShowUsersService;
describe('ShowUsers', () => {
beforeEach(() => {
fakeUsersRepository = new FakeUsersRepository();
showUsersService = new ShowUsersService(fakeUsersRepository);
});
it('should list all the users, minus the one requesting it', async () => {
const firstUser = new User();
Object.assign(firstUser, {
cpf: '90207045089',
email: 'johndoe@gmail.com',
fullname: 'John Doe',
password: '123456',
phone: '61999999999',
role: Math.floor(Math.random() * 4),
active: true,
});
const secondUser = new User();
Object.assign(secondUser, {
cpf: '60470393084',
email: 'johntre@gmail.com',
fullname: 'John Tré',
password: '123456',
phone: '61999999999',
role: Math.floor(Math.random() * 4),
active: true,
});
const admin = new User();
Object.assign(admin, {
cpf: '42498355022',
email: 'johnadmin@gmail.com',
fullname: 'John Admin',
password: '123456',
phone: '61999999999',
role: 0,
active: true,
});
const { id: firstId } = await fakeUsersRepository.create(firstUser);
const { id: secondId } = await fakeUsersRepository.create(secondUser);
const { id: admin_id } = await fakeUsersRepository.create(admin);
const users = await showUsersService.execute({
user_id: admin_id,
});
expect(users.length).toEqual(2);
expect(users).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: firstId,
}),
expect.objectContaining({
id: secondId,
}),
]),
);
});
it('should not list the users if the requester doest not exist', async () => {
await expect(
showUsersService.execute({
user_id: 'non-existing-user',
}),
).rejects.toBeInstanceOf(AppError);
});
it('should not list all the users if the requester is not an Admin', async () => {
const user = new User();
Object.assign(user, {
cpf: '42498355022',
email: 'johnadmin@gmail.com',
fullname: 'John Admin',
password: '123456',
phone: '61999999999',
role: Math.floor(Math.random() * 3 + 1),
active: true,
});
const { id: user_id } = await fakeUsersRepository.create(user);
await expect(
showUsersService.execute({
user_id,
}),
).rejects.toBeInstanceOf(AppError);
});
});
|
5699bfc2668ef820586fe6bed664d8dbd3b546a9
|
TypeScript
|
Assasindie/fortniteBot
|
/src/command/TriggerableCommand.ts
| 2.984375
| 3
|
import Command from "./Command";
import Trigger from "action/Trigger";
import NikkuCore from "core/NikkuCore";
import IHasAction from "action/IHasAction";
import IHasTrigger from "action/IHasTrigger";
import OnMessageState from "state/OnMessageState";
export default class TriggerableCommand extends Command implements IHasAction, IHasTrigger {
protected trigger: Trigger;
/**
* @classdesc Commands which are triggered without user directly calling it.
* @param accessLevel - The required access level to execute this command.
* @param action - The action to execute.
* @param trigger - The condition required to execute the action.
*/
public constructor(accessLevel: number) {
super(accessLevel, 0);
this.trigger = this.setCustomTrigger();
}
public async tryTrigger(msg: OnMessageState): Promise<boolean> {
return await this.trigger.execute(msg);
}
public setCustomTrigger(): Trigger {
return;
}
}
|
11f9a8978a23ee5505fd71b4feb08652cf4cd681
|
TypeScript
|
chrisguttandin/standardized-audio-context
|
/src/factories/analyser-node-constructor.ts
| 2.625
| 3
|
import { IAnalyserNode, IAnalyserOptions } from '../interfaces';
import { TAnalyserNodeConstructorFactory, TAudioNodeRenderer, TContext, TNativeAnalyserNode } from '../types';
const DEFAULT_OPTIONS = {
channelCount: 2,
channelCountMode: 'max',
channelInterpretation: 'speakers',
fftSize: 2048,
maxDecibels: -30,
minDecibels: -100,
smoothingTimeConstant: 0.8
} as const;
export const createAnalyserNodeConstructor: TAnalyserNodeConstructorFactory = (
audionNodeConstructor,
createAnalyserNodeRenderer,
createIndexSizeError,
createNativeAnalyserNode,
getNativeContext,
isNativeOfflineAudioContext
) => {
return class AnalyserNode<T extends TContext> extends audionNodeConstructor<T> implements IAnalyserNode<T> {
private _nativeAnalyserNode: TNativeAnalyserNode;
constructor(context: T, options?: Partial<IAnalyserOptions>) {
const nativeContext = getNativeContext(context);
const mergedOptions = { ...DEFAULT_OPTIONS, ...options };
const nativeAnalyserNode = createNativeAnalyserNode(nativeContext, mergedOptions);
const analyserNodeRenderer = <TAudioNodeRenderer<T, this>>(
(isNativeOfflineAudioContext(nativeContext) ? createAnalyserNodeRenderer() : null)
);
super(context, false, nativeAnalyserNode, analyserNodeRenderer);
this._nativeAnalyserNode = nativeAnalyserNode;
}
get fftSize(): number {
return this._nativeAnalyserNode.fftSize;
}
set fftSize(value) {
this._nativeAnalyserNode.fftSize = value;
}
get frequencyBinCount(): number {
return this._nativeAnalyserNode.frequencyBinCount;
}
get maxDecibels(): number {
return this._nativeAnalyserNode.maxDecibels;
}
set maxDecibels(value) {
// Bug #118: Safari does not throw an error if maxDecibels is not more than minDecibels.
const maxDecibels = this._nativeAnalyserNode.maxDecibels;
this._nativeAnalyserNode.maxDecibels = value;
if (!(value > this._nativeAnalyserNode.minDecibels)) {
this._nativeAnalyserNode.maxDecibels = maxDecibels;
throw createIndexSizeError();
}
}
get minDecibels(): number {
return this._nativeAnalyserNode.minDecibels;
}
set minDecibels(value) {
// Bug #118: Safari does not throw an error if maxDecibels is not more than minDecibels.
const minDecibels = this._nativeAnalyserNode.minDecibels;
this._nativeAnalyserNode.minDecibels = value;
if (!(this._nativeAnalyserNode.maxDecibels > value)) {
this._nativeAnalyserNode.minDecibels = minDecibels;
throw createIndexSizeError();
}
}
get smoothingTimeConstant(): number {
return this._nativeAnalyserNode.smoothingTimeConstant;
}
set smoothingTimeConstant(value) {
this._nativeAnalyserNode.smoothingTimeConstant = value;
}
public getByteFrequencyData(array: Uint8Array): void {
this._nativeAnalyserNode.getByteFrequencyData(array);
}
public getByteTimeDomainData(array: Uint8Array): void {
this._nativeAnalyserNode.getByteTimeDomainData(array);
}
public getFloatFrequencyData(array: Float32Array): void {
this._nativeAnalyserNode.getFloatFrequencyData(array);
}
public getFloatTimeDomainData(array: Float32Array): void {
this._nativeAnalyserNode.getFloatTimeDomainData(array);
}
};
};
|
654ddd9f7b3dd5c85d3d61d8c47b083089704ed7
|
TypeScript
|
shoNagai/react-virtuoso
|
/e2e/long-last-item.test.ts
| 2.546875
| 3
|
import { test, expect } from '@playwright/test'
test.describe('list with a long last item', () => {
test.beforeEach(async ({ page }) => {
await page.goto('http://localhost:1234/long-last-item')
await page.waitForSelector('#test-root')
await page.waitForTimeout(300)
})
test('starts from the last item', async ({ page }) => {
const paddingTop = await page.evaluate(() => {
const listContainer = document.querySelector('#test-root > div > div > div')
return (listContainer as HTMLElement).style.paddingTop
})
expect(paddingTop).toBe('7200px')
})
test('compensates on upwards scrolling correctly', async ({ page }) => {
await page.evaluate(() => {
const scroller = document.querySelector('#test-root > div')!
scroller.scrollBy({ top: -2 })
})
await page.waitForTimeout(200)
const scrollTop = await page.evaluate(() => {
return document.querySelector('#test-root > div')!.scrollTop
})
// items are 800 and 100px tall.
// scrolling up by 2px reveals an unexpectedly short item, so it should compensate
expect(scrollTop).toBe(7200 - 2 - (800 - 100))
})
})
|
9484ee39e49e4916a4d289762ccd6d7dde968a6e
|
TypeScript
|
ArkEcosystemArchive/platform-sdk
|
/packages/platform-sdk-http-axios/source/request.ts
| 2.703125
| 3
|
import { AbstractRequest, HttpResponse, RequestOptions, Response } from "@arkecosystem/platform-sdk-http";
import axios from "axios";
/**
* Implements HTTP communication through axios/axios.
*
* @see https://github.com/axios/axios
*
* @export
* @class Request
* @extends {Request}
*/
export class Request extends AbstractRequest {
/** {@inheritDoc Request.send} */
protected async send(method: string, url: string, data?: { query?: object; data?: any }): Promise<HttpResponse> {
const options: RequestOptions = {
...this._options,
};
options.method = method;
if (data && data.query) {
options.params = data.query;
}
if (data && data.data) {
if (this._bodyFormat === "json") {
options.json = data.data;
}
if (this._bodyFormat === "form_params") {
throw new Error("Method form_params is not supported.");
}
}
try {
const response = await axios[method.toLowerCase()](url.replace(/^\/+/g, ""), options);
return new Response({
body: JSON.stringify(response.data),
headers: response.headers,
statusCode: response.status,
});
} catch (error) {
return new Response(
{
body: JSON.stringify(error.response.data),
headers: error.response.headers,
statusCode: error.response.status,
},
error,
);
}
}
}
|
6a92f4b18aa891ffee5c4e0121e457de1a3c0f7a
|
TypeScript
|
zcorky/koa-cache-hits
|
/src/index.ts
| 2.765625
| 3
|
import { Context } from 'koa';
import LRU, { LRU as ILRU} from '@zcorky/lru';
import { undefined as isUndefined, string as isString } from '@zcorky/is';
export type DB<K, V> = {
get(key: K): V | Promise<V>;
set(key: K, value: V): void | Promise<void>
[key: string]: any;
} & ILRU<K, V>;
export interface Options<K, V> {
key?: keyof Context & string | ((ctx: Context) => string);
max?: number;
db?: DB<K, V>;
}
const creatCacheHits = <V = any>(options?: Options<string, V>) => {
const _options = options || {};
const getKey = isUndefined(_options.key)
? (ctx: Context) => ctx.originalUrl || ctx.url
: isString(_options.key)
? (ctx: Context) => ctx[_options.key as any] as string
: _options.key;
const max = _options.max || 100;
const db = _options.db || new LRU<string, V>(max);
return async function koaCacheHit (ctx: Context, next: () => Promise<any>) {
if (ctx.method !== 'GET') {
return next();
}
const key = getKey(ctx);
const cached = await db.get(key);
if (cached) {
const hits = db.hits();
ctx.set('X-Cache-Hits', `rate=${(hits.rate * 100).toFixed(2)}%`);
ctx.status = 200;
ctx.body = cached;
return;
}
await next();
const data = ctx.body;
await db.set(key, data);
};
}
export {
creatCacheHits,
};
export default creatCacheHits;
|
711c058420fffd30a4cb213fe324766e25057dff
|
TypeScript
|
flekschas/regl-scatterplot
|
/src/types.d.ts
| 2.65625
| 3
|
type Hex = string;
type Rgb = [number, number, number];
type Rgba = [number, number, number, number];
type Color = Hex | Rgb | Rgba;
type ColorMap = Color | Array<Color>;
type Category = 'category' | 'value1' | 'valueA' | 'valueZ' | 'z';
type Value = 'value' | 'value2' | 'valueB' | 'valueW' | 'w';
type DataEncoding = Category | Value;
type PointDataEncoding = DataEncoding | 'inherit' | 'segment';
type KeyAction = 'lasso' | 'rotate' | 'merge';
type KeyMap = Record<'alt' | 'cmd' | 'ctrl' | 'meta' | 'shift', KeyAction>;
type MouseMode = 'panZoom' | 'lasso' | 'rotate';
type ZWDataType = 'continuous' | 'categorical';
type Camera2D = any; // Needs to be typed at some point
type Scale = import('d3-scale').ScaleContinuousNumeric<number, number>;
type PointsObject = {
x: ArrayLike<number>;
y: ArrayLike<number>;
line?: ArrayLike<number>;
lineOrder?: ArrayLike<number>;
} & {
[Key in Category | Value]?: ArrayLike<number>;
};
export type Points = Array<Array<number>> | PointsObject;
type PointOptions = {
color: ColorMap;
colorActive: Color;
colorHover: Color;
outlineWidth: number;
size: number | Array<number>;
sizeSelected: number;
};
type PointConnectionOptions = {
color: ColorMap;
colorActive: Color;
colorHover: Color;
opacity: number | Array<number>;
opacityActive: number;
size: number | Array<number>;
sizeActive: number;
maxIntPointsPerSegment: number;
tolerance: number;
// Nullifiable
colorBy: null | PointDataEncoding;
opacityBy: null | PointDataEncoding;
sizeBy: null | PointDataEncoding;
};
type LassoOptions = {
color: Color;
lineWidth: number;
minDelay: number;
minDist: number;
clearEvent: 'lassoEnd' | 'deselect';
initiator: boolean;
initiatorParentElement: HTMLElement;
onLongPress: boolean;
longPressTime: number;
longPressAfterEffectTime: number;
longPressEffectDelay: number;
longPressRevertEffectTime: number;
};
type CameraOptions = {
target: [number, number];
distance: number;
rotation: number;
view: Float32Array;
};
type Rect = {
x: number;
y: number;
width: number;
height: number;
};
interface BaseOptions {
backgroundColor: Color;
deselectOnDblClick: boolean;
deselectOnEscape: boolean;
keyMap: KeyMap;
mouseMode: MouseMode;
showPointConnections: boolean;
showReticle: boolean;
reticleColor: Color;
opacity: number | Array<number>;
opacityByDensityFill: number;
opacityInactiveMax: number;
opacityInactiveScale: number;
height: 'auto' | number;
width: 'auto' | number;
gamma: number;
aspectRatio: number;
// Nullifiable
backgroundImage: null | import('regl').Texture2D | string;
colorBy: null | DataEncoding;
sizeBy: null | DataEncoding;
opacityBy: null | DataEncoding;
xScale: null | Scale;
yScale: null | Scale;
}
/**
* Helper type. Adds a prefix to keys of Options.
*
* type A = { a: number; b: string };
* WithPrefix<'myPrefix', A> === { myPrefixA: number, myPrefixB: string };
*/
type WithPrefix<
Name extends string,
Options extends Record<string, unknown>
> = {
[Key in keyof Options as `${Name}${Capitalize<string & Key>}`]: Options[Key];
};
export type Settable = BaseOptions &
WithPrefix<'point', PointOptions> &
WithPrefix<'pointConnection', PointConnectionOptions> &
WithPrefix<'lasso', LassoOptions> &
WithPrefix<'camera', CameraOptions>;
export type RendererOptions = {
regl: import('regl').Regl;
canvas: HTMLCanvasElement;
gamma: number;
};
export type Properties = {
renderer: ReturnType<typeof import('./renderer').createRenderer>;
canvas: HTMLCanvasElement;
regl: import('regl').Regl;
syncEvents: boolean;
version: string;
lassoInitiatorElement: HTMLElement;
camera: Camera2D;
performanceMode: boolean;
opacityByDensityDebounceTime: number;
points: [number, number][];
pointsInView: number[];
isDestroyed: boolean;
isPointsDrawn: boolean;
isPointsFiltered: boolean;
hoveredPoint: number;
filteredPoints: number[];
selectedPoints: number[];
} & Settable;
// Options for plot.{draw, select, hover}
export interface ScatterplotMethodOptions {
draw: Partial<{
transition: boolean;
transitionDuration: number;
transitionEasing: (t: number) => number;
preventFilterReset: boolean;
hover: number;
select: number | number[];
filter: number | number[];
zDataType: ZWDataType;
wDataType: ZWDataType;
}>;
hover: Partial<{
showReticleOnce: boolean;
preventEvent: boolean;
}>;
select: Partial<{
merge: boolean;
preventEvent: boolean;
}>;
filter: Partial<{
preventEvent: boolean;
}>;
preventEvent: Partial<{
preventEvent: boolean;
}>;
zoomToPoints: Partial<{
padding: number;
transition: boolean;
transitionDuration: number;
transitionEasing: (t: number) => number;
}>;
}
// PubSub definitions
type PubSubEvent<EventName extends string, Payload extends unknown> = {
[Key in EventName]: Payload;
};
type EventMap = PubSubEvent<
| 'init'
| 'destroy'
| 'backgroundImageReady'
| 'deselect'
| 'unfilter'
| 'lassoStart'
| 'transitionStart'
| 'pointConnectionsDraw',
undefined
> &
PubSubEvent<'lassoEnd' | 'lassoExtend', { coordinates: number[] }> &
PubSubEvent<'pointOver' | 'pointOut', number> &
PubSubEvent<'select' | 'focus', { points: Array<number> }> &
PubSubEvent<'points', { points: Array<Array<number>> }> &
PubSubEvent<'transitionEnd', import('regl').Regl> &
PubSubEvent<
'view' | 'draw',
Pick<Properties, 'camera' | 'xScale' | 'yScale'> & {
view: Properties['cameraView'];
}
>;
export interface PubSub {
subscribe<EventName extends keyof EventMap>(
eventName: EventName,
eventHandler: (payload: EventMap[EventName]) => void,
times?: number
): void;
unsubscribe(eventName: keyof EventMap): void;
publish<EventName extends keyof EventMap>(
eventName: EventName,
payload: EventMap[EventName]
): void;
}
|
67ba36740b947fa67b504d3b413d11dbd58eb7dc
|
TypeScript
|
yayudev/ctci-js
|
/chapter-01/07-rotateMatrix/main.ts
| 3.609375
| 4
|
type Matrix2D<T> = Array<Array<T>>;
/*
Note for blogpost:
- matrix[row][col]; // top
- matrix[col][size - row]; // right
- matrix[size - row][size - col]; // bottom
- matrix[size - col][row]; // left
*/
export function rotateMatrix(matrix: Matrix2D<number>): boolean {
if (matrix.length !== matrix[0].length) return false;
const size = matrix.length - 1;
for (let row = 0; row < matrix.length / 2; row++) {
const first = row;
const last = size - row;
for (let col = row; col < last; col++) {
const temp = matrix[row][col]; // Top -> Temp
matrix[row][col] = matrix[size - col][row]; // Left -> Top
matrix[size - col][row] = matrix[size - row][size - col]; // Bottom -> Left
matrix[size - row][size - col] = matrix[col][size - row]; // Right -> Bottom
matrix[col][size - row] = temp; // Top/Temp -> Right
}
}
return true;
}
|
8482b76d6accc182ae31805b26c90d66580a5e4b
|
TypeScript
|
brudil/kings-search
|
/frontend/src/utils.ts
| 2.59375
| 3
|
import { Result, SearchResultForm } from './types';
export function getForm(result: Result) {
if (result.link.startsWith('/organisation')) {
return SearchResultForm.StudentGroup;
}
if (result.link.startsWith('/news')) {
return SearchResultForm.News;
}
if (result.link.startsWith('/events')) {
return SearchResultForm.Event;
}
return SearchResultForm.Page;
}
export const formLangs = (form: SearchResultForm): string => {
switch (form) {
case SearchResultForm.News:
return 'News';
case SearchResultForm.Event:
return 'Event';
case SearchResultForm.StudentGroup:
return 'Student Group';
case SearchResultForm.Page:
return 'Page';
}
};
|
47deab720eb94a838f379f3f6de0f61886296848
|
TypeScript
|
mrsimpson/abaplint
|
/src/file.ts
| 3.125
| 3
|
import { Token } from "./tokens/";
import { Statement } from "./statements/";
import Issue from "./issue";
export default class File {
private tokens: Array<Token> = [];
private statements: Array<Statement> = [];
private issues: Array<Issue> = [];
private raw: string = "";
private filename: string = "";
constructor(filename: string, raw: string) {
this.raw = raw.replace(/\r/g, ""); // ignore all carriage returns
this.filename = filename;
}
// todo, something wrong here, refactor? the issues are also linked to
// a file object
public add(issue: Issue) {
this.issues.push(issue);
}
public get_count(): number {
return this.issues.length;
}
public get_issues(): Array<Issue> {
return this.issues;
}
public get_raw(): string {
return this.raw;
}
public get_raw_rows(): Array<string> {
return this.raw.split("\n");
}
public get_filename(): string {
return this.filename;
}
public set_tokens(tokens: Array<Token>) {
this.tokens = tokens;
}
public set_statements(statements: Array<Statement>) {
this.statements = statements;
}
public get_tokens(): Array<Token> {
return this.tokens;
}
public get_statements(): Array<Statement> {
return this.statements;
}
}
|
51fe7bfa41f8fe82ab3425f6457f302efce8032f
|
TypeScript
|
BlackspaceInc/typescript-microservices-template
|
/libs/logger/src/base.logger.ts
| 3.078125
| 3
|
import dateFormat from 'dateformat';
export enum LogLevel {
Off = 0,
Error,
Warning,
Info,
Debug,
Log,
}
export type LogOutput = (
source: string | undefined,
level: LogLevel,
message: string,
...data: any[]
) => void;
export abstract class BaseLogger {
static level = LogLevel.Log;
static outputs: LogOutput[] = [];
static showTimestamp = true;
static enableProductionMode(): void {
BaseLogger.level = LogLevel.Warning;
}
constructor(protected source?: string) {
if (source) this.source = source.toUpperCase();
}
log(message: string, ...data: any[]): void {
this.doLog(console.log, LogLevel.Log, message, data);
}
debug(message: string, ...data: any[]): void {
this.doLog(console.debug, LogLevel.Debug, message, data);
}
info(message: string, ...data: any[]): void {
this.doLog(console.info, LogLevel.Info, message, data);
}
warn(message: string, ...data: any[]): void {
this.doLog(console.warn, LogLevel.Warning, message, data);
}
error(message: string, ...data: any[]): void {
this.doLog(console.error, LogLevel.Error, message, data);
}
protected timestamp(): string {
return `[${dateFormat(new Date(), dateFormat.masks.isoDateTime)}]`;
}
private doLog(
func: (...args: any[]) => void,
level: LogLevel,
message: string,
data: any[]
) {
if (level > BaseLogger.level) {
return;
}
const log = this.build(level, message, data);
func.apply(console, log);
this.applyLoggerOutpus(level, message, data);
}
protected abstract build(
level: LogLevel,
message: string,
data: any[]
): any[];
private applyLoggerOutpus(level: LogLevel, message: string, data: any[]) {
BaseLogger.outputs.forEach((output) => {
output.apply(output, [this.source, level, message, ...data]);
});
}
}
|
bff3a10d92c14f702e0f2c677906a5b82765a56c
|
TypeScript
|
nicholasanthonys/distributed-database-demo
|
/server-jkt/models/RefreshToken.ts
| 2.546875
| 3
|
import {
Model,
Optional,
DataTypes,
} from "sequelize";
import sequelize from "database/sequelize";
// These are all the attributes in the RefreshToken model
export interface RefreshTokenAttributes {
id: Number;
refreshToken: String;
};
// Some attributes are optional in `RefreshToken.build` and `RefreshToken.create` calls
interface RefreshTokenCreationAttributes extends Optional<RefreshTokenAttributes, "id"> { };
class RefreshToken extends Model<RefreshTokenAttributes, RefreshTokenCreationAttributes>
implements RefreshTokenAttributes {
public id!: number; // Note that the `null assertion` `!` is required in strict mode.
public refreshToken!: string;
// timestamps!
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
}
RefreshToken.init(
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
},
refreshToken: {
type: DataTypes.STRING,
allowNull: false,
},
},
{
tableName: "refreshtokens",
sequelize, // passing the `sequelize` instance is required
underscored: true,
}
);
export default RefreshToken;
|
243cb1a1ee08a560331fa753d0ef81782f82459f
|
TypeScript
|
equilcode/evtstore
|
/src/domain.ts
| 2.578125
| 3
|
import {
Event,
Aggregate,
Provider,
Domain,
Command,
CmdBody,
CommandHandler,
StoreEvent,
BaseAggregate,
ExecutableAggregate,
DomainOptions,
} from './types'
import { EventHandler } from './event-handler'
import { toMeta } from './common'
export function createDomain<Evt extends Event, Agg extends Aggregate, Cmd extends Command>(
opts: DomainOptions<Evt, Agg>,
cmd: CommandHandler<Evt, Agg, Cmd>
): Domain<Evt, Agg, Cmd> {
function handler(bookmark: string) {
return new EventHandler({
bookmark,
provider: opts.provider,
stream: opts.stream,
})
}
return {
handler,
...wrapCmd(opts, cmd),
}
}
function wrapCmd<E extends Event, A extends Aggregate, C extends Command>(
opts: DomainOptions<E, A>,
cmd: CommandHandler<E, A, C>
) {
const keys = Object.keys(cmd) as Array<C['type']>
const command: CmdBody<C, A & BaseAggregate> = {} as any
const providerAsync = Promise.resolve(opts.provider)
if ('aggregate' in cmd) {
throw new Error(`Invalid command body: Command handler function cannot be named "aggregate"`)
}
const aggregateCache = new Map<
string,
{ aggregate: A & { aggregateId: string; version: number }; position: any }
>()
async function getAggregate(id: string) {
const provider = await providerAsync
const cached = opts.useCache && aggregateCache.get(id)
if (cached) {
const events = await getAllEventsFor<E>(provider, opts.stream, id, cached.position)
if (!events.length) {
return cached.aggregate
}
const lastEvent = events.slice(-1)[0]
const aggregate = events.reduce(toNextAggregate, cached.aggregate)
aggregateCache.set(id, { aggregate, position: lastEvent.position })
return aggregate
}
const events = await getAllEventsFor<E>(provider, opts.stream, id)
const next = { ...opts.aggregate(), aggregateId: id, version: 0 }
const aggregate = events.reduce(toNextAggregate, next)
if (events.length > 0) {
const lastEvent = events.slice(-1)[0]
aggregateCache.set(id, { aggregate, position: lastEvent.position })
}
return aggregate
}
async function getExecAggregate(id: string) {
const aggregate = await getAggregate(id)
const body: ExecutableAggregate<C, A> = {} as any
for (const type of keys) {
body[type] = async (cmdBody) => {
const cmdResult = await cmd[type]({ ...cmdBody, aggregateId: id, type }, aggregate)
const nextAggregate = await handleCommandResult(cmdResult, aggregate)
return { ...body, aggregate: nextAggregate }
}
}
return { ...body, aggregate }
}
// Prepare the command handlers that accept an aggregateId and a command body
for (const type of keys) {
command[type] = async (id, body) => {
const agg = await getAggregate(id)
const cmdResult = await cmd[type]({ ...body, aggregateId: id, type }, agg)
const nextAggregate = await handleCommandResult(cmdResult, agg)
return nextAggregate
}
}
async function handleCommandResult(cmdResult: E | E[] | void, aggregate: A & BaseAggregate) {
const id = aggregate.aggregateId
let nextAggregate = { ...aggregate }
if (cmdResult) {
const events = Array.isArray(cmdResult) ? cmdResult : [cmdResult]
const provider = await providerAsync
let nextVersion = aggregate.version + 1
const storeEvents = await provider.append(opts.stream, id, nextVersion, events)
const nextAggregate = storeEvents.reduce(toNextAggregate, aggregate)
return nextAggregate
}
return nextAggregate
}
function toNextAggregate(next: A & BaseAggregate, ev: StoreEvent<E>): A & BaseAggregate {
return {
...next,
...opts.fold(ev.event, next, toMeta(ev)),
version: ev.version,
aggregateId: ev.aggregateId,
}
}
return { command, getAggregate: getExecAggregate }
}
async function getAllEventsFor<E extends Event>(
provider: Provider<any>,
stream: string,
id: string,
from?: any
) {
const events: StoreEvent<E>[] = []
let current = from
do {
const stored = await provider.getEventsFor(stream, id, current)
events.push(...stored)
if (stored.length === 0) return events
if (!provider.limit) return events
if (stored.length < provider.limit) return events
const last = stored.slice(-1)[0]
current = last.position
} while (true)
}
|
f8d3c5c06a7feb66a57c4905078be3e8d24d302e
|
TypeScript
|
bcgov/jag-lcrb-carla-public
|
/cllc-public-app/ClientApp/src/app/services/feature-flag.service.ts
| 2.578125
| 3
|
import { Injectable } from "@angular/core";
import { FeatureFlagDataService } from "./feature-flag-data.service";
import { mergeMap } from "rxjs/operators";
import { of, Observable } from "rxjs";
@Injectable({
providedIn: "root"
})
export class FeatureFlagService {
private _featureFlags: Array<string> = []; // A list of all features turned ON
initialized = false;
constructor(private featureFlagDataService: FeatureFlagDataService) {
}
init() {
// need to get features here to make sure initialized will be set to true at some point
this.featureFlagDataService.getFeatureFlags()
.subscribe(featureFlags => {
this._featureFlags = featureFlags;
this.initialized = true;
return featureFlags;
});
}
getFeature(featureName: string): Observable<boolean> {
if (!featureName) {
return of(false);
}
// Find the feature flag that is turned on
if (this._featureFlags &&
!!this._featureFlags.find(feature => {
return feature === featureName;
})) {
return of(true);
} else {
return of(false);
}
}
featureOn(featureName: string): Observable<boolean> {
if (this.initialized) {
return this.getFeature(featureName);
} else {
return this.featureFlagDataService.getFeatureFlags()
.pipe(mergeMap(featureFlags => {
this._featureFlags = featureFlags;
this.initialized = true;
return this.getFeature(featureName);
}));
}
}
}
|
c4af5205ab087c31ba8d4a45a548cedd484d45a2
|
TypeScript
|
leiyangs/typescript-training
|
/Datatype/index.ts
| 4.4375
| 4
|
export {} // 可以防止变量名冲突(与其他文件变量名相同会报错)
/**
* 数据类型
*/
// 1.布尔类型(boolean) #
let married: boolean = false;
// 2.数字类型(number) #
let num: number = 10;
// 3.字符串类型(string) #
let str: string = 'yang';
// 4.数组类型(array)
let arr1: number[] = [1, 2, 3];
let arr2: Array<string> = ['1', '2', '3'];
let arr3: object[] = [{a:1,b:2,c:3}];
// 5.元组类型(tuple) #
// 在 TypeScript 的基础类型中,元组( Tuple )表示一个已知数量和类型的数组, 每一项可以是不同的类型,有长度预定,数组没有。
let tuple: [number, string] = [10, 'yang'];
tuple[0].toFixed(2);
tuple[1].length;
// 6.枚举类型(enum) #
// 事先考虑某一个变量的所有的可能的值,尽量用自然语言中的单词表示它的每一个值
// - 普通枚举 #
enum Gender {
girl,
boy
}
let boy: Gender = Gender.boy;
console.log('我是'+boy)
enum Week {
monday = 1,
tuesday = 2
}
console.log(`今天是星期${Week.monday}`)
// - 常数枚举 #
// 常数枚举与普通枚举的区别是,它会在编译阶段被删除,并且不能包含计算成员。
// 假如包含了计算成员,则会在编译阶段报错
const enum Color {
RED,
YELLOW,
BLUE
}
console.log(Color.RED, Color.YELLOW, Color.BLUE); // 编译结果 console.log(0 /* RED */, 1 /* YELLOW */, 2 /* BLUE */);
// console.log(Color) // 会报错 "const" 枚举仅可在属性、索引访问表达式、导入声明的右侧、导出分配或类型查询中使用。
// 7.任意类型(any) #
/**
* 1.any就是可以赋值给任意类型
2.第三方库没有提供类型文件时可以使用any
3.类型转换遇到困难时
4.数据结构太复杂难以定义
*/
let root:(HTMLElement|null) = document.getElementById("root"); // 联合类型
root!.style.color = "blue"; // 加!忽略警告,标识root肯定有值
let root1: any = document.getElementById("root"); // 可以赋值为任何类型
root1.style.background = "red";
root1 = '1';
root1 = 10;
// 8.null 和 undefined #
/**
* 1.null 和 undefined 是其它类型的子类型,可以赋值给其它类型,如数字类型,此时,赋值后的类型会变成 null 或 undefined
* 2.strictNullChecks 参数用于新的严格空检查模式,在严格空检查模式下, null 和 undefined 值都不属于任何一个类型,它们只能赋值给自己这种类型或者 any, 在tscconfig中配置
*/
let sum: number;
sum = 2;
// sum = undefined;
// sum = null;
let number: number|undefined|null;
number = undefined;
// 9.void 类型
/**
* void 表示没有任何类型 当一个函数没有返回值时,TS 会认为它的返回值是 void 类型。
*/
function javascrpit(name: string): void {
console.log(name)
// return name; // 有返回值会报错
return ; // 可以return空 undefined null
}
javascrpit('yang')
// never类型 never是其它类型(null undefined)的子类型,代表不会出现的值
function infiniteLoop():never {
while(true) {
}
}
function fn(x:number | string) {
if(typeof x == 'number') {
}else if(typeof x == 'string') {
}else {
console.log('never')
}
}
// 10.类型推论
/**
* 是指编程语言中能够自动推导出值的类型的能力,它是一些强静态类型语言中出现的特性
定义时未赋值就会推论成any类型
如果定义的时候就赋值就能利用到类型推论
*/
let username;
username = 10;
username = 'yang';
username = null;
// 11.包装对象(Wrapper Object)
/**
* JavaScript 的类型分为两种:原始数据类型(Primitive data types)和对象类型(Object types)。
所有的原始数据类型都没有属性(property)
原始数据类型(布尔值/数值/字符串/null/undefined/Symbol)
*/
let name = 'yang';
console.log(name.toUpperCase());
console.log((new String('yang')).toUpperCase());
// 当调用基本数据类型方法的时候,JavaScript 会在原始数据类型和对象类型之间做一个迅速的强制性切换
// let isOK1: boolean = true; // 编译通过
// let isOK2: boolean = Boolean(1) // 编译通过
// let isOK3: boolean = new Boolean(1); // 编译失败 期望的 isOK 是一个原始数据类型
// 11.联合类型
/**
* 联合类型(Union Types)表示取值可以为多种类型中的一种
未赋值时联合类型上只能访问两个类型共有的属性和方法
*/
let a: string | number;
a = 1;
a = '1'
// 12.类型断言
/**
* 类型断言可以将一个联合类型的变量,指定为一个更加具体的类型
不能将联合类型断言为不存在的类型
*/
let name1: string | number;
name1 = 'asdsd';
console.log((name1 as string).length);
name1 = 10;
console.log((name1 as number).toFixed(2));
// console.log((name1 as boolean));
// 13.字面量类型
/**
* 可以把字符串、数字、布尔值字面量组成一个联合类型
*/
type ZType = 1 | 'on' | true;
let t1: ZType = 1;
let t2: ZType = 'on'
// 14.字符串字面量 vs 联合类型
/**
* 字符串字面量类型用来约束取值只能是某几个字符串中的一个, 联合类型(Union Types)表示取值可以为多种类型中的一种
* 字符串字面量 限定了使用该字面量的地方仅接受特定的值,联合类型 对于值并没有限定,仅仅限定值的类型需要保持一致
*/
|
60a4575ea0df862f30702a813146fb30b0733031
|
TypeScript
|
yuya373/manga-viewer
|
/src/actions/fileDialog.ts
| 2.5625
| 3
|
import { Action } from 'redux';
import { Types } from './types';
import { ThunkAction } from '.';
import { File, isFile } from '../types';
export interface FileDialogOpenAction extends Action {
type: Types.FILE_DIALOG_OPEN;
payload: {
name: string;
path: string;
files: Array<File>;
};
}
const fileDialogOpen = ({
path,
name,
files,
}: {
path: string;
name: string;
files: Array<File>;
}): FileDialogOpenAction => ({
type: Types.FILE_DIALOG_OPEN,
payload: {
name,
path,
files,
},
});
export function openFileDialog({
path,
name,
fromFavorite,
fromHitomi,
}: {
path: string;
name: string;
fromFavorite?: boolean;
fromHitomi?: boolean;
}): ThunkAction<void> {
return (dispatch, getState) => {
let files: Array<File>;
if (fromFavorite) {
files = Object.values(getState().favorites.byPath).filter(isFile);
} else if (fromHitomi) {
files = Object.values(getState().hitomi.fileByUrl);
} else {
const directory = getState().directories.byPath[path];
if (directory == null) return;
files = directory.entries.filter(isFile);
}
dispatch(
fileDialogOpen({
path,
name,
files,
})
);
};
}
export interface FileDialogCloseAction extends Action {
type: Types.FILE_DIALOG_CLOSE;
}
export const closeFileDialog = (): FileDialogCloseAction => ({
type: Types.FILE_DIALOG_CLOSE,
});
export interface FileDialogHideAppBarAction extends Action {
type: Types.FILE_DIALOG_HIDE_APP_BAR;
}
export const fileDialogHideAppBar = (): ThunkAction<void> => {
return (dispatch, getState) => {
if (getState().fileDialog.isAppBarHidden) return;
requestAnimationFrame(() => {
dispatch({
type: Types.FILE_DIALOG_HIDE_APP_BAR,
});
});
};
};
export interface FileDialogDisplayAppBarAction extends Action {
type: Types.FILE_DIALOG_DISPLAY_APP_BAR;
}
export const fileDialogDisplayAppBar = (): ThunkAction<void> => {
return (dispatch, getState) => {
if (!getState().fileDialog.isAppBarHidden) return;
requestAnimationFrame(() => {
dispatch({
type: Types.FILE_DIALOG_DISPLAY_APP_BAR,
});
});
};
};
export interface FileDialogFileChangedAction extends Action {
type: Types.FILE_DIALOG_FILE_CHANGED;
payload: {
path: string;
name: string;
};
}
export type FileDialogActions =
| FileDialogFileChangedAction
| FileDialogOpenAction
| FileDialogCloseAction
| FileDialogHideAppBarAction
| FileDialogDisplayAppBarAction;
|
d5ff4375b66052082b349bca07f4000552973cb0
|
TypeScript
|
mitto121/TypeScript-Assignments
|
/Desktop/106232_mitto/TypeScript Assignment/19_Arithmetic/Script/script.ts
| 3.75
| 4
|
class Airthmetic{
add = function (number1: number, number2:number) : number{
return (number1 + number2);
}
}
class Adder extends Airthmetic{
constructor(){super();}
}
function CalculateValues(){
let num1 =Number((document.getElementById("txtFirstNum") as HTMLInputElement).value);
let num2 =Number((document.getElementById("txtSecondNum") as HTMLInputElement).value);
document.getElementById("divResult").innerHTML = "";
let addValue = new Adder();
document.getElementById("divResult").innerHTML = "Sum of "+num1+" and "+num2+" = "+ addValue.add(num1, num2).toString();
}
|
91fb306c90a12d9632b0ed559f5c01b3525f4bad
|
TypeScript
|
Datawheel/olap-client
|
/src/interfaces/descriptors.ts
| 2.546875
| 3
|
/**
* These are objects constructed by the user to use as reference to an object
* in the Cube schema.
*/
import { Calculation, Comparison, Direction, TimePrecision, TimeValuePoint } from "./enums";
export interface CalculationGrowthDescriptor {
kind: "growth";
category: LevelDescriptor;
value: string;
}
export interface CalculationRCADescriptor {
kind: "rca";
location: LevelDescriptor;
category: LevelDescriptor;
value: string;
}
export interface CalculationTopkDescriptor {
kind: "topk";
amount: number;
category: LevelDescriptor;
value: string | Calculation;
order: string;
}
export type CalculationDescriptor =
| CalculationGrowthDescriptor
| CalculationRCADescriptor
| CalculationTopkDescriptor;
export interface CutDescriptor extends LevelDescriptor {
members: string[] | number[];
exclusive?: boolean;
for_match?: boolean;
}
export interface FilterDescriptor {
server?: string;
cube?: string;
measure: string;
constraint: [Comparison, number];
joint?: "and" | "or";
constraint2?: [Comparison, number];
}
export interface LevelDescriptor {
server?: string;
cube?: string;
dimension?: string;
hierarchy?: string;
level: string;
}
export interface PropertyDescriptor {
server?: string;
cube?: string;
dimension?: string;
hierarchy?: string;
level?: string;
property: string;
}
export interface QueryDescriptor {
server?: string;
cube?: string;
calculations: CalculationDescriptor[];
captions: PropertyDescriptor[];
cuts: CutDescriptor[];
drilldowns: LevelDescriptor[];
filters: FilterDescriptor[];
format: string;
locale: string;
measures: string[];
options: Record<string, boolean | undefined>;
page_limit: number;
page_offset: number;
properties: PropertyDescriptor[];
sort_direction: Direction | string | undefined;
sort_property: PropertyDescriptor | string | undefined;
time: [TimePrecision | string, TimeValuePoint | string] | undefined;
}
|
a9706da777a9ee00c1a5256fbf3690f1af02f081
|
TypeScript
|
ChimeraX/common-web
|
/src/util/cookies.ts
| 2.59375
| 3
|
export interface Cookies {
[key: string]: string;
}
export function getCookies(): Cookies {
return document.cookie
.split(';')
.map((x) => x.trim().split('='))
.reduce((acc: Cookies, value: string[]) => {
acc[value[0]] = value[1];
return acc;
}, {});
}
|
ff40a12345a33c9b856d4d0ed0db6c6b0f772e1e
|
TypeScript
|
Just-Hosam/WannaBitly
|
/backend/db/queries/click-queries.ts
| 2.75
| 3
|
const db = require('../../lib/db.js');
interface Click {
id: number;
url_id: number;
timestamp: number;
}
const getClicks = (urlId: number): Promise<Click[]> => {
const query = `
SELECT *
FROM clicks
WHERE url_id = $1
ORDER BY id DESC;`;
const values = [urlId];
return db
.query(query, values)
.then(({ rows }: { rows: Click[] }) => rows)
.catch((err: Error) => console.log(`Error at clicks queries 'getClicks'`, err));
};
const getClick = (urlId: number, clickId: number): Promise<Click> => {
const query = `
SELECT *
FROM clicks
WHERE url_id = $1
AND id = $2;`;
const values = [urlId, clickId];
return db
.query(query, values)
.then(({ rows }: { rows: Click[] }) => rows[0])
.catch((err: Error) => console.log(`Error at clicks queries 'getClick'`, err));
};
const addClick = (urlId: number, clickTimestamp: number): Promise<Click> => {
const query = `
INSERT INTO clicks (url_id, timestamp)
VALUES ($1, $2)
RETURNING *;`;
const values = [urlId, clickTimestamp];
return db
.query(query, values)
.then(({ rows }: { rows: Click[] }) => rows[0])
.catch((err: Error) => console.log(`Error at clicks queries 'addClick'`, err));
};
export { getClicks, getClick, addClick };
|
4b4dd8ce6235447955bc7d16a509c178b320f102
|
TypeScript
|
AdamVig/personal-metrics
|
/src/environment/environment.provider.ts
| 2.953125
| 3
|
import { Injectable } from '@nestjs/common'
import { LogFactory, Logger } from '../logger/log-factory'
/**
* Environment variables.
* @description Must match `.env.example`.
*/
export interface Environment {
/** Environment the application is running in. */
NODE_ENV: string
/** Port to run the application on. */
APP_PORT: string
/** Port to run Grafana on. */
GRAFANA_PORT: string
/**
* Host to connect to the database on.
* @description When running with `npm start`, this should be set to `'localhost'`. When running in a Docker
* container, this should be set to the name of the database's container (`'postgres'` if you are using the
* `docker-compose.yml` in this repository).
*/
DB_HOST: string
/**
* Port to run the database on.
* @description Will also be used to connect to the database when running with `npm start`, but will be ignored when
* running in a Docker container.
*/
DB_PORT: string
/** Username for read/write database user. Will also be used as name of database. */
DB_USER: string
/** Password for read/write database user. */
DB_PASSWORD: string
/** Username for read-only database user. */
DB_USER_READONLY: string
/** Password for read-only database user. */
DB_PASSWORD_READONLY: string
/** API token for [Pinboard](https://pinboard.in/). */
TOKEN_PINBOARD: string
}
/** Provider for environment variables used by the application. */
@Injectable()
export class EnvironmentProvider {
private readonly log: Logger
private readonly capturedVariables = new Set<keyof Environment>([
'NODE_ENV',
'APP_PORT',
'GRAFANA_PORT',
'DB_HOST',
'DB_PORT',
'DB_USER',
'DB_PASSWORD',
'DB_USER_READONLY',
'DB_PASSWORD_READONLY',
'TOKEN_PINBOARD',
])
private readonly variables = new Map<keyof Environment, string>()
public constructor(log: LogFactory) {
this.log = log.child('Environment')
this.log.trace(process.env, 'environment variables')
this.capture()
this.log.debug(
this.redact(
(EnvironmentProvider.strMapToObj(this.variables) as unknown) as Environment,
),
'captured variables',
)
}
/**
* Captures environment variables by assigning them as properties on this object.
*/
private capture(): void {
for (const name of this.capturedVariables) {
if (process.env[name] !== undefined && process.env[name] !== '') {
this.variables.set(name, process.env[name] as string)
}
}
}
/**
* Validates that all captured variables are set. Throws an error if any captured variables are not set.
*/
public validate(): void {
for (const name of this.capturedVariables) {
if (!this.variables.has(name)) {
throw new Error(`variable "${name}" is not set`)
}
}
}
/**
* Gets an environment variable by name. Throws an error if the variable is not set.
* @param name Name of an environment variable.
* @returns Value of an environment variable.
*/
public get(name: keyof Environment): string {
if (this.variables.has(name)) {
return this.variables.get(name) as string
}
throw new Error(`variable "${name}" is not set`)
}
/** Redact sensitive variables in environment for logging purposes. */
private redact(variables: Environment): Environment {
const redactedVariables = { ...variables }
const toRedact = Array.from(this.capturedVariables).filter(
(varName): boolean => varName.includes('TOKEN') || varName.includes('PASSWORD'),
)
for (const varName of toRedact) {
if (varName in variables) {
redactedVariables[varName] = '[REDACTED]'
}
}
return redactedVariables
}
/**
* Convert string Maps to and from objects.
* @see {@link http://2ality.com/2015/08/es6-map-json.html}
*/
private static strMapToObj(strMap: Map<string, string>): Record<string, string> {
const obj = Object.create(null)
for (const [k, v] of strMap) {
obj[k] = v
}
return obj
}
}
|
b7cff1ab8a8c366fb4a0fda935987bba6f126ec7
|
TypeScript
|
mrv1k/separating-the-books
|
/src/controllers/authors.ts
| 2.671875
| 3
|
import { NextFunction, Request, Response } from "express";
import AuthorModel, { Author } from "@/models/author";
import { REST } from "@/types";
import { createLocationUrl } from "@/utils/express-helpers";
class AuthorsController implements REST {
async getMany(req: Request, res: Response) {
const authors = await AuthorModel.find().lean();
return res.json(authors);
}
async getOne(req: Request, res: Response, next: NextFunction) {
const author = await AuthorModel.findById(res.locals._id).lean().exec();
if (author === null) return next();
return res.json(author);
}
async postOne(req: Request, res: Response, next: NextFunction) {
const payload: Author = {
first_name: req.body.first_name,
last_name: req.body.last_name,
};
await AuthorModel.validate(payload);
// can't use .exists() - need object id for url, use equivalent
const existingAuthor = await AuthorModel.findOne(payload, { _id: 1 })
.lean()
.exec();
if (existingAuthor) {
const location = createLocationUrl(req, existingAuthor._id);
return res.location(location.absolute).status(409).json({
error: "Resource already exists",
location: location.relative,
});
}
const author = await new AuthorModel(payload).save({
validateBeforeSave: false, // validated above
});
res.location(createLocationUrl(req, author._id).absolute).json(author);
}
async putOne(req: Request, res: Response, next: NextFunction) {
const _id = res.locals._id;
const payload: Author = {
first_name: req.body.first_name,
last_name: req.body.last_name,
};
console.log(payload);
const author = await AuthorModel.findOne({
$or: [{ _id: _id }, payload],
});
if (author === null) {
const newAuthor = await AuthorModel.create(payload);
return res.status(201).json(newAuthor);
}
// found by id
if (author.id === _id) {
author.first_name = payload.first_name;
author.last_name = payload.last_name;
await author.save();
return res.json(author);
}
// found not by id, redirect
const { absolute } = createLocationUrl(req, author.id);
console.log("found by id, redirect");
return res.location(absolute).status(303).end();
}
async patchOne(req: Request, res: Response, next: NextFunction) {
const author = await AuthorModel.findById(res.locals._id);
if (author === null) return res.status(404).end();
const { first_name, last_name } = req.body;
if (first_name === author.first_name && last_name === author.last_name) {
// already up to date
return res.json(author);
}
if (first_name) author.first_name = first_name;
if (last_name) author.last_name = last_name;
author.save();
res.json(author);
}
async deleteOne(req: Request, res: Response, next: NextFunction) {
const author = await AuthorModel.findByIdAndDelete(res.locals._id);
if (author === null) {
return res.status(204).json();
}
res.json(author);
}
}
export default new AuthorsController();
|
d0b0f8a1ccbcd42c244923edf32dadd490aea698
|
TypeScript
|
karavaan/random-walker
|
/src/components/walker/helpers/edge.ts
| 3.296875
| 3
|
export interface Edges {
top: boolean;
left: boolean;
right: boolean;
bottom: boolean;
}
export const isEdge = (pos: number, size: number): Edges => {
return {
top: pos < size,
left: pos % size === 0,
right: (pos + 1) % size === 0,
bottom: pos >= size * (size - 1)
}
}
|
586029eeb82a36744059d75c45267fdfffe48d85
|
TypeScript
|
turboka4/RedOwlTask
|
/RedOwl.UI/ClientApp/app/components/addproduct/addproduct.component.ts
| 2.609375
| 3
|
import { Component, Inject } from '@angular/core';
import { Http } from '@angular/http';
import { NgForm } from '@angular/forms';
@Component({
selector: 'addproduct',
templateUrl: './addproduct.component.html'
})
export class AddProductComponent {
private http: Http;
private baseUrl: string;
public responseStatus: string | null;
constructor(http: Http, @Inject('BASE_URL') baseUrl: string) {
this.http = http;
this.baseUrl = baseUrl;
}
onSubmit(form: NgForm) {
let product: Product =
{
name: form.value.name,
price: form.value.price
};
this.http.post(this.baseUrl + 'api/product/addproduct', product).subscribe(
result => this.responseStatus = result.statusText,
error => this.responseStatus = error.statusText);
}
}
interface Product {
name: string;
price: number;
}
|
dc85203b6f631d89fc6dc2a75aa1acab5df810cf
|
TypeScript
|
hakudev/nitro-emu
|
/src/database/daos/UserOutfitDao.ts
| 2.65625
| 3
|
import { Application } from '../../app';
import { UserGender } from '../../core';
import { UserOutfitEntity } from '../entities/UserOutfitEntity';
export class UserOutfitDao
{
public static async loadUserOutfits(userId: number): Promise<UserOutfitEntity[]>
{
if(!userId) return null;
const results = await Application.instance.core.database.entityManager.find(UserOutfitEntity, { where: { userId } });
if(!results || !results.length) return null;
return results;
}
public static async addOutfit(userId: number, figure: string, gender: string, slotNumber: number): Promise<UserOutfitEntity>
{
if(!userId || !figure || !gender || (slotNumber <= 0 || slotNumber > 6)) return;
const entity = new UserOutfitEntity();
entity.userId = userId;
entity.figure = figure;
entity.gender = gender === UserGender.MALE ? UserGender.MALE : UserGender.FEMALE;
entity.slotNumber = slotNumber;
await this.removeOutfit(userId, slotNumber);
await Application.instance.core.database.entityManager.save(entity);
return entity;
}
public static async removeOutfit(userId: number, slotNumber: number): Promise<void>
{
if(!userId || !slotNumber) return;
await Application.instance.core.database.entityManager.delete(UserOutfitEntity, { userId, slotNumber });
}
}
|
8bc38c9df74bbd9ec0020e4c1bd301ece03bc65f
|
TypeScript
|
findawayer/chess-player
|
/app/features/chess/hooks/useChessGuides.ts
| 3.03125
| 3
|
import update from 'immutability-helper';
import { useCallback, useState } from 'react';
import { stringifySquare } from '~app/features/chess/utils';
import type {
ChessGuides,
ChessLegalMove,
ChessSquare,
} from '~app/features/chess/types';
/**
* Reducer hook to manipulate chess square highlights collectively.
*
* @returns Array of:
* - activeSquare: Square that the user is interacting.
* - hoveredSquare: Square where the user's cursor is on.
* - legalSquares: Squares where the user can move the piece to.
* - setActive: Set or unset the active square.
* - setHover: Set or unset the hovered square.
*/
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const useChessGuides = () => {
const [{ active, hover, legal }, setGuides] = useState<ChessGuides>({
active: null,
hover: null,
legal: [],
});
/**
* Highlight the square that user is interacting,
* and squares that the player can move the active piece to.
*/
const setActive = useCallback(
(activeSquare: ChessSquare | null, legalMoves?: ChessLegalMove[]) => {
setGuides(previousGuides =>
update(previousGuides, {
$merge: {
active: activeSquare ? stringifySquare(activeSquare) : null,
legal: legalMoves ?? [],
hover: null,
},
}),
);
},
[],
);
/** Highlight the square that the user is moving the cursor onto. */
const setHover = useCallback((square: ChessSquare | null) => {
setGuides(previousGuides =>
update(previousGuides, {
$merge: { hover: square ? stringifySquare(square) : null },
}),
);
}, []);
return {
active,
hover,
legal,
setActive,
setHover,
};
};
|
bebf62af9344e4aaaae1e203834339643e7c7b50
|
TypeScript
|
Zweer/oroscopo-api
|
/lambda/utils/lambda/decorators.ts
| 2.609375
| 3
|
import 'reflect-metadata';
import { parseBody } from './request';
import { createSuccessResponse, createErrorResponse } from './response';
import { APIGatewayProxyEvent, SNSEvent } from 'aws-lambda';
type paramKey = string | Symbol | number;
type paramMetadata = {
paramKey: paramKey;
paramIndex: number;
};
const paramMetadataKey = Symbol('param');
export function param(paramKey: paramKey): ParameterDecorator {
return createRouteParamDecorator(paramMetadataKey)(paramKey);
}
const bodyMetadataKey = Symbol('body');
const bodyEntireKey = Symbol('entire-body');
export function body(paramKey: paramKey = bodyEntireKey): ParameterDecorator {
return createRouteParamDecorator(bodyMetadataKey)(paramKey);
}
const snsMessageMetadataKey = Symbol('sns');
export function sns(): ParameterDecorator {
return createRouteParamDecorator(snsMessageMetadataKey)(0);
}
const createRouteParamDecorator = (paramType: Symbol) => (paramKey: paramKey): ParameterDecorator => (target: Object, propertyKey: string | symbol, paramIndex: number): void => {
const existingParamMetadata: paramMetadata[] = Reflect.getOwnMetadata(paramType, target, propertyKey) || [];
existingParamMetadata.push({ paramKey, paramIndex });
Reflect.defineMetadata(paramType, existingParamMetadata, target, propertyKey);
};
export function endpoint(target: any, propertyName: string, descriptor: TypedPropertyDescriptor<Function>): void {
const method = descriptor.value;
descriptor.value = async function (...args) {
const event = args[0] as APIGatewayProxyEvent;
const paramMetadata: paramMetadata[] = Reflect.getOwnMetadata(paramMetadataKey, target, propertyName) || [];
paramMetadata.forEach(({ paramKey, paramIndex }) => {
args[paramIndex] = event.pathParameters && event.pathParameters[paramKey as string];
});
const bodyMetadata = Reflect.getOwnMetadata(bodyMetadataKey, target, propertyName) || [];
bodyMetadata.forEach(({ paramKey, paramIndex }) => {
const body = parseBody(event);
args[paramIndex] = body && paramKey === bodyEntireKey ? body : body[paramKey];
});
const snsMessageMetadata = Reflect.getOwnMetadata(snsMessageMetadataKey, target, propertyName) || [];
snsMessageMetadata.forEach(({ paramKey, paramIndex }) => {
let message;
try {
message = (event as unknown as SNSEvent).Records[paramKey as number].Sns.Message;
} catch (error) {}
try {
message = typeof message === 'string' ? JSON.parse(message) : message;
message = {
text: '',
...message,
};
} catch (error) {
message = { text: message };
}
args[paramIndex] = message;
});
try {
const result = await method.apply(this, args);
return createSuccessResponse(result);
} catch (error) {
return createErrorResponse(error);
}
};
}
|
91ba3f81cd01f12935a4f06ddf7a36a91145e048
|
TypeScript
|
pip-services3-node/pip-services3-commons-node
|
/test/run/Parameters.test.ts
| 2.84375
| 3
|
let assert = require('chai').assert;
import { TestClass } from './TestClass';
import { ConfigParams } from '../../src/config/ConfigParams';
import { Parameters } from '../../src/run/Parameters';
suite('Parameters', ()=> {
test('Defaults', () => {
var result = Parameters.fromTuples(
"value1", 123,
"value2", 234
);
var defaults = Parameters.fromTuples(
"value2", 432,
"value3", 345
);
result = result.setDefaults(defaults, false);
assert.equal(3, result.length());
assert.equal(123, result["value1"]);
assert.equal(234, result["value2"]);
assert.equal(345, result["value3"]);
});
test('Override Recursive', () => {
var result = Parameters.fromJson(
"{ \"value1\": 123, \"value2\": { \"value21\": 111, \"value22\": 222 } }"
);
var defaults = Parameters.fromJson(
"{ \"value2\": { \"value22\": 777, \"value23\": 333 }, \"value3\": 345 }"
);
result = result.setDefaults(defaults, true);
assert.equal(3, result.length());
assert.equal(123, result.get("value1"));
assert.equal(345, result.get("value3"));
var deepResult = result.getAsMap("value2");
assert.equal(3, deepResult.length());
assert.equal(111, deepResult.getAsInteger("value21"));
assert.equal(222, deepResult.getAsInteger("value22"));
assert.equal(333, deepResult.getAsInteger("value23"));
});
test('Override With Nulls', () => {
var result = Parameters.fromJson(
"{ \"value1\": 123, \"value2\": 234 }"
);
result = result.override(null, true);
assert.equal(2, result.length());
assert.equal(123, result.get("value1"));
assert.equal(234, result.get("value2"));
});
test('Assign To', () => {
var value = new TestClass(null, null);
var newValues = Parameters.fromJson(
"{ \"value1\": 123, \"value2\": \"ABC\", \"value3\": 456 }"
);
newValues.assignTo(value);
assert.isNotNull(value.value1);
assert.equal(123, value.value1);
assert.isNotNull(value.value2);
assert.equal("ABC", value.value2);
});
test('Get', () => {
var config = Parameters.fromJson(
"{ \"value1\": 123, \"value2\": { \"value21\": 111, \"value22\": 222 } }"
);
var value = config.get("");
assert.isNull(value);
value = config.getAsInteger("value1");
assert.isNotNull(value);
assert.equal(123, value);
value = config.get("value2");
assert.isNotNull(value);
var boolVal = config.containsKey("value3");
assert.isFalse(boolVal);
value = config.getAsInteger("value2.value21");
assert.isNotNull(value);
assert.equal(111, value);
boolVal = config.containsKey("value2.value31");
assert.isFalse(boolVal);
boolVal = config.containsKey("value2.value21.value211");
assert.isFalse(boolVal);
boolVal = config.containsKey("valueA.valueB.valueC");
assert.isFalse(boolVal);
});
test('Contains', () => {
var config = Parameters.fromJson(
"{ \"value1\": 123, \"value2\": { \"value21\": 111, \"value22\": 222 } }"
);
var has = config.containsKey("");
assert.isFalse(has);
has = config.containsKey("value1");
assert.isTrue(has);
has = config.containsKey("value2");
assert.isTrue(has);
has = config.containsKey("value3");
assert.isFalse(has);
has = config.containsKey("value2.value21");
assert.isTrue(has);
has = config.containsKey("value2.value31");
assert.isFalse(has);
has = config.containsKey("value2.value21.value211");
assert.isFalse(has);
has = config.containsKey("valueA.valueB.valueC");
assert.isFalse(has);
});
test('Set', () => {
let config: Parameters = new Parameters();
config.put(null, 123);
assert.equal(0, config.length());
config.put("field1", 123);
assert.equal(1, config.length());
assert.equal(123, config.getAsInteger("field1"));
config.put("field2", "ABC");
assert.equal(2, config.length());
assert.equal("ABC", config.get("field2"));
config.put("field2.field1", 123);
assert.equal("ABC", config.get("field2"));
config.put("field3.field31", 456);
assert.equal(3, config.length());
var subConfig = config.getAsMap("field3");
assert.isNotNull(subConfig);
assert.equal(456, subConfig.getAsInteger("field31"));
config.put("field3.field32", "XYZ");
assert.equal("XYZ", config.get("field3.field32"));
});
test('From Config', () => {
var config = ConfigParams.fromTuples(
"field1.field11", 123,
"field2", "ABC",
"field1.field12", "XYZ"
);
var parameters = Parameters.fromConfig(config);
assert.equal(2, parameters.length());
assert.equal("ABC", parameters.get("field2"));
var value = parameters.getAsMap("field1");
assert.equal(2, value.length());
assert.equal("123", value.get("field11"));
assert.equal("XYZ", value.get("field12"));
});
});
|
460461d455da06dd9a3e53df2cf658bbd829835c
|
TypeScript
|
jacintcodina/angular-avanzado-zoo
|
/src/app/admin/pipes/search.pipe.ts
| 2.734375
| 3
|
import { isNgTemplate } from '@angular/compiler';
import { Injectable, Pipe, PipeTransform } from '@angular/core';
@Pipe ({
name : 'search'
})
@Injectable()
export class SearchPipe implements PipeTransform {
transform (items:any, term:any) : any {
if(term == undefined){ //si el texte de buscqueda esta buit retorna tot
return items;
}
// si existeix filtra per javascript busca en el nom el terme de busqueda
return items.filter(function(item){
return item.name.toLowerCase().includes(term.toLowerCase());
});
}
}
|
b7421931763c5d26ce1020df59f8093e6c3d177b
|
TypeScript
|
BinniPyx98/FullProject
|
/server/src/check/pageInQuery/page.ts
| 2.578125
| 3
|
import {Request, Response} from "express";
import {sendErrorMessage} from "../../errorMessage/sendErrorMessage.js";
export function checkPage(request: Request, response: Response) {
let pageNumber: Number = Number(request.query.page)
let pageStatus: boolean
if (pageNumber <= 3) {
pageStatus = true
} else {
sendErrorMessage(response, {errorMessage: "server haven't this page"})
}
return pageStatus
}
|
a9e566d2905864d4249fa07727b1c8f7bc779671
|
TypeScript
|
NicolasFkm/BankApp
|
/src/services/PaymentService.ts
| 2.53125
| 3
|
import { IPayment } from "@models/Payment";
import PaymentRepository from "@repositories/PaymentRepository";
export default class PaymentService {
public paymentRepository: PaymentRepository;
constructor(){
this.paymentRepository = new PaymentRepository();
}
async create(account: IPayment): Promise<IPayment> {
const createdPayment = await this.paymentRepository.add(account);
return createdPayment;
}
async getById(id: number): Promise<IPayment|null> {
const account = await this.paymentRepository.getById(id);
return account;
}
}
|
21cb4ecdb12b7d669b11883bd42d6d34ec7d19db
|
TypeScript
|
Osbelkz/spotify_clone
|
/src/store/myLibrary-reducer.ts
| 2.515625
| 3
|
import {createAsyncThunk, createSlice} from "@reduxjs/toolkit";
import {spotifyWebApi} from "../api/spotify-web-api";
const initialState = {
myTopArtists: [] as SpotifyApi.ArtistObjectFull[]
}
export type MyLibraryStateType = typeof initialState
export const getMyTopArtists = createAsyncThunk("getMyTopArtists", async (arg, thunkAPI) => {
let result = await spotifyWebApi.getMyTopArtists()
return result.body.items
})
export const myLibrarySlice = createSlice({
name: "myLibrary",
initialState: initialState,
reducers: {},
extraReducers: builder => (
builder
.addCase(getMyTopArtists.fulfilled, (state, action) => {
state.myTopArtists = action.payload
})
)
})
|
7d85acd8cfb62a4f46d6943aaed8d352fffcba91
|
TypeScript
|
stwith/UniLogin
|
/universal-login-react/src/ui/hooks/useToggler.ts
| 2.578125
| 3
|
import {useState} from 'react';
export const useToggler = () => {
const [visible, setVisibility] = useState(false);
const toggle = (value?: boolean) => {
if (value === undefined) {
setVisibility(visible => !visible);
} else {
setVisibility(() => value);
}
};
return {visible, toggle};
};
|
fe3362fe69c7e41117738fec5b2c117e8f1a096b
|
TypeScript
|
YaoZeyuan/leetcode
|
/resolve/二刷/150.ts
| 3.421875
| 3
|
function evalRPN(tokens: string[]): number {
let stackList: number[] = []
for (let item of tokens) {
let stack1: number
let stack2: number
let result: number
switch (item) {
case '+':
stack2 = stackList.pop()
stack1 = stackList.pop()
result = stack1 + stack2
stackList.push(result)
break
case '-':
stack2 = stackList.pop()
stack1 = stackList.pop()
result = stack1 - stack2
stackList.push(result)
break
case '*':
stack2 = stackList.pop()
stack1 = stackList.pop()
result = stack1 * stack2
stackList.push(result)
break
case '/':
stack2 = stackList.pop()
stack1 = stackList.pop()
// 只取整数部分
result = Math.trunc(stack1 / stack2)
stackList.push(result)
break
default:
// 普通数字
stackList.push(parseInt(item))
}
}
return stackList.pop()
}
// console.log(evalRPN(['10', '6', '9', '3', '+', '-11', '*', '/', '*', '17', '+', '5', '+']))
|
1935b2c59ae302e937ee80958633478ad58dc11c
|
TypeScript
|
LarryHPham/ang_batterup
|
/app/modules/share/share.module.ts
| 2.5625
| 3
|
import {Component, OnInit, Input} from '@angular/core';
import {ModuleHeader} from '../../components/module-header/module-header.component';
import {CircleImage} from '../../components/images/circle-image';
//Import needed interfaces
import {ModuleHeaderData} from '../../components/module-header/module-header.component';
import {CircleImageData} from '../../components/images/image-data';
export interface ShareModuleInput{
//Image url used for the image component
imageUrl: string;
//Optional - Title of module
//Default is 'Share This Profile With Your Friends'
moduleTitle?: string;
//Optional - Text inside module
//Default is 'Share this Profile Below'
shareText?: string;
}
@Component({
selector: 'share-module',
templateUrl: './app/modules/share/share.module.html',
directives: [ModuleHeader, CircleImage],
providers: []
})
export class ShareModule implements OnInit{
@Input() shareModuleInput: ShareModuleInput;
public moduleHeaderData: ModuleHeaderData = {
moduleTitle: 'Share This Profile With Your Friends',
hasIcon: false,
iconClass: ''
};
public imageData: CircleImageData = {
imageClass: "image-174",
mainImage: {
imageUrl: '',
hoverText: "Sample",
imageClass: "border-3"
}
};
public shareText: string = 'Share This Profile Below:';
public shareButtons: Array<{
class: string;
icon: string;
text: string;
url: string;
}> = [
{
class: 'facebook',
icon: 'fa-facebook',
text: 'Share on Facebook',
url: 'https://www.facebook.com/sharer/sharer.php?u='
},
{
class: 'twitter',
icon: 'fa-twitter',
text: 'Share on Twitter',
url: 'https://twitter.com/home?status='
},
{
class: 'google',
icon: 'fa-google-plus',
text: 'Share on Google +',
url: 'https://plus.google.com/share?url='
},
{
class: 'pinterest',
icon: 'fa-pinterest',
text: 'Share on Pinterest',
url: 'https://pinterest.com/pin/create/button/?url='
}
];
//Function to configure buttons and components
configureModule(){
var input = this.shareModuleInput;
var currentUrl = window.location.href;
var shareButtons = this.shareButtons;
//If input is undefined, exit function
if(typeof input === 'undefined'){
return false;
}
//Set custom module title if it exists
if(typeof input.moduleTitle !== 'undefined'){
this.moduleHeaderData.moduleTitle = input.moduleTitle;
}
//Set custom share text if it exists
if(typeof input.shareText !== 'undefined'){
this.shareText = input.shareText;
}
//Set image url
this.imageData.mainImage.imageUrl = input.imageUrl;
//Complete Url of share button
this.shareButtons.map(function(item){
switch(item.class){
case 'pinterest':
item.url += currentUrl + '&media=' + input.imageUrl;
break;
default:
item.url += currentUrl;
break;
}
return item;
})
}
ngOnInit(){
this.configureModule();
}
}
|
bd43787361d427264a4e0ff21a33860c55a54f12
|
TypeScript
|
adityaU/AfterGlow
|
/frontend-v2/src/helpers/variableExtractor.ts
| 2.515625
| 3
|
import { fetchQuestionVariables } from 'src/apis/questions';
import { randomID } from './random';
class VariableExtractor {
allVariables: any;
variablesLocal: any;
resolve: any;
code: string;
noMatch: any;
constructor(code, existingVariables) {
this.allVariables = [];
this.variablesLocal = existingVariables;
this.resolve = [];
this.code = code;
this.noMatch = false;
}
findAndSetupQuestionVariables(id, index) {
fetchQuestionVariables(id, this.setupQuestionVariables(index));
}
setupQuestionVariables(index) {
return (variables, _loading) => {
if (!variables) {
return;
}
const variableNames = this.variablesLocal.map((v) => v.name);
variables.forEach((v) => {
this.allVariables.push(v.name);
if (variableNames.indexOf(v.name) < 0) {
const generatedID = randomID() * 1000000000;
this.variablesLocal.push({
name: v.name,
id: generatedID,
var_type: v.var_type,
default: v.default,
});
}
});
this.resolve[index] = true;
this.cleanupOldVariables();
};
}
cleanupOldVariables() {
if (this.resolve.indexOf(false) >= 0 && this.noMatch) {
return;
}
const variableNames = this.variablesLocal.map((v) => v.name);
variableNames.forEach((v, i) => {
if (this.allVariables.indexOf(v) < 0) {
this.variablesLocal.splice(i, 1);
}
});
}
setUpVariables() {
if (!this.code) {
return;
}
this.allVariables = [];
this.noMatch = false;
const matches = this.code.match(/{{\W*.+?\W*}}/g);
const variableNames = this.variablesLocal.map((v) => v.name);
this.resolve = matches?.map(() => false) || [];
matches?.forEach((m, i) => {
const varName = m.replaceAll('{', '').replaceAll('}', '').trim();
const quesMatch = varName.match(/ques:(\d+)/);
if (quesMatch) {
this.findAndSetupQuestionVariables(quesMatch[1], i);
} else {
this.allVariables.push(varName);
if (variableNames.indexOf(varName) < 0) {
const generatedID = randomID() * 1000000000;
this.variablesLocal.push({
name: varName,
id: generatedID,
var_type: 'String',
default: '0',
});
}
this.resolve[i] = true;
this.cleanupOldVariables();
}
});
this.noMatch = true;
this.cleanupOldVariables();
}
}
export { VariableExtractor };
|
19ed75500640aecdc66ae78b7cae08d32f989c5a
|
TypeScript
|
cborac/node-discord
|
/tests/api/guildChannel.api.ts
| 2.609375
| 3
|
'use strict';
import { Bot } from '../../src/bot';
import { BotEvent } from '../../src/socket';
import { PermissionFlags, PermissibleType, Permission } from '../../src/structures/flags';
import config from '../config.json';
const bot = new Bot(config.token);
bot.connection.connect();
(async function (): Promise<void> {
await bot.events.wait(BotEvent.Ready);
const guild = await bot.guilds.get('702476896008405002');
const channel = await guild.channels.get('702476896008405005');
// Modify the name and topic of the guild channel
await channel
.modify({
name: channel.name + 'a',
topic: channel.topic ? channel.topic + 'a' : 'a',
})
.catch(() => console.log('Rate limit reached for channel modification'));
// Modify the permissions of the guild channel
channel.permissions.modify(
{
id: bot.user!.id,
type: PermissibleType.Member,
},
{
allow: PermissionFlags.from(Permission.SendMessages, Permission.AddReactions),
deny: PermissionFlags.from(Permission.AttachFiles),
},
);
await bot.events.wait(BotEvent.ChannelUpdate);
console.log(
channel.permissions.cache.get(bot.user!.id)?.flags.allow.has(Permission.AttachFiles),
'whether the bot use has the AttachFiles permission',
'expected: false',
); // expected: false
// Create a new invite in the guild channel
const invite = await channel.invites.create({
max: {
age: 15,
uses: 3,
},
unique: true,
});
console.log(invite.code, 'newly generated invite code');
// Delete the overwritten permissions of the bot's user
channel.permissions.delete(bot.user!.id);
await bot.events.wait(BotEvent.ChannelUpdate);
console.log(
channel.permissions.cache.has(bot.user!.id),
'whether a permission overwrite for the bot user exists',
'expected: false',
); // expected: false
})();
bot.events.on(BotEvent.Debug, console.log);
|
e1e8416797d6dc51629421b3634bb9a2c3bcfed3
|
TypeScript
|
sakuvaru/FitRockApp
|
/src/app/core/services/current-language.service.ts
| 2.9375
| 3
|
import { Injectable } from '@angular/core';
import { LanguageConfig } from '../models/core.models';
import { LanguageEnum, languageHelper } from '../../../lib/repository';
@Injectable()
export class CurrentLanguageService {
/**
* Default language
*/
private readonly defaultLanguage: LanguageConfig = new LanguageConfig(LanguageEnum.Cz, 'cs', 'cs');
/**
* Name of the local storage key where language is stored
*/
private readonly languageStorageKey = 'ui_language';
constructor(
) {
}
isDifferentThanCurrent(languageEnum: LanguageEnum): boolean {
const currentLanguage = this.getLanguage();
const languageToCompare = languageEnum === LanguageEnum.Default ? this.defaultLanguage.language : languageEnum;
if (currentLanguage.language === languageToCompare) {
return false;
}
return true;
}
setLanguage(languageEnum: LanguageEnum): void {
// get language config
const config = this.getLanguageConfig(languageEnum);
// store language
this.storeLanguage(config);
}
getLanguage(): LanguageConfig {
return this.getLanguageFromLocalStorage();
}
private getLanguageFromLocalStorage(): LanguageConfig {
const languageJson = localStorage.getItem(this.languageStorageKey);
if (!languageJson) {
// return default language && store it
return this.defaultLanguage;
}
// parse language from local storage
const parsedJson = JSON.parse(languageJson) as LanguageConfig;
return new LanguageConfig(languageHelper.getLanguage(parsedJson.language), parsedJson.locale, parsedJson.uiLanguage);
}
private storeLanguage(language: LanguageConfig): void {
localStorage.setItem(this.languageStorageKey, JSON.stringify(language));
}
/**
* Gets varios culture strings used by application
* @param language Language stored in db
*/
private getLanguageConfig(languageEnum: LanguageEnum): LanguageConfig {
let language: LanguageConfig;
if (languageEnum === LanguageEnum.Default) {
language = this.defaultLanguage;
} else if (languageEnum === LanguageEnum.Cz) {
language = new LanguageConfig(languageEnum, 'cs', 'cs');
} else if (languageEnum === LanguageEnum.En) {
language = new LanguageConfig(languageEnum, 'en', 'en');
} else {
console.warn(`Language '${languageEnum}' is not valid. Default language used`);
language = this.defaultLanguage;
}
return language;
}
}
|
7fce2150ae6963bb83f72c41e387ff9df6f8dc41
|
TypeScript
|
boosterlong/roguelikeautobattler
|
/data/modifiers.ts
| 2.671875
| 3
|
type Modifier = {
position: 'prefix' | 'suffix'
text: string
}
const Grand : Modifier = {
position: 'prefix',
text: 'Grand'
}
const Reaper : Modifier = {
position: 'suffix',
text: 'of the Reaper'
}
const Seeking : Modifier = {
position: 'prefix',
text: 'Seeking'
}
|
3d69b5ce2b39c2ca1c9a0824b487ecfee426663b
|
TypeScript
|
ftmmohd2000/blog-app
|
/server/src/tests/fixtures/user.ts
| 2.765625
| 3
|
import faker from "faker";
export interface IUser {
email: string;
password: string;
firstName: string;
lastName: string;
}
export const createFakeUser = () => ({
email: faker.internet.email(),
password: faker.internet.password(),
firstName: faker.name.firstName(),
lastName: faker.name.lastName()
});
|
21c310eb738f40e9ff6fd9b0d352dcc3c425d49f
|
TypeScript
|
meanhive/voltron
|
/src/app/auth.service.ts
| 2.59375
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { of} from 'rxjs/observable/of';
import {Subject } from 'rxjs/Subject';
import { User } from '../user';
import { Auth } from '../auth';
import { catchError, map, tap, } from 'rxjs/operators';
@Injectable()
export class AuthService {
private http: HttpClient;
loginEndpoint = 'http://localhost:3000/api/users/authenticate';
signupEndpoint = 'http://localhost:3000/api/users';
signupData: any;
loginData: any;
private loggedIn = false;
private authAnnouncerSource = new Subject<object|null>();
authAnnouncer$ = this.authAnnouncerSource.asObservable()
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
};
constructor(http: HttpClient) {
this.http = http;
if (localStorage.getItem('user')) {
this.loggedIn = true;
} else {
this.loggedIn = false;
}
}
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
console.error(error); // log to console instead
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
login (loginData ): Observable<{} | Auth>{
this.loggedIn = true;
return this.http.post<Auth>(this.loginEndpoint,JSON.stringify(loginData), this.httpOptions)
}
signup (signupData): Observable<{} | User> {
return this.http.post<User>(this.signupEndpoint, JSON.stringify(signupData), this.httpOptions)
.pipe(
tap(data => console.log(`${data} user created`)),
catchError(this.handleError('signup', {}))
)
}
announceLogin(user) {
return this.authAnnouncerSource.next(user);
}
logOut () {
localStorage.removeItem('jwtToken');
localStorage.removeItem('user');
this.announceLogin(null)
}
}
|
ef3a27ced118c937b827202b59c86e3b487e49b5
|
TypeScript
|
francisco-neto-fit/sistemas_comentarios_API
|
/src/middlewares/ensureAuthenticated.ts
| 3.078125
| 3
|
import { Request, Response, NextFunction } from "express";
import {verify} from 'jsonwebtoken'
interface IPayload{
sub:string;
}
export function ensureAuthenticated(request:Request, response:Response, next:NextFunction){
//Recupernaod o token na requisição
const authToken = request.headers.authorization; //Baerer Token => authorization:Baerer {token}
//verifica se está faltando o token
if(!authToken){
return response.status(401).end();
}
const [,token] = authToken.split(' '); // coloca o segundo valor do reotrno na variável 'token'
try{
//verifica se é token válido
const decode = verify(token,'ea39ff7c7647a69d28f56e86ff287860');
const {sub} = decode as IPayload; // sub = id do usuário
request.user_id = sub;
//Caso seja válido retorna o payload do jwt na variável decode
//com o token váliado avança para a próxima função
return next();
//caso o token seja inválido, cai dentro do catch
} catch(err){
//O end singifica que não precisa ir para a próxima função
return response.status(401).end();
}
}
|
5a94760177c28113d19d92ad8659f514dbee03d4
|
TypeScript
|
lucasfloripa/bank-front
|
/src/store/reducers/banker.reducer.ts
| 2.828125
| 3
|
import { Reducer } from 'redux'
import { bankerTypes } from '../types'
const initialState: bankerTypes.State = {
banker: {
_id: '',
userType: '',
name: '',
email: '',
bank: '',
},
bankers: []
}
const bankerReducer: Reducer<bankerTypes.State, bankerTypes.ActionsTypes> = (
state = initialState,
action: bankerTypes.ActionsTypes
): bankerTypes.State => {
switch (action.type) {
case bankerTypes.Types.GET_BANKER:
return { ...state, banker: action.payload }
case bankerTypes.Types.GET_BANKERS:
return { ...state, bankers: action.payload }
case bankerTypes.Types.CREATE_BANKER:
return { ...state, banker: action.payload }
case bankerTypes.Types.UPDATE_BANKER:
return {
...state,
bankers: state.bankers.map((banker) =>
banker._id === action.payload._id ? (banker = action.payload) : banker
)
}
case bankerTypes.Types.DELETE_BANKER:
return {
...state,
bankers: state.bankers.filter(
(banker) => banker._id !== action.payload
)
}
default:
return state
}
}
export { bankerReducer }
|
90ed17f2971a42e390115ef916b147a47e4f67f9
|
TypeScript
|
josandreu/Js-examples
|
/webpack/webpack-starter-kit/src/components/app.ts
| 3.265625
| 3
|
export class HelloWorld {
// hay que definir el tipo de dato de cada propiedad
name: string;
constructor(name: string) {
this.name = name;
}
greet(): string {
return `Hola mundo, Webpack con ${this.name}`;
}
}
|
7bbc288ec3c6b214ea40c6d8b7f88427126c331b
|
TypeScript
|
GalStan/minesweeper
|
/src/Solver/ListNode/index.ts
| 2.921875
| 3
|
export default class ListNode<T> {
public next?: ListNode<T>;
public prev?: ListNode<T>;
constructor(public value: T) {}
}
|
c0f83b1ad33da64ce5bb0b7983f337d38a7ceb40
|
TypeScript
|
OU-CS/capstone-repo-group-4
|
/backend/src/handlers/find-user-token.ts
| 3.015625
| 3
|
import { APIGatewayProxyEventQueryStringParameters, APIGatewayProxyHandler } from 'aws-lambda';
import { failedResponse, successResponse } from '../helpers/responses';
export type ParamProps = APIGatewayProxyEventQueryStringParameters | null;
export type UserTokenParams = {
userToken: string;
};
/**
* Validates all query string parameters from api event
*/
export const validateParameters = (params: ParamProps): UserTokenParams => {
if (!params) {
throw new Error('No query parameters were specified');
}
const { userToken } = params;
if (!userToken) {
throw new Error('No userToken was specified');
}
return { userToken };
};
/**
* A simple example includes a HTTP get method to get return a message
*/
export const findUserToken: APIGatewayProxyHandler = async (event) => {
console.info('received:', event);
try {
const { userToken } = validateParameters(event.queryStringParameters);
console.info('Token found', userToken);
return successResponse({});
} catch (e) {
console.error(e);
return failedResponse(400, e);
}
};
|
0c4fdea11ba75577a88559ddd77ddc3890bd9f65
|
TypeScript
|
yujuiting/gaudi-editor
|
/src/ui/hooks/dnd/types.ts
| 2.5625
| 3
|
import { Blueprint } from 'gaudi';
import { ScaffoldId } from 'base/id';
export enum DnDType {
Blueprint = 'blueprint',
Scaffold = 'scaffold',
}
export class BlueprintDragData {
static of(blueprint: Blueprint) {
return new BlueprintDragData(blueprint);
}
constructor(public readonly blueprint: Blueprint) {}
}
export function isBlueprintDragData(value: unknown): value is BlueprintDragData {
return value instanceof BlueprintDragData;
}
export class ScaffoldDragData {
static of(id: ScaffoldId) {
return new ScaffoldDragData(id);
}
constructor(public readonly id: ScaffoldId) {}
}
export function isScaffoldDragData(value: unknown): value is ScaffoldDragData {
return value instanceof ScaffoldDragData;
}
|
4809c8f80d4a1bb96200ba12e7a87fdcec2362c9
|
TypeScript
|
ng-ui-libraries/forms
|
/test/Service/NestedSearcher.spec.ts
| 2.75
| 3
|
import {NestedSearcher} from "../../src/lib/Service/Impl/NestedSearcher";
import {Observable} from "rxjs/Rx";
class NestedSearcherShunt extends NestedSearcher {
shouldBeFound = true;
doesItemMatchSearch(item) {
return this.shouldBeFound;
}
}
describe('Module: Form', () => {
describe('Class: NestedSearcher', () => {
describe('On New Instance', () => {
it('should be a new instance of NestedSearcher', () => {
let service = new NestedSearcher();
expect(service instanceof NestedSearcher).toBeTruthy();
});
});
describe('After Instantiation', () => {
let service: NestedSearcherShunt;
beforeEach(() => {
service = new NestedSearcherShunt();
});
describe('Method: Does Item Match Search', () => {
let shouldBeFoundInChildren = false;
beforeEach(() => {
shouldBeFoundInChildren = false;
service.doAnyChildrenMatchSearch$ = (item) => {
return Observable.from([shouldBeFoundInChildren]);
};
});
describe('Item was found', () => {
beforeEach(() => {
service.shouldBeFound = true;
});
it('should return true', (done) => {
service.doesItemMatchSearch$({}).subscribe((value) => {
expect(value).toBeTruthy();
done();
});
});
});
describe('Item was not found', () => {
beforeEach(() => {
service.shouldBeFound = false;
});
it('should return true if any children were matched', (done) => {
shouldBeFoundInChildren = true;
service.doesItemMatchSearch$({children: [{}]}).subscribe((value) => {
expect(value).toBeTruthy();
done();
});
});
it('should return false if no children were matched', (done) => {
shouldBeFoundInChildren = false;
service.doesItemMatchSearch$({children: [{}]}).subscribe((value) => {
expect(value).toBeFalsy();
done();
});
});
});
});
describe('Method: Does Parent Match Search', () => {
beforeEach(() => {
service.shouldBeFound = false;
});
it('should return false if parent does not exist', (done) => {
service.doesParentMatchSearch$({}).subscribe((value) => {
expect(value).toBeFalsy();
done();
});
});
it('should return false if the parent does not match', (done) => {
service.doesParentMatchSearch$({parent: {}}).subscribe((value) => {
expect(value).toBeFalsy();
done();
});
});
it('should return true if a parent matches', (done) => {
service.shouldBeFound = true;
service.all[1] = {};
service.doesParentMatchSearch$({$parent: 1}).subscribe((value) => {
expect(value).toBeTruthy();
done();
});
})
});
describe('Method: Do Any Children Match Search', () => {
beforeEach(() => {
service.shouldBeFound = false;
});
it('regardless of number of children, only one boolean value is returned', (done) => {
let numberSent = 0;
service.doAnyChildrenMatchSearch$({children: [{}, {}, {}]}).subscribe({
next : (value) => {
expect(value).toBeFalsy();
numberSent++;
},
complete: () => {
expect(numberSent).toEqual(1);
done();
}
});
});
it('should return true if any of the children matched the search', (done) => {
service.shouldBeFound = true;
service.doAnyChildrenMatchSearch$({children: [{}, {}, {}]}).subscribe((value) => {
expect(value).toBeTruthy();
done();
});
});
});
describe('Method: Are Any Children Found', () => {
beforeEach(() => {
service.shouldBeFound = false;
});
it('should return false if there is no children property', (done) => {
service.areAnyChildrenFound$({}).subscribe((value) => {
expect(value).toBeFalsy();
done();
})
});
it('should return false if there are no children', (done) => {
service.areAnyChildrenFound$({children: []}).subscribe((value) => {
expect(value).toBeFalsy();
done();
})
});
it('should return true if any children match the search', (done) => {
service.shouldBeFound = true;
service.areAnyChildrenFound$({children: [{}]}).subscribe((value) => {
expect(value).toBeTruthy();
done();
})
})
});
});
});
});
|
c88cf27af4f4d49e4f588d6a136add561bee5aaa
|
TypeScript
|
chrand90/DeathCauses
|
/death-causes-app/src/components/database/Deathcause.ts
| 2.6875
| 3
|
import RelationLinks from "../../models/RelationLinks";
import FrequencyTable, { FrequencyJson } from "./FrequencyTable";
import { RiskFactorGroup, RiskFactorGroupJson } from "./RickFactorGroup";
import { SpecialFactorTable, SpecialFactorTableJson } from "./RiskRatioTable";
export interface DeathCauseJson {
Age?: FrequencyJson;
RiskFactorGroups: RiskFactorGroupJson[];
}
export interface ConditionJson extends DeathCauseJson {
SpecialFactorGroups: SpecialFactorTableJson[][];
}
export interface RawDeathCauseJson {
[deathCauseName: string]: DeathCauseJson;
}
export class RiskFactorGroupsContainer {
riskFactorGroups: RiskFactorGroup[];
deathCauseName: string;
optimizabilityClasses: string[][] | null=null;
constructor(json: DeathCauseJson, name: string) {
this.riskFactorGroups = json.RiskFactorGroups.map(element => {
return new RiskFactorGroup(element)
});
this.deathCauseName = name
}
getAllFactorNamesWithoutAge(){
return this.riskFactorGroups.flatMap((rfg: RiskFactorGroup) => {
return Array.from(rfg.getAllFactorsInGroup())
}).filter((d: string) => {
return d!=="Age"
})
}
getAllFactorNames(){
return this.riskFactorGroups.flatMap((rfg: RiskFactorGroup) => {
return Array.from(rfg.getAllFactorsInGroup())
})
}
}
export default class DeathCause extends RiskFactorGroupsContainer{
ages: FrequencyTable;
constructor(json: DeathCauseJson, name: string) {
super(json, name);
if(json.Age!==undefined){
this.ages = new FrequencyTable(json.Age);
}
else{
this.ages = new FrequencyTable({age_classification:[], age_prevalences:[]});
}
}
}
export class Condition extends DeathCause {
specialFactorTables: SpecialFactorTable[]
constructor(json: ConditionJson, name: string){
super(json, name)
this.specialFactorTables=[]
json.SpecialFactorGroups.forEach(listOfSpecialFactorTables => {
listOfSpecialFactorTables.forEach((specialFactorTableJSON: SpecialFactorTableJson) => {
this.specialFactorTables.push(new SpecialFactorTable(specialFactorTableJSON))
})
})
}
}
|
8bb7eaf72c448283368106979aeba21665215a1f
|
TypeScript
|
surendra20/sample-stock-market
|
/src/features/stock/stockReducer.ts
| 2.609375
| 3
|
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { RootState } from '../../app/store';
import moment from 'moment';
import { getGeometricMean as mean } from '../../common';
export type TradeObject = {
stock: string;
type: string;
quantity: number;
price: number;
totalPrice: number;
time: string;
};
export interface StockObject {
symbol: string;
type: string;
lastDividend: number;
fixedDividend: number | null;
parValue: number;
}
interface StockState {
stockDetails: Array<StockObject>;
selectedStock: StockObject | null;
tradeList: Array<TradeObject>;
tradeListColumns: Array<Column>;
}
export interface Column {
key: string;
value: string;
prepend?: string | number;
isPrice?: boolean;
}
const initialState: StockState = {
stockDetails: [
{
symbol: 'TEA',
type: 'common',
lastDividend: 0,
fixedDividend: null,
parValue: 100
},
{
symbol: 'POP',
type: 'common',
lastDividend: 8,
fixedDividend: null,
parValue: 100
},
{
symbol: 'ALE',
type: 'common',
lastDividend: 23,
fixedDividend: null,
parValue: 60
},
{
symbol: 'GIN',
type: 'preferred',
lastDividend: 8,
fixedDividend: 2,
parValue: 100
},
{
symbol: 'JOE',
type: 'common',
lastDividend: 13,
fixedDividend: null,
parValue: 250
}
],
selectedStock: null,
tradeList: [],
tradeListColumns: [
{ key: 'stock', value: 'Stock' },
{ key: 'type', value: 'Trade Type' },
{ key: 'quantity', value: 'Quantity' },
{ key: 'price', value: 'Price', prepend: '$', isPrice: true },
{ key: 'totalPrice', value: 'Total Price', prepend: '$', isPrice: true },
{ key: 'time', value: 'Time' }
]
};
export const stockReduce = createSlice({
name: 'stock',
initialState,
reducers: {
selectStock: (state, action: PayloadAction<string>) => {
const selectedStock: StockObject | undefined = state.stockDetails.find(
({ symbol }) => symbol === action.payload
);
state.selectedStock = selectedStock || null;
},
clearStockSelection: (state) => {
state.selectedStock = null;
},
updateTradeList: (state, action: PayloadAction<{ type: string; quantity: number; price: number }>) => {
const tradeList = [
...state.tradeList,
{
...action.payload,
totalPrice: action.payload.quantity * action.payload.price,
time: moment().format('MM-DD-YY, hh:mm:ss a'),
stock: state.selectedStock ? state.selectedStock.symbol : ''
}
];
state.tradeList = tradeList;
}
}
});
export const { selectStock, clearStockSelection, updateTradeList } = stockReduce.actions;
export const getStock = (state: RootState) => state.stock.stockDetails;
export const getSelectedStock = (state: RootState) => state.stock.selectedStock;
export const getTradeListColumns = (state: RootState) => state.stock.tradeListColumns;
export const getTradeList = (state: RootState) => {
const list = state.stock.tradeList.filter((trade) => {
const duration = moment.duration(moment(new Date()).diff(trade.time));
const mins = duration.minutes();
return state.stock.selectedStock ? mins < 15 && state.stock.selectedStock.symbol === trade.stock : mins < 15;
});
return list;
};
export const getAllPrices = (state: RootState): number => {
const prices = state.stock.tradeList.reduce((acc: Array<number>, { price }) => {
return [ ...acc, price ];
}, []);
return mean(prices);
};
export default stockReduce.reducer;
|
d29fe6199c0781f0847abc5c49743088f94eac5f
|
TypeScript
|
decaffeinate/decaffeinate
|
/test/iife_test.ts
| 2.546875
| 3
|
import check from './support/check';
test('does not wrap in an IIFE by default', () => {
check(`a = 1`, `const a = 1;`);
});
test('wraps in an IIFE if requested', () => {
check(`a = 1`, `(function() {\nconst a = 1;\n}).call(this);`, { options: { bare: false } });
});
test('cannot be used with useJSModules', () => {
expect(() => check(`a = 1`, `const a = 1;`, { options: { useJSModules: true, bare: false } })).toThrow(
/useJSModules requires bare output/
);
});
|
d95d3a8a3397e9fc12661db948923a31934f520d
|
TypeScript
|
milesj/emojibase
|
/packages/generator/src/builders/buildVersionedData.ts
| 2.78125
| 3
|
import { log } from '../helpers/log';
import { readCache } from '../helpers/readCache';
import { writeCache } from '../helpers/writeCache';
import { loadData } from '../loaders/loadData';
import { loadSequences } from '../loaders/loadSequences';
import { loadZwjSequences } from '../loaders/loadZwjSequences';
import { EmojiDataMap } from '../types';
export type VersionDataMap = Record<string, EmojiDataMap>;
export interface VersionDataSet {
emojiVersions: VersionDataMap;
unicodeVersions: VersionDataMap;
}
export async function buildVersionedData(): Promise<VersionDataSet> {
const cache = readCache<VersionDataSet>('final/emoji-unicode-versions.json');
if (cache) {
return cache;
}
log.title('build', 'Building versioned data');
const used: Record<string, boolean> = {};
const emojiVersions: VersionDataMap = {};
const unicodeVersions: VersionDataMap = {};
// Handle partitioning each emoji into a specific version
const partitionVersions = (data: EmojiDataMap) => {
Object.keys(data).forEach((hexcode) => {
const emoji = data[hexcode];
const { version, unicodeVersion } = data[hexcode];
// Was introduced in a prior version
if (used[hexcode]) {
return;
}
used[hexcode] = true;
if (emojiVersions[version]) {
emojiVersions[version][hexcode] = emoji;
} else {
emojiVersions[version] = { [hexcode]: emoji };
}
if (unicodeVersion) {
if (unicodeVersions[unicodeVersion]) {
unicodeVersions[unicodeVersion][hexcode] = emoji;
} else {
unicodeVersions[unicodeVersion] = { [hexcode]: emoji };
}
}
});
};
// As of v13.0, the versions are included in the data sources,
// so we don't need to loop and extract from previous versions.
partitionVersions(await loadData());
partitionVersions(await loadSequences());
partitionVersions(await loadZwjSequences());
// Cache the partitioned files
await writeCache('final/emoji-unicode-versions.json', {
emojiVersions,
unicodeVersions,
});
log.success('build', 'Built versioned data');
return {
emojiVersions,
unicodeVersions,
};
}
|
d561c1f0219bca5ff9ee0b9243d68788a8f9df85
|
TypeScript
|
pixel-pixel/chat-bucket
|
/server/src/Bots/Spam.bot.ts
| 2.53125
| 3
|
import { Message } from '../../../common/types/Message.type'
import { adjectives, animals, colors, Config, names, uniqueNamesGenerator } from 'unique-names-generator'
import Bot from './Bot'
export default class SpamBot extends Bot {
ids: number[] = []
constructor(id: number) {
super(
id,
'Spam bot',
'https://media.istockphoto.com/photos/spam-picture-id458632943',
'lorem ipsem'
)
}
getRandNum() {
return (10 + Math.random() * 110) * 1000
}
getSpamText() {
return uniqueNamesGenerator({
dictionaries: [adjectives, colors, adjectives, names, animals],
separator: ' ',
length: 5
})
}
onMessage(msg: Message, send: (m: Message) => void) {
const d = this.ids.find(id => id === msg.senderId)
if (!d) {
this.ids.push(msg.senderId)
const spam = () => {
const botMsg: Message = {
...msg,
senderName: msg.recipientName,
senderId: msg.recipientId,
recipientName: msg.senderName,
recipientId: msg.senderId,
text: 'SPAM: ' + this.getSpamText()
}
send(botMsg)
setTimeout(spam, this.getRandNum())
}
spam()
}
}
}
|
09510cbe31d435f9ed477661e92691e8045002f1
|
TypeScript
|
johanrojas07/Votos
|
/src/app/votes/votes.component.ts
| 2.703125
| 3
|
import { Article } from './Article';
import { Component } from '@angular/core';
@Component({
selector: 'app-votes',
templateUrl: './votes.component.html',
styleUrls: ['./votes.component.css']
})
export class VotesComponent {
title: string;
articles: Article[];
constructor() {
this.title = 'Votes App';
this.articles= [
new Article('Angular2', 'http://angular.io',30),
new Article('johan', 'http://johan.io',20),
new Article('Nada', 'http://nada.io',5),
];
}
addArticle(title: HTMLInputElement, link: HTMLInputElement):boolean{
this.articles.push(
new Article(title.value, link.value);
);
title.value='';
link.value='';
return false;
}
sortedArticles() : Article[]{
return this.articles.sort((a : Article ,b : Article) => b.votes - a.votes );
}
}
|
eef95ae5f4441573af2f9ebe569ee5f3c7f7dd1c
|
TypeScript
|
kova1chuk/Blog-React.js-Next.js
|
/store/posts/reducer.ts
| 2.9375
| 3
|
import values from 'lodash/values';
import { IPostsState, CREATE_POST, UPDATE_POST, DELETE_POST, SET_POSTS, IPostActionTypes } from './types';
const initialState: IPostsState = {
posts: null,
};
export const postReducer = (state = initialState, action: IPostActionTypes): IPostsState => {
switch (action.type) {
case CREATE_POST:
return { posts: [...values(state.posts), action.payload] };
case UPDATE_POST:
return {
posts: values(state.posts).map((post) => {
if (post.id !== Number(action.payload.id)) {
return action.payload;
}
return post;
}),
};
case DELETE_POST:
return {
posts: values(state.posts).filter((post) => post.id !== Number(action.payload)),
};
case SET_POSTS:
return {
posts: action.payload,
};
default:
return state;
}
};
|
f8b41985529fd70eb7384cca19219f3f65ee54cc
|
TypeScript
|
elder-orm/core
|
/tests/integration/defining-models.test.ts
| 2.890625
| 3
|
import Elder, {
Model,
StringType,
type,
Adapter,
PostgresAdapter,
Collection
} from '../../src'
import * as Knex from 'knex'
import { development } from '../../knexfile'
import config from '../config'
beforeEach(async () => {
const knex: Knex = Knex(development)
await knex.seed.run(development.migrations)
return knex.destroy()
})
describe('Defining models', () => {
test('Creating a simple model', async () => {
class Cat extends Model {
@type('string') name: string
}
const orm = Elder.create({
config,
models: { cat: Cat }
})
const cats = await Cat.all()
expect(cats).toBeInstanceOf(Collection)
expect(cats.length).toBe(2)
expect(cats[0]).toBeInstanceOf(Cat)
expect(cats[0].name).toBe('Fluffy')
return orm.destroy()
})
test('Creating a model with a custom type', async () => {
class CatModel extends Model {
@type('cat-name') name: string
}
class CatName extends StringType {}
const orm = Elder.create({
config,
models: { cat: CatModel },
types: { 'cat-name': CatName }
})
const cats = await CatModel.all()
expect(cats[0].name).toBe('Fluffy')
return orm.destroy()
})
test('Creating a model with a custom type thats scoped to the model', async () => {
class Cat extends Model {
@type('name') name: string
}
class CatName extends StringType {}
const orm = Elder.create({
config,
models: { cat: Cat },
types: { 'cat:name': CatName }
})
const cats = await Cat.all()
expect(cats[0].name).toBe('Fluffy')
return orm.destroy()
})
test('Creating a model with a custom adapter', async () => {
class Cat extends Model {
@type('string') name: string
}
class Dog extends Model {
@type('string') name: string
}
class DefaultAdapter extends Adapter {
all(): Promise<any> {
return Promise.resolve([{ name: 'Fido' }])
}
}
const orm = Elder.create({
config: config,
models: { cat: Cat, dog: Dog },
adapters: { default: DefaultAdapter, cat: PostgresAdapter }
})
const cats = await Cat.all()
const dogs = await Dog.all()
expect(cats[0].name).toBe('Fluffy')
expect(dogs.serialize()).toEqual([{ name: 'Fido' }])
return orm.destroy()
})
test('Defining id explicitly', async () => {
class Cat extends Model {
@type('number') id: number
@type('string') name: string
}
class CatName extends StringType {}
const orm = Elder.create({
config,
models: { cat: Cat }
})
const cat = Cat.create()
expect(cat.id).toBe(null)
cat.id = 2
expect(cat.id).toBe(2)
return orm.destroy()
})
})
|
9161ed5acdcb3b860d64b6e840f6a995eef7401a
|
TypeScript
|
anjrew/angular-schematics-playground
|
/src/utils/add-to-module-context.ts
| 2.578125
| 3
|
import * as ts from 'typescript';
/**
* @description
* The file add-to-module-context.ts gets a context class holding data for the planned modifications
*
* */
export class AddToModuleContext {
// source of the module file
source: ts.SourceFile;
// the relative path that points from
// the module file to the component file
relativePath: string;
// name of the component class
classifiedName: string;
}
|
44d6737590b7b3a380d485c233027407c757646b
|
TypeScript
|
mohamedmagdy17593/proto3d
|
/src/utils/model.ts
| 2.6875
| 3
|
import { titleCase } from 'tiny-case';
import { Model, ModelTypes } from 'types/editor';
import { ApiModelStatus } from 'types/model';
let nameCounts: { [key: string]: number } = {};
export function getModelName(label: string) {
let count = (nameCounts[label] = (nameCounts[label] ?? 0) + 1);
let name = `${titleCase(label)} ${count}`;
return name;
}
interface CreateNewModelArg {
id: string;
type: ModelTypes;
name?: string;
modelUrl?: string;
}
export function createNewModel({
id,
type,
name,
modelUrl,
}: CreateNewModelArg): Model {
let label = name ?? type;
switch (type) {
case 'plane': {
return {
id,
type,
name: getModelName(label),
color: '#393e46',
scale: [1, 1, 1],
position: [0, 0, 0],
rotation: [0, 0, 0],
};
}
case 'box': {
return {
id,
type,
name: getModelName(label),
color: '#b55400',
scale: [1, 1, 1],
position: [0, 0, 0],
rotation: [0, 0, 0],
};
}
case 'sphere': {
return {
id,
type,
name: getModelName(label),
color: '#b55400',
scale: [1, 1, 1],
position: [0, 0, 0],
rotation: [0, 0, 0],
segments: [15, 15],
radius: 1,
};
}
case 'custom': {
return {
id,
type,
name: getModelName(label),
scale: [1, 1, 1],
position: [0, 0, 0],
rotation: [0, 0, 0],
modelUrl: modelUrl!,
};
}
default: {
throw Error(`unknown model Type ${type}`);
}
}
}
export function getModelBadgeDotColor(status: ApiModelStatus) {
return status === 'uploaded'
? 'green'
: status === 'error-while-uploading'
? 'red'
: status === 'uploading'
? 'orange'
: 'blue';
}
export function getModelBadgeDotTitle(status: ApiModelStatus) {
return status === 'uploaded'
? 'Ready to use'
: status === 'error-while-uploading'
? 'Error while uploading (try later)'
: status === 'uploading'
? 'Wait this is currently uploading'
: 'Click to trigger upload';
}
|
f31c9d20d88c4c7852c514b166b26bbd8c49699b
|
TypeScript
|
chansen1988/acme-web
|
/server/src/helpers/domain-validation.helper.ts
| 3
| 3
|
import { Product } from "../models/product";
import productService from "../services/product.service";
interface DomainValidationHelper {
isRegistered(domain: string, customerId?: string): Promise<boolean>;
validate(tld: RegExp, product: Product): Promise<string>;
}
class DomainValidationHelperClass implements DomainValidationHelper {
async isRegistered(domain: string, customerId?: string) {
const product = await productService.find(i => i.Domain === domain
&& /Domain$/i.test(i.ProductName)
&& i.StartDate <= new Date()
&& i.endDate >= new Date()
&& (!customerId || i.CustomerId === customerId));
return !!product;
}
async validate(tld: RegExp, product: Product): Promise<string> {
if (!tld.test(product.Domain)) {
return `Unsupported Domain: ${product.Domain}`;
}
if (product.DurationMonths <= 0 || product.DurationMonths % 12 !== 0) {
return `Duration must be postive multiple of 1 year (12 months)`;
}
if (await this.isRegistered(product.Domain)) {
return `Duplicate Domain Registration: ${product.Domain}`;
}
}
}
export default <DomainValidationHelper>new DomainValidationHelperClass();
|
47f458bd03cd3f0bfdac2aa5ca795271ab637083
|
TypeScript
|
tung-dang/alfred-workflow-nodejs-next
|
/packages/sc-repo-search/src/actions/ProjectAction.ts
| 2.578125
| 3
|
import { AfItem, IAction } from '@alfred-wf-node/core';
import { CommandParams, ProjectActionArg } from '../types';
const DEFAULT_ICON = 'code.png';
export default class ProjectAction implements IAction {
getDesc?: ((arg: any) => string) | undefined;
isValid: (arg: any) => boolean;
toAlfredItem: (arg: any) => AfItem;
shortcut: any;
icon: any;
key: string;
name: string;
execute: (arg: any) => void;
constructor(options) {
this.key = options.key;
this.name = options.name;
this.execute = options.execute ? options.execute.bind(this) : undefined;
this.shortcut = options.shortcut || '';
this.icon = options.icon || DEFAULT_ICON;
}
// @ts-ignore
shouldDisplay(data?: any) {
return true;
}
build(argItem: CommandParams) {
const arg: ProjectActionArg = {
actionKey: this.key || this.name,
actionArg: argItem
};
return new AfItem({
uid: this.name,
title: this.name,
subtitle: this.getSubTitle(argItem),
icon: 'icons/' + this.icon,
// arg will be passed to hanlder of `commands.EXECUTE`
arg,
valid: this.shouldDisplay(argItem)
});
}
/**
* When creating new instance, consumer can pass a overridden of `getSubTitle` method.
* @param data
* @returns {*|string}
*/
getSubTitle(data) {
return data.path;
}
filterKey() {
return `${this.name}${this.shortcut ? ' ' + this.shortcut : ''}`;
}
}
|
3e69dfccd452494a0bc8d8846e7f1004b7f35e2f
|
TypeScript
|
Shakarbek/angular
|
/src/app/calculator/calculator.component.ts
| 2.703125
| 3
|
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-calculator',
templateUrl: './calculator.component.html',
styleUrls: ['./calculator.component.scss']
})
export class CalculatorComponent implements OnInit {
currentNumber='0';
firstNumber=null;
secondNumber=null;
operator=null;
writeSecondNumber=false;
constructor() { }
ngOnInit(): void {
}
public enterNumber(n: string){
if(this.writeSecondNumber){
this.currentNumber=n;
this.writeSecondNumber=false;
}
else if(this.currentNumber=='0'){
this.currentNumber=n;
this.firstNumber=n;
}
else{
this.currentNumber+=n;
}
}
public operate(op, secondNum){
if(op=="+"){
return this.firstNumber+=Number(secondNum);
}
else if (op=="-"){
return this.firstNumber-=secondNum;
}
else if (op=="*"){
return this.firstNumber*=secondNum;
}
else if (op=="/"){
return this.firstNumber/=secondNum;
}
else if (op=="%"){
this.firstNumber*=(secondNum/100);
return this.firstNumber*100;
}
else if (op=="pow"){
return this.firstNumber=Math.pow(this.firstNumber, secondNum);
}
else if(op=="="){
return this.secondNumber;
}
}
public operation(op: string){
if(this.firstNumber === null){
this.firstNumber = Number(this.currentNumber);
}else if(this.operator){
const result = this.operate(this.operator , Number(this.currentNumber));
this.currentNumber = String(result);
this.firstNumber = result;
}
this.operator = op;
this.writeSecondNumber = true;
}
public clearall(){
this.currentNumber='0';
this.firstNumber=null;
this.operator=null;
this.writeSecondNumber=false;
}
public clear(){
if(this.operator!=null){
this.operator=null;
}
else if(this.currentNumber!='0'){
this.currentNumber='0';
}
}
public sqrt(){
this.firstNumber=Math.sqrt(this.firstNumber)
return this.firstNumber;
}
}
|
e8c20ae55d4f8ad5ad4748cf341f03990a4971b0
|
TypeScript
|
carolinamenezes/store-framework-course
|
/course/steps/pdp/index.ts
| 2.640625
| 3
|
export default {
tests: [
{
description: 'Getting the file',
failMsg: `You didn't provide a 'product.jsonc' file`,
test: async ({ ctx }) => {
ctx.pdp = await ctx.getFile('store/blocks/product.jsonc')
return true
},
},
{
description: 'Code compilation',
failMsg: "There's something wrong with your `product.jsonc` file",
test: ({ ctx }) => {
ctx.blocks = ctx.parseJsonc(ctx.pdp)
return true
},
},
{
description: 'Crete a product template page',
failMsg: "You didn't use a `store.product`",
test: ({ ctx }) => {
ctx.productBlock = ctx.blocks?.['store.product']
return !!ctx.productBlock
},
},
{
description: 'Create a main row inside the product page',
failMsg: "You didn't use nor defined a `flex-layout.row` in your product page",
test: ({ ctx }) => {
const {
ramda: { find },
} = ctx
const used = !!find<string>(elem => elem.includes('flex-layout.row'), ctx.productBlock.children)
ctx.mainRow = ctx.blocks?.[find<string>(elem => elem.includes('flex-layout.row'), Object.keys(ctx.blocks)) as string]
const defined = !!ctx.mainRow
return used && defined
},
},
{
description: 'Define two columns inside the main row',
failMsg: "There aren't two `flex-layout.col` inside your `flex-layout.row`",
test: ({ ctx }) => {
const {
mainRow: { children },
ramda: { find },
} = ctx
return children.length === 2 && !find((elem: string) => !elem.includes('flex-layout.col'), children)
},
},
{
description: 'Define `product-images` on the left column',
failMsg: "You didn't define `product-images` on the left column",
test: ({ ctx }) => {
ctx.leftCol = ctx.blocks?.[ctx.mainRow.children[0]]
return ctx.leftCol.children[0].includes('product-images')
},
},
{
description: 'Define `product-name`, `product-price` and `buy-button` on the right column',
failMsg: "You didn't define `product-name`, `product-price` and `buy-button` on the right column",
test: ({ ctx }) => {
ctx.rightCol = ctx.blocks?.[ctx.mainRow.children[1]]
const {
rightCol: { children },
} = ctx
return (
children.includes('product-name') && children.includes('product-price') && children.includes('buy-button')
)
},
},
{
description: 'Control stretch and alignment of right column',
failMsg: "You didn't use the props `preventVerticalStretch` and `verticalAlign`",
test: ({ ctx }) => {
const {
rightCol: { props: rightColProps },
} = ctx
return rightColProps.verticalAlign === 'middle' && rightColProps.preventVerticalStretch
},
},
{
description: 'Define `product-price` with props',
failMsg: "You didn't define `product-price` or defined the expected props",
test: ({ ctx }) => {
const {
ramda: { find, keys },
} = ctx
const productPriceId = find(elem => (elem as any).includes('product-price'), keys(ctx.blocks))
if (!productPriceId) {
return false
}
const { props: productPriceProps } = ctx.blocks?.[productPriceId]
return productPriceProps.showSavings && productPriceProps.showListPrice
},
},
],
} as TestCase
|
acd5aa2893b372228c76b4ba4ccc569657bb15d6
|
TypeScript
|
BitGo/BitGoJS
|
/modules/sdk-coin-trx/src/lib/keyPair.ts
| 2.59375
| 3
|
import { bip32 } from '@bitgo/utxo-lib';
import { randomBytes } from 'crypto';
import {
AddressFormat,
DefaultKeys,
isPrivateKey,
isPublicKey,
isSeed,
KeyPairOptions,
Secp256k1ExtendedKeyPair,
} from '@bitgo/sdk-core';
import * as Utils from './utils';
const DEFAULT_SEED_SIZE_BYTES = 16;
/**
* Tron keys and address management.
*/
export class KeyPair extends Secp256k1ExtendedKeyPair {
/**
* Public constructor. By default, creates a key pair with a random master seed.
*
* @param {KeyPairOptions} source Either a master seed, a private key (extended or raw), or a public key
* (extended, compressed, or uncompressed)
*/
constructor(source?: KeyPairOptions) {
super(source);
if (!source) {
const seed = randomBytes(DEFAULT_SEED_SIZE_BYTES);
this.hdNode = bip32.fromSeed(seed);
} else if (isSeed(source)) {
this.hdNode = bip32.fromSeed(source.seed);
} else if (isPrivateKey(source)) {
super.recordKeysFromPrivateKey(source.prv);
} else if (isPublicKey(source)) {
super.recordKeysFromPublicKey(source.pub);
} else {
throw new Error('Invalid key pair options');
}
if (this.hdNode) {
this.keyPair = Secp256k1ExtendedKeyPair.toKeyPair(this.hdNode);
}
}
/**
* Tron default keys format is raw private and uncompressed public key
*
* @returns {DefaultKeys} The keys in the protocol default key format
*/
getKeys(): DefaultKeys {
return {
pub: this.getPublicKey({ compressed: false }).toString('hex').toUpperCase(),
prv: this.getPrivateKey()?.toString('hex').toUpperCase(),
};
}
/**
* Get a public address in the specified format, or in base58 if none is provided.
*
* @param {AddressFormat} format The address specified format
* @returns {string} The public address in the specified format
*/
getAddress(format?: AddressFormat): string {
const { pub } = this.getKeys();
// These are custom Tron methods. They can probably be replaced with other methods or libraries
const addressBytes = Utils.getRawAddressFromPubKey(Buffer.from(pub, 'hex'));
if (!format || format === AddressFormat.base58) {
// Default address are in hex
return Utils.getBase58AddressFromByteArray(addressBytes);
} else if (format === AddressFormat.hex) {
return Utils.getHexAddressFromByteArray(addressBytes);
}
throw new Error('Unsupported address format');
}
/**
* Generates a signature for an arbitrary string with the current private key using keccak256
* hashing algorithm. Throws if there is no private key.
*
* @param {string} message to produce a signature for
* @returns {Buffer} The signature as a buffer
*/
signMessage(message: string): Buffer {
const messageToSign = Buffer.from(message).toString('hex');
const { prv } = this.getKeys();
if (!prv) {
throw new Error('Missing private key');
}
const signature = Utils.signString(messageToSign, prv, true).replace(/^0x/, '');
return Buffer.from(signature, 'hex');
}
/**
* Verifies a message signature using the current public key.
*
* @param {string} message signed
* @param {Buffer} signature to verify
* @returns {boolean} True if the message was signed with the current key pair
*/
verifySignature(message: string, signature: Buffer): boolean {
const messageToVerify = Buffer.from(message).toString('hex');
const address = this.getAddress(AddressFormat.base58);
return Utils.verifySignature(messageToVerify, address, signature.toString('hex'), true);
}
}
|
01af3710eb92bcd00abefb7496cdb2163c60d987
|
TypeScript
|
gitsupportting/ReactNative_GraphQL
|
/apps/mobile-v1/src/lib/utils/redux/dateTransformer.ts
| 2.859375
| 3
|
import { parseISO, isValid } from 'date-fns';
import produce from 'immer';
import { createTransform } from 'redux-persist';
const convertDateToStringRecursive = <T extends { [key: string]: unknown }>(obj: T): T =>
produce(obj, (draft: any) => {
Object.keys(draft).forEach(key => {
const value = draft[key];
if (typeof value === 'string' && isValid(parseISO(value))) {
draft[key] = { __DATE: value };
} else if (value instanceof Date) {
draft[key] = isValid(value) ? { __DATE: value.toISOString() } : undefined;
} else if (isObject(value) && value !== null) {
draft[key] = convertDateToStringRecursive(value);
}
});
});
const convertStringToDateRecursive = <T extends { [key: string]: unknown }>(obj: T): T =>
produce(obj, (draft: any) => {
Object.keys(draft).forEach(key => {
const value = draft[key];
if (isObject(value) && value !== null) {
if ('__DATE' in value) {
draft[key] = parseISO(value.__DATE as string);
} else {
draft[key] = convertStringToDateRecursive(value);
}
}
});
});
const isObject = (input: unknown): input is { [key: string]: unknown } => typeof input === 'object';
const dateTransformer = createTransform(
(inboundState: unknown) => {
if (isObject(inboundState) && inboundState) {
return convertDateToStringRecursive(inboundState);
}
return inboundState;
},
outboundState => {
if (isObject(outboundState) && outboundState) {
return convertStringToDateRecursive(outboundState);
}
return outboundState;
},
);
export default dateTransformer;
|
f67fe86496d466ab906152b9a2cda61165ff1dab
|
TypeScript
|
crabmusket/deno_pull_streams
|
/lib/types.ts
| 4.0625
| 4
|
/**
* A Source is a producer of values for a pull stream. It is a function that you
* may call in one of two ways:
* 1. Provide the first parameter, `end`, to signal that no more values will be
* requested from this source. This lets a consumer terminate a producer.
* 2. Provide the second parameter, `cont`, a continuation to be called when the
* source produces its next value.
* Sources are designed to be asynchronous by nature. Therefore the only way to
* "pull" data from them is by passing a continuation.
*/
export type Source<Value> = (end: End, cont: Cont<Value>) => void;
/**
* A Cont (continuation) is a callback that receives data from a Source. It may,
* however, be called with an End value, if the Source has run out of values.
*/
export type Cont<Value> = (end: End, value: Value | undefined) => void;
/**
* A Sink is a function that "consumes" a Source and may produce a Result at some
* point. Sinks are in control of the stream's flow: they must call the `read`
* function to receive a new value each time they want one. They control the pacing
* of data flow.
*/
export type Sink<Value, Result = void> = (read: Source<Value>) => Result;
/**
* A Through is a transformer from Source to Source. It might change the type of
* the data that flows through it from Before to After.
*/
export type Through<Before, After = Before> = (
read: Source<Before>
) => Source<After>;
/**
* End is the signal propagated to end the stream. Sources, Sinks, and Throughs
* can all cause a pull stream to terminate by passing an end signal.
* `null` means "continue as normal".
* `true`, when passed to a Source, means "the consumer requires no more values";
* and when passed to a Sink, it means "the source has no more values".
* `Error` signals there was some error.
*/
export type End = null | true | Error;
|
f5625be8d573dcbbe915a431f440176b37ee6ccb
|
TypeScript
|
dev2team/ibzocr
|
/app_ocrweb/src/utils/json-http/json-http.ts
| 2.609375
| 3
|
import Jsonp from '../jsonp/jsonp';
/**
* 示例数请求对象
*
* @export
* @class AppSamle
*/
export default class JsonHttp {
/**
* 获取 Http 单例对象
*
* @static
* @returns {Http}
* @memberof SampleHttp
*/
public static getInstance(): JsonHttp {
return new JsonHttp();
}
/**
* jsonp跨域请求对象
*
* @type {Jsonp}
* @memberof JsonHttp
*/
public jsonpHttp: Jsonp = new Jsonp();
/**
* 请求
*
* @param {string} url
* @returns {Promise<any>}
* @memberof SampleHttp
*/
public http(url: string, params: any = {}): Promise<any> {
return new Promise((resolve: any, reject: any) => {
let action = url.substring(url.lastIndexOf('/') + 1);
let type: string = url.substring(url.indexOf('/') + 1, url.indexOf('/', url.indexOf('/') + 1));
url = `./assets/sampledata/${url.substring(0, url.lastIndexOf('/'))}.json`;
let fileName: string = url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.'));
this.jsonp(url, fileName).then((data: any) => {
if (Object.is(type, 'app')) {
let result = this.setResultData(data);
resolve(result);
} else {
let result: Promise<any>;
if (Object.is(type, 'ctrl')) {
result = this.ctrlHttp(url, action, data, params);
} else {
result = this.DEHttp(url, action, data, params);
}
result.then((response: any) => {
resolve(this.setResultData(response));
}).catch((response: any) => {
reject(response);
})
}
}).catch((error: any) => {
reject(error);
});
});
}
/**
* 实体部件类请求
*
* @param {string} url
* @param {string} action
* @param {*} data
* @param {*} [params={}]
* @memberof SampleHttp
*/
public DEHttp(url: string, action: string, data: any, params: any = {}): Promise<any> {
return new Promise((resolve: any, reject: any) => {
let ctrlName: string = url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.'));
url = url.substring(0, url.lastIndexOf('/'));
let deName: string = url.substring(url.lastIndexOf('/') + 1);
url += `/${deName}.json`;
this.jsonp(url, deName).then((json: any) => {
resolve(this.getResultData(ctrlName, json, data, params));
}).catch((error: any) => {
reject(error);
});
});
}
/**
* 获取返回数据
*
* @param {string} ctrlName
* @param {any[]} items
* @param {*} mode
* @returns {*}
* @memberof SampleHttp
*/
public getResultData(ctrlName: string, items1: any[] = [], items2: any[] = [], params: any = {}): any {
let data: any = {};
if (ctrlName.endsWith('form')) {
if (params.srfkey) {
let index = items1.findIndex((item: any) => Object.is(item.srfkey, params.srfkey));
if (index >= 0) {
Object.assign(data, items1[index]);
data.srfuf = "1";
}
}
}
if (ctrlName.endsWith('grid') || ctrlName.endsWith('list') || ctrlName.endsWith('dataview')) {
let items: any[] = [];
items1.forEach((item1: any) => {
let data: any = {};
items2.forEach((item2: any) => {
data[item2.name] = item1[item2.valueitem] != undefined ? item1[item2.valueitem] : null;
});
items.push(data);
});
Object.assign(data, { records: items, total: items1.length });
}
return data;
}
/**
* ctrl类请求
*
* @param {string} url
* @param {string} action
* @param {*} data
* @param {*} [params={}]
* @returns {Promise<any>}
* @memberof SampleHttp
*/
public ctrlHttp(url: string, action: string, data: any, params: any = {}): Promise<any> {
return new Promise((resolve: any, reject: any) => {
let ctrlName: string = url.substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.'));
if (ctrlName.endsWith('appmenu')) {
resolve(data);
}
if (ctrlName.endsWith('treeview')) {
if (params.srfnodeid) {
let index: number = data.findIndex((item: any) => Object.is(item.id, params.srfnodeid));
if(index >= 0) {
let node: any = data[index];
let items: any[] = [];
node.childNode.forEach((id: string) => {
let item = data.find((item: any) => Object.is(item.id, id));
items.push(item);
});
resolve(items);
}
}
}
});
}
/**
* 请求
*
* @param {string} url
* @param {string} callbackName
* @returns
* @memberof SampleHttp
*/
public jsonp(url: string, callbackName: string) {
return new Promise((resolve: any, reject: any) => {
this.jsonpHttp.jsonp(url, {
callbackName: callbackName
}).then((json: any) => {
resolve(json);
}).catch((error: any) => {
reject(error);
});
});
}
/**
* 设置返回数据
*
* @param {*} resolve
* @param {*} data
* @memberof SampleHttp
*/
public setResultData(data: any): any {
return {
status: 200,
data: data,
statusText: "OK"
};
}
}
|
2631781354ee713d3df656dcf9ab3ded631cdc1b
|
TypeScript
|
PawelRadawiec/todo-frontend
|
/src/app/store/authentication/authorization.reducer.ts
| 2.75
| 3
|
import * as authorizationActions from './authorization.actions';
import {AuthorizationState} from '../state/app.state';
export const initialState: AuthorizationState = {
isAuthenticated: false
};
export function reducer(state = initialState, action: authorizationActions.AuthorizationActions) {
switch (action.type) {
case authorizationActions.AUTHENTICATION_RESPONSE: {
return {
...state,
isAuthenticated: true
};
}
case authorizationActions.AUTHENTICATION_CLEAR: {
return {
...state,
isAuthenticated: false
};
}
case authorizationActions.AUTHENTICATION_SUCCESS: {
return {
...state,
isAuthenticated: true
};
}
}
return state;
}
|
3e636dfd0dd243f4f779ed02e0a637b6176e20ca
|
TypeScript
|
srghma/ramda-asserters
|
/src/assertNotNil.ts
| 2.828125
| 3
|
import { isNil } from 'ramda'
export default function assertNotNil<X>(x: X | null | undefined): X | never {
if (!isNil(x)) {
return x as any
}
const error = new Error(`Got unexpected ${x}`)
error.name = 'Assert not nil error'
throw error
}
|
53890fbd4532dec6a1ee305d0e90133f8c4a8fdf
|
TypeScript
|
7affer/raycast
|
/src/scripts/controls.ts
| 2.65625
| 3
|
export class Controls {
public rotateleft: boolean = false
public rotateright: boolean = false
public forward: boolean = false
public backward: boolean = false
public run: boolean = false
public strafeleft: boolean = false
public straferight: boolean = false
public mouserotateleft: number = 0
public mouserotateright: number = 0
public shoot: boolean = false
public mousemove(e: MouseEvent) {
if (e.movementX < 0) {
this.mouserotateleft = -e.movementX / 5
this.mouserotateright = 0
} else if (e.movementX > 0) {
this.mouserotateleft = 0
this.mouserotateright = e.movementX / 5
}
}
public resetmouserotate() {
this.mouserotateleft = 0
this.mouserotateright = 0
}
public keydown(e: KeyboardEvent) {
if (e.keyCode == 17) this.shoot = true
if (e.keyCode == 37) this.rotateleft = true
if (e.keyCode == 68) this.strafeleft = true
if (e.keyCode == 39) this.rotateright = true
if (e.keyCode == 65) this.straferight = true
if (e.keyCode == 38 || e.keyCode == 87) this.forward = true
if (e.keyCode == 40 || e.keyCode == 83) this.backward = true
this.run = e.shiftKey
}
public touchstart(e: TouchEvent, canvas: HTMLCanvasElement) {
var t = e.touches[0];
this.touchend(e);
if (t.pageY < canvas.height * 0.5) {
this.shoot = true
} else {
if (t.pageX < window.innerWidth * 0.333) this.rotateleft = true
else if (t.pageX < window.innerWidth * 0.666) this.forward = true
else this.rotateright = true
}
e.preventDefault();
e.stopPropagation();
}
public touchend(e: TouchEvent) {
this.rotateleft = false
this.rotateright = false
this.forward = false
e.preventDefault();
e.stopPropagation();
}
public keyup(e: KeyboardEvent) {
if (e.keyCode == 37) this.rotateleft = false
if (e.keyCode == 68) this.strafeleft = false
if (e.keyCode == 39) this.rotateright = false
if (e.keyCode == 65) this.straferight = false
if (e.keyCode == 38 || e.keyCode == 87) this.forward = false
if (e.keyCode == 40 || e.keyCode == 83) this.backward = false
this.run = e.shiftKey
}
public bindevents(doc: HTMLDocument, canvas: HTMLCanvasElement) {
doc.addEventListener('keydown', (e) => this.keydown(e), false)
doc.addEventListener('keyup', (e) => this.keyup(e), false)
doc.addEventListener('pointerlockchange', (e) => { this.lockChangeAlert(doc, canvas) }, false)
doc.addEventListener('mozpointerlockchange', (e) => { this.lockChangeAlert(doc, canvas) }, false)
canvas.addEventListener('touchstart', (e) => { this.touchstart(e, canvas) }, false)
canvas.addEventListener('touchend', (e) => { this.touchend(e) }, false)
canvas.addEventListener('click', (e) => {
canvas.requestPointerLock = canvas.requestPointerLock || (<any>canvas).mozRequestPointerLock
canvas.requestPointerLock()
this.shoot = true
}, false)
}
private mousemovefunction = (e: MouseEvent) => this.mousemove(e)
private lockChangeAlert(doc: HTMLDocument, canvas: HTMLElement) {
let canvaselement = <HTMLCanvasElement>document.getElementById('hudcanvas')
if (doc.pointerLockElement === canvaselement || (<any>document).mozPointerLockElement === canvas) {
doc.addEventListener("mousemove", this.mousemovefunction, false)
} else {
doc.removeEventListener("mousemove", this.mousemovefunction, false)
}
}
}
|
12c903edc765708f8ae1e0f05b29cabfe250477a
|
TypeScript
|
kimkanu/hyperbolic-minesweeper
|
/app/utils/cycle.ts
| 4.03125
| 4
|
export class Cycle<T> {
constructor(public inner: T[] = []) {}
get(index: number): T {
if (index < 0 || index >= this.inner.length) {
const remainder =
index - this.inner.length * Math.floor(index / this.inner.length);
return this.get(remainder);
}
return this.inner[index];
}
get length() {
return this.inner.length;
}
// [0, 1, 2, 3, 4, 5] |> .rotate(2) |> [2, 3, 4, 5, 0, 1]
rotated(index: number = 0): T[] {
if (index < 0 || index >= this.inner.length) {
const remainder =
index - this.inner.length * Math.floor(index / this.inner.length);
return this.rotated(remainder);
}
return [...this.inner.slice(index), ...this.inner.slice(0, index)];
}
rotate(index: number = 0) {
this.inner = this.rotated(index);
return this.inner;
}
// [0, 1, 2, 3, 4, 5] |> .reverse(2) |> [4, 3, 2, 1, 0, 5]
reversed(index: number = 0): T[] {
const reversed = this.inner.slice(0).reverse();
return new Cycle(reversed).rotated(2 * (length - index) - 1);
}
reverse(index: number = 0) {
this.inner = this.reversed(index);
return this.inner;
}
}
|
a091c8b214f46487afc734d15a100e3c08654214
|
TypeScript
|
mojaloop/fraud_risk_management
|
/predicate-builder-service/src/services/kafka.service.ts
| 2.546875
| 3
|
import * as kafka from 'kafka-node';
import { config } from '../config';
export class KafkaService {
ready = false;
producer: kafka.Producer;
constructor() {
const kafkaClient = new kafka.KafkaClient({
kafkaHost: config.kafkaEndpoint,
});
this.producer = new kafka.Producer(kafkaClient, { partitionerType: 2 });
this.producer.on('ready', () => (this.ready = true));
}
async log(
messageType: 'Error' | 'Warning' | 'Info' | 'Debug',
message: string,
) {
switch (messageType) {
case 'Error':
console.error(message);
break;
case 'Warning':
console.warn(message);
break;
case 'Info':
case 'Debug':
console.log(message);
break;
}
new Promise((resolver) => {
this.producer.send(
[
{
topic: config.logTopic,
messages: [
`[Predicate Builder Service][${messageType}] ${message}`,
],
partition: config.partition,
},
],
() => resolver(undefined),
);
});
}
async publishResult(topic: string, resultValue: string) {
const result = `{"topic":"${topic}","result": "${resultValue}"}`;
return new Promise((resolve) => {
this.producer.send(
[
{
topic: topic,
messages: [result],
partition: config.partition,
},
],
(err) => {
if (err) {
this.log(
'Error',
`Error while sending result of blocking with message: \r\n${err}`,
);
}
resolve(undefined);
},
);
});
}
}
|
4685ca6a64a945e88dd12e2ba81df0f93283d230
|
TypeScript
|
Joan1106web/component
|
/fileList/src/fileList/utils.ts
| 2.53125
| 3
|
// 公用方法
export const ImagesFormat = {
DOC: ['doc', 'docx'],
PNG: ['png', 'psd', 'gif'],
XLS: ['xls']
}
/**
* 获取带前缀类名
* @param {string} cls
* @param {string} prefix
* @returns {string}
*/
export function getPrefixCls(cls: string = '', prefix: string = 'file-list') {
return `${prefix}-${cls}`;
}
export const noop = () => { };
|
0b98598d02caa4b6cda7627143e9ab1961d0c98d
|
TypeScript
|
nbever/grand-sumo-showdown
|
/src/app/services/banzuke.service.ts
| 2.671875
| 3
|
import {Injectable} from '@angular/core';
import isNil from 'lodash-es/isNil';
import isNan from 'lodash-es/isNan';
import RIKISHI_CARDS from '../data/rikishi_cards';
import Banzuke from '../model/banzuke';
import BanzukeEntry from '../model/banzukeEntry';
import Rank from '../model/rank';
import Bout from '../model/bout';
import Result from '../model/Result';
import SIDE from '../model/side';
@Injectable()
class BanzukeService {
_banzuke: Banzuke;
constructor() {
}
get banzuke() {
if ( isNil( this._banzuke ) ) {
this._banzuke = this.initializeBanzuke();
}
return this._banzuke;
}
initializeBanzuke = (): Banzuke => {
const banzuke: Banzuke = new Banzuke();
for ( const key in RIKISHI_CARDS ) {
const entry: BanzukeEntry = this.buildBanzukeEntry( RIKISHI_CARDS[key], key );
const result: boolean = banzuke.addEntry( entry );
if ( result === false ) {
entry.side = SIDE.WEST;
banzuke.addEntry( entry );
}
}
banzuke.list.forEach( (entry: BanzukeEntry, index: number) => {
entry.numericalRank = index;
});
return banzuke;
}
buildBanzukeEntry = (rikishiData: any, name: string): BanzukeEntry => {
const lastRank = rikishiData['Last Rank'];
const rank: Rank = this.buildRank( lastRank );
const sideChar = lastRank.substring(lastRank.length - 2);
const side: SIDE = SIDE.EAST;
let number: number = parseInt( lastRank.substring(1), 10 );
if (isNan(number)) {
number = parseInt( lastRank.substring(2), 10);
}
const entry: BanzukeEntry = new BanzukeEntry( name, rank, number, side );
return entry;
}
buildRank = (lastRank: String): Rank => {
if ( lastRank.startsWith('ms') ) {
return Rank.MAKUSHITA;
}
const rankChar = lastRank.substring(0, 1).toUpperCase();
let rank: Rank = Rank.JURYO;
switch ( rankChar ) {
case Rank.MAEGASHIRA:
rank = Rank.MAEGASHIRA;
break;
case Rank.KOMUSUBI:
rank = Rank.KOMUSUBI;
break;
case Rank.SEKIWAKE:
rank = Rank.SEKIWAKE;
break;
case Rank.OZEKI:
rank = Rank.OZEKI;
break;
case Rank.YOKOZUNA:
rank = Rank.YOKOZUNA;
break;
case Rank.JURYO:
rank = Rank.JURYO;
break;
default:
rank = Rank.MAKUSHITA;
break;
}
return rank;
}
getWinTotal = (rikishi: BanzukeEntry): number => {
return this.countResults(rikishi, true);
}
getLossTotal = (rikishi: BanzukeEntry): number => {
return this.countResults(rikishi, false);
}
countResults = (rikishi: BanzukeEntry, wins: boolean = true): number => {
const results = rikishi.results.map( (result: Result): number => {
if (result.winner === rikishi.name && wins === true) {
return 1;
} else if (result.loser === rikishi.name && wins !== true) {
return 1;
}
return 0;
}).reduce( (total: number, win: number) => {
return total + win;
});
return results;
}
getLeaders = (): BanzukeEntry[] => {
const leaderList = this.banzuke.list.concat().sort( (rikishiA: BanzukeEntry, rikishiB: BanzukeEntry) => {
const winsA: number = this.getWinTotal(rikishiA);
const winsB: number = this.getWinTotal(rikishiB);
return winsB - winsA;
});
return leaderList;
}
reportResult = (bout: Bout) => {
// find the banzuke entries
const entries: BanzukeEntry[] = this.banzuke.list.filter( (entry: BanzukeEntry) => {
return (entry.name === bout.eastRikishi || entry.name === bout.westRikishi);
});
entries.forEach( (entry: BanzukeEntry) => {
entry.setResult(bout.day - 1, bout.result);
});
}
}
export default BanzukeService;
|
3c3965ef5fac9e8c8e46b047663d219beac924f2
|
TypeScript
|
marcobrasci1986/angular-sandbox
|
/src/app/person/person.component.ts
| 3.03125
| 3
|
import {Component, OnInit} from '@angular/core';
export interface PersonProperties {
name: string;
age: number;
}
export class Person implements PersonProperties {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
@Component({
selector: 'app-person',
templateUrl: './person.component.html',
styleUrls: ['./person.component.css']
})
export class PersonComponent implements OnInit {
person: Person = new Person('John', 20);
constructor() {
}
ngOnInit() {
}
changeName() {
console.log('Show person');
// Non immutable way
this.person.name = 'Marco';
// this.person = new Person('Marco', 32);
}
}
|
5493d980c231f55120df5a6c5f0103115767ebf6
|
TypeScript
|
jovercao/lubejs
|
/src/orm/modeler/entity-builder.ts
| 2.78125
| 3
|
import { Scalar, Select } from "../../core";
import { Entity, EntityConstructor } from "../entity";
import { ColumnMetadata, EntityMetadata, HasManyMetadata, HasOneMetadata, IndexMetadata, KeyMetadata, TableEntityMetadata } from "../metadata";
import { DataTypeOf, ScalarDataType } from "../data-types";
import { selectProperty } from "../util";
import { ContextBuilder } from "./context-builder";
import { HasManyBuilder } from "./has-many-builder";
import { HasOneBuilder } from "./has-one-builder";
import { IndexBuilder } from "./index-builder";
import { PropertyBuilder } from "./property-builder";
import { TableKeyBuilder } from "./table-key-builder";
/**
* 实体构造器
* 列可以重复获取,关系不可以重复获取
*/
export class EntityBuilder<T extends Entity> {
constructor(
protected contextBuilder: ContextBuilder,
public readonly metadata: EntityMetadata
) {}
protected readonly relationMaps: Map<
string,
HasOneBuilder<T, Entity> | HasManyBuilder<T, Entity>
> = new Map();
protected readonly columnMaps: Map<string, PropertyBuilder<T>> = new Map();
private assertRelation(property: string) {
if (this.relationMaps.has(property) || this.columnMaps.has(property)) {
throw new Error(`Property or Relation ${property} is declared`);
}
}
private assertKind() {
if (this.metadata.kind) {
throw new Error('Not allow set a entity kind twice in modeling.');
}
}
asTable(name?: string): EntityBuilder<T>;
asTable(build: (builder: EntityBuilder<T>) => void): ContextBuilder;
asTable(
name: string,
build: (builder: EntityBuilder<T>) => void
): ContextBuilder;
asTable(
nameOrBuild?: string | ((builder: EntityBuilder<T>) => void),
build?: (builder: EntityBuilder<T>) => void
): EntityBuilder<T> | ContextBuilder {
// this.assertKind();
let tableName: string | undefined;
if (typeof nameOrBuild === 'string') {
tableName = nameOrBuild;
} else if (typeof nameOrBuild === 'function') {
build = nameOrBuild;
}
const tableMetadata = this.metadata as TableEntityMetadata;
this.metadata.kind = 'TABLE';
tableMetadata.dbName = tableName || this.metadata.className;
this.metadata.readonly = false;
if (build) {
build(this);
return this.contextBuilder;
}
return this;
}
// asTable(tableName?: string): Omit<this, 'asTable' | 'asView' | 'asQuery'> {
// }
// asView(body: Select<T>): Omit<this, 'asTable' | 'asView' | 'asQuery'>
// asView(viewName: string, body: Select<T>): Omit<this, 'asTable' | 'asView' | 'asQuery'>
// asView(bodyOrViewName: Select<T> | string, body?: Select<T>): Omit<this, 'asTable' | 'asView' | 'asQuery'> {
// // this.assertKind();
// let viewName: string;
// if (!body) {
// body = bodyOrViewName as Select<T>;
// viewName = this.metadata.class.name;
// } else {
// viewName = bodyOrViewName as string;
// }
// this.metadata.kind = 'VIEW';
// this.metadata.viewName = viewName;
// this.metadata.body = body;
// this.metadata.readonly = true;
// return this;
// }
// asQuery(sql: Select<T>): Omit<this, 'asTable' | 'asView' | 'asQuery'> {
// // this.assertKind();
// if (this.metadata.kind) {
// throw new Error('Not allow change entity kind twice in modeling.')
// }
// this.metadata.kind = 'QUERY';
// this.metadata.sql = sql;
// this.metadata.readonly = true;
// return this;
// }
// hasBody(body: Select<T>) {
// if (this.metadata.kind !== 'VIEW') {
// throw new Error(`Not need query sql when entity is not View.`)
// }
// this.metadata.body = body;
// }
// hasSql(sql: Select<T>) {
// if (this.metadata.kind !== 'QUERY') {
// throw new Error(`Not need query sql when entity is not Query.`)
// }
// this.metadata.sql = sql;
// }
/**
* 实体声明为视图
*/
asView(body: Select<T>): this;
asView(body: Select<T>, build: (builder: this) => void): ContextBuilder;
asView(name: string, body: Select<T>): this;
asView(
name: string,
body: Select<T>,
build: (builder: this) => void
): ContextBuilder;
asView(
nameOrBody: string | Select<T>,
bodyOrBuild?: Select<T> | ((builder: this) => void),
build?: (builder: this) => void
): this | ContextBuilder {
let name: string | undefined;
let body: Select<T>;
if (typeof nameOrBody === 'string') {
name = nameOrBody;
body = bodyOrBuild as Select<T>;
} else {
body = nameOrBody;
build = bodyOrBuild as (builder: this) => void;
}
this.metadata.kind = 'VIEW';
this.metadata.dbName = name || this.metadata.className;
this.metadata.readonly = true;
this.metadata.body = body;
if (build) {
build(this);
return this.contextBuilder;
}
return this;
}
/**
* 实体声明为视图
*/
asQuery(sql: Select<T>): this;
asQuery(sql: Select<T>, build: (builder: this) => void): ContextBuilder;
asQuery(
sql: Select<T>,
build?: (builder: this) => void
): this | ContextBuilder {
this.metadata.kind = 'QUERY';
this.metadata.readonly = true;
this.metadata.sql = sql;
if (build) {
build(this);
return this.contextBuilder;
}
return this;
}
hasName(name: string): this {
this.metadata.dbName = name;
return this;
}
// /**
// * 声明视图选择语句
// * 声明在函数中是为了避免循环引用时引发异常
// */
// hasBody(body: Select<T>): this {
// this.metadata.body = body;
// return this;
// }
// withSql(sql: Select<T>): this {
// this.metadata.sql = sql;
// return this;
// }
/**
* 声明主键
*/
hasKey<P extends Scalar>(selector: (p: Required<T>) => P): TableKeyBuilder;
hasKey<P extends Scalar>(
constraintName: string,
selector: (p: Required<T>) => P
): TableKeyBuilder;
hasKey<P extends Scalar>(
nameOrSelector: string | ((p: Required<T>) => P),
selector?: (p: Required<T>) => P
): TableKeyBuilder {
let constraintName: string | undefined;
if (typeof nameOrSelector === 'function') {
selector = nameOrSelector;
} else {
constraintName = nameOrSelector;
}
const property: string = selectProperty(selector!);
if (!property) {
throw new Error('Please select a property');
}
if (!this.metadata.key) {
this.metadata.key = {} as KeyMetadata;
}
this.metadata.key = {
property,
} as KeyMetadata;
if (constraintName) {
this.metadata.key!.constraintName = constraintName;
}
// this.metadata.addIndex({
// name: undefined,
// properties: [property],
// columns: null,
// isUnique: true,
// isClustered
// });
return new TableKeyBuilder(this, this.metadata.key);
}
hasIndex(name: string): IndexBuilder<T> {
// if (!name) {
// name = `IX_${this.metadata.tableName || this.metadata.className}_${index}`
// }
let metadata = this.metadata.getIndex(name);
if (!metadata) {
metadata = { name } as IndexMetadata;
this.metadata.addIndex(metadata);
}
const builder = new IndexBuilder(this.contextBuilder, this, metadata);
return builder;
}
/**
* 声明一个单一引用属性
* @param selector
* @param type 因typescript反射机制尚不完善,因此无法获取到属性类型,因而需要传递该属性类型参数
* @returns
*/
// hasOne<D extends Entity>(
// name: string,
// type: Constructor<D>
// ): HasOneBuilder<T, D>
hasOne<D extends Entity>(
propertySelector: (p: Required<T>) => D,
type: EntityConstructor<D>
): HasOneBuilder<T, D>;
hasOne<D extends Entity>(
propertyOrSelector: string | ((p: Required<T>) => D),
type: EntityConstructor<D>
): HasOneBuilder<T, D> {
const property: string =
typeof propertyOrSelector === 'function'
? selectProperty(propertyOrSelector)
: propertyOrSelector;
if (!property) {
throw new Error(
`Entity ${
this.metadata.class!.name
} hasOne selector mast return a property, example property name "user", 'builder.hasOne(p => p.user)'`
);
}
this.assertRelation(property);
const metadata: HasOneMetadata = {
property,
referenceClass: type,
// 追加关联关系
referenceEntity: this.contextBuilder.entity(type).metadata,
} as any;
const builder = new HasOneBuilder<T, D>(
this.contextBuilder,
this,
metadata
);
this.relationMaps.set(property, builder);
this.metadata.addRelation(metadata as HasOneMetadata);
return builder;
}
/**
* 声明一个集体属性
* @param selector
* @param type 因typescript反射机制尚不完善,因此无法获取到属性类型,因而需要传递该属性类型参数
* @returns
*/
hasMany<D extends Entity>(
selector: (p: Required<T>) => D[],
type: EntityConstructor<D>
): HasManyBuilder<T, D> {
const property: string = selectProperty(selector);
if (!property)
throw new Error(
`Entity ${
this.metadata.class!.name
} hasMany selector mast select a property like this: '.hasMany(p => p.listPropery)'.`
);
this.assertRelation(property);
const metadata: Partial<HasManyMetadata> = {
referenceClass: type,
referenceEntity: this.contextBuilder.entity(type)
.metadata as TableEntityMetadata,
property: property,
isDetail: false,
isImplicit: false,
};
this.contextBuilder.entity(type);
const builder = new HasManyBuilder<T, D>(
this.contextBuilder,
this,
metadata
);
this.relationMaps.set(property, builder);
this.metadata.addRelation(metadata as HasManyMetadata);
return builder;
}
// TODO: 待添加种子数据结构化初始
/**
* 种子数据,必须指定所有字段值,包括Identity字段
* 暂时只支持,数据表对象新增
* 重复调用则追加
*/
// hasData(data: T[]): this
// hasData(data: any[]): this
hasData(data: Record<string, Scalar>[]): this {
// if (this.metadata.kind !== "TABLE") {
// throw new Error("Seed data is allowed only on table.");
// }
if (data.length === 0) {
throw new Error(
`Entity ${this.metadata.class!.name} hasData seed data is empty.`
);
}
if (!this.metadata.data) this.metadata.data = [];
this.metadata.data.push(...data);
return this;
}
property<P extends Scalar>(
selector: (p: Required<T>) => P,
type: DataTypeOf<P>
): PropertyBuilder<T, P>;
property<P extends Scalar>(
selector: (p: Required<T>) => P,
type: DataTypeOf<P>,
build: (builder: PropertyBuilder<T>) => void
): this;
property<D extends Scalar, P extends keyof T>(
property: string,
type: DataTypeOf<D>
): PropertyBuilder<T, D>;
property<D extends Scalar, P extends keyof T>(
property: string,
type: DataTypeOf<D>,
build: (builder: PropertyBuilder<T>) => void
): this;
property<P extends Scalar>(
propertyOrselector: string | ((p: Required<T>) => P),
type: DataTypeOf<P>,
build?: (builder: PropertyBuilder<T>) => void
): PropertyBuilder<T, P> | this {
const property: string =
typeof propertyOrselector === 'function'
? selectProperty(propertyOrselector)
: propertyOrselector;
if (!property) {
throw new Error(`Please select a property`);
}
let columnBuilder: PropertyBuilder<T, P> | undefined = this.columnMaps.get(
property
) as PropertyBuilder<T, P>;
if (!columnBuilder) {
const metadata: ColumnMetadata<P> = {
kind: 'COLUMN',
property,
type: type as ScalarDataType,
} as ColumnMetadata<P>;
columnBuilder = new PropertyBuilder<T, P>(
this.contextBuilder,
this,
metadata
);
this.columnMaps.set(property, columnBuilder);
this.metadata.addColumn(metadata as ColumnMetadata);
}
if (build) {
build(columnBuilder);
return this;
}
return columnBuilder;
}
hasComment(comment: string): Omit<this, 'hasComment'> {
this.metadata.comment = comment;
return this;
}
/**
* 可将初始化代码写于此处,支持异步方法
*/
async forAsync(action: (builder: this) => Promise<void>): Promise<this> {
await action(this);
return this;
}
}
|
c6d9df3b65cbb268eb6d54a3f575094601f4be73
|
TypeScript
|
future4code/brunoPacheco
|
/semana12/aula3/exDaTarde/src/index.ts
| 2.90625
| 3
|
import { ResidencialClient } from './residencialClient';
import { TradeClient } from './tradeClient';
import { IndustryClient } from './industryClient';
import { ClientManager } from './clientManager';
//clientes residenciais
const client1 = new ResidencialClient("apartamento", "12345678912", "12345678", "bruno", 100,50)
const client2 = new ResidencialClient("casa", "32165498709", "123456789","jorge",99,75)
console.log(client1)
console.log(`O cliente ${client1.clientName} vai pagar R$${client1.calculateBill()}`)
console.log()
console.log(client2)
console.log(`O cliente ${client2.clientName} vai pagar R$${client2.calculateBill()}`)
console.log()
//clientes comerciais
const client11= new TradeClient("lojinha","431287651234","12345654","Lojinha do Jão",88,150)
const client22= new TradeClient("lojinha","431287651234","12345654","Lanchonete do Jão",88,250)
console.log(client11)
console.log(`O cliente ${client11.clientName} vai pagar R$${client11.calculateBill()}`)
console.log()
console.log(client22)
console.log(`O cliente ${client22.clientName} vai pagar R$${client22.calculateBill()}`)
console.log()
//clientes industriais
const client111= new IndustryClient("fábrica","1800","1235442","Tesla",299,500)
const client222= new IndustryClient("fábrica","1900","9876544","CombRex",12,90000)
console.log(client111)
console.log(`O cliente ${client111.clientName} vai pagar R$${client111.calculateBill()}`)
console.log()
console.log(client222)
console.log(`O cliente ${client222.clientName} vai pagar R$${client222.calculateBill()}`)
console.log()
const clientManager = new ClientManager()
clientManager.addClient(client1)
console.log(`A quantidade de clientes é de ${clientManager.getClientsQuantity()}`)
|
57a3821de7bdc997b29ecefee49ad6300d94af3b
|
TypeScript
|
bakuzan/sticky-fingers
|
/src/sudoku/isUnique.ts
| 2.96875
| 3
|
import { SudokuGrid } from './interfaces/SudokuGrid';
import solve from './solve';
export default function isUnique(grid: SudokuGrid) {
const input = grid;
const solved1 = solve(input, { chooseDigit: 'min' });
const solved2 = solve(input, { chooseDigit: 'max' });
for (const s in solved1) {
if (solved2[s] !== solved1[s]) {
return false;
}
}
return true;
}
|
3d9d8a9f004d94a2370085941f290c68aeeee75b
|
TypeScript
|
gunjankarun/just50words
|
/src/app/service/audio.service.ts
| 2.53125
| 3
|
import { Injectable, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { ConfigService } from './config.service';
/**
* This service handles audio related tasks. It is the central location to make global changes to audio events
*
* @export
* @class AudioService
*/
@Injectable()
export class AudioService implements OnDestroy {
mute_all_sound = false;
global_sound_volume = 1;
config_subscription: Subscription;
constructor(private _configService: ConfigService) {
this.mute_all_sound = _configService.config.mute_all_sound;
this.config_subscription = this._configService.cast.subscribe(
new_config => {
this.mute_all_sound = new_config.mute_all_sound;
this.global_sound_volume = new_config.global_sound_volume;
}
);
}
ngOnDestroy() {
this.config_subscription.unsubscribe();
}
playSound(sound_file: string, volume = this.global_sound_volume) {
if (!this.mute_all_sound) {
const audio = new Audio(sound_file);
audio.volume = volume;
audio.play();
}
}
}
|
80eaa92ccc53e85a448549abe2d01faba9a2e843
|
TypeScript
|
alexa/alexa-skills-kit-sdk-for-nodejs
|
/ask-sdk-core/lib/util/SsmlUtils.ts
| 2.859375
| 3
|
/*
* Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/**
* return the string with all invalid XML characters escaped
* @param input
*/
export function escapeXmlCharacters(input : string) : string {
const invalidXmlCharactersMapping = {
'&' : '&',
'<' : '<',
'>' : '>',
'"' : '"',
"'" : ''',
};
const invalidXmlCharactersMappingReverse = Object.keys(invalidXmlCharactersMapping).reduce(
/* eslint-disable-next-line */
(obj : object, key : string) => {
obj[invalidXmlCharactersMapping[key]] = key;
return obj;
},
{},
);
// sanitize any already escaped character to ensure they are not escaped more than once
const sanitizedInput = input.replace(/&|<|>|"|']/g, (c) => invalidXmlCharactersMappingReverse[c]);
return sanitizedInput.replace(/[&'"><]/g, (c) => invalidXmlCharactersMapping[c]);
}
|
67490cfc8cfe3d972a5f834081c5d0cc81f59b86
|
TypeScript
|
wwalpha/pocket-cards
|
/backend/nodejs/batch/src/func/scheduler.ts
| 2.625
| 3
|
import { SES } from '@aws-sdk/client-ses';
import moment from 'moment';
import { Learning } from '@queries';
import { DBHelper, Environments, Consts } from '@utils';
import { Tables } from 'typings';
const client = new SES({});
export default async () => {
// get teachers
const results = await DBHelper().scan<Tables.TUsers>({
TableName: Environments.TABLE_NAME_USERS,
FilterExpression: 'attribute_exists(teacher)',
});
const teachers = results.Items;
const tasks = teachers.map(async (item) => {
const datas = await getStudentProgress(item.id);
await sendmail(datas, item.username, item.teacher as string);
});
await Promise.all(tasks);
};
const getStudentProgress = async (userId: string): Promise<Tables.TLearning[][]> => {
const results = await Promise.all([
DBHelper().query<Tables.TLearning>(Learning.query.byUserTests(userId, moment().add(0, 'days').format('YYYYMMDD'))),
DBHelper().query<Tables.TLearning>(Learning.query.byUserTests(userId, moment().add(1, 'days').format('YYYYMMDD'))),
DBHelper().query<Tables.TLearning>(Learning.query.byUserTests(userId, moment().add(2, 'days').format('YYYYMMDD'))),
]);
return results.map((item) => item.Items);
};
const sendmail = async (datas: Tables.TLearning[][], username: string, email: string) => {
await client.sendEmail({
Source: Environments.MASTER_EMAIL_ADDRESS,
Destination: {
ToAddresses: [email],
},
Message: {
Subject: {
Charset: 'UTF-8',
Data: '【勉強にゃん】の週間予定',
},
Body: {
Text: {
Charset: 'UTF-8',
Data: getMessageBody(datas, username),
},
},
},
});
};
const getMessageBody = (datas: Tables.TLearning[][], username: string): string => {
const message = `
★★${username}さんの3日間の予定表★★
${moment().add(0, 'days').format('YYYY/MM/DD')}: 国語: ${getJapaneseCount(datas[0])} 社会: ${getSocietyCount(
datas[0]
)} 理科: ${getScienceCount(datas[0])}
${moment().add(1, 'days').format('YYYY/MM/DD')}: 国語: ${getJapaneseCount(datas[1])} 社会: ${getSocietyCount(
datas[1]
)} 理科: ${getScienceCount(datas[1])}
${moment().add(2, 'days').format('YYYY/MM/DD')}: 国語: ${getJapaneseCount(datas[2])} 社会: ${getSocietyCount(
datas[2]
)} 理科: ${getScienceCount(datas[2])}`;
return message;
};
const getJapaneseCount = (datas: Tables.TLearning[]): number =>
datas.filter((item) => item.subject === Consts.SUBJECT.JAPANESE.toString()).length;
const getSocietyCount = (datas: Tables.TLearning[]): number =>
datas.filter((item) => item.subject === Consts.SUBJECT.SOCIETY.toString()).length;
const getScienceCount = (datas: Tables.TLearning[]): number =>
datas.filter((item) => item.subject === Consts.SUBJECT.SCIENCE.toString()).length;
|
571e7974879640c01b335a4b2f7bc460da961ca8
|
TypeScript
|
sedc-codecademy/mexn
|
/group2/angualr-class-01/src/app/notes/notes.component.ts
| 2.75
| 3
|
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
class Note
{
}
@Component({
selector: 'app-notes',
templateUrl: './notes.component.html',
styleUrls: ['./notes.component.css']
})
export class NotesComponent implements OnInit
{
notes: Note = [{
id: 1,
title: "some note",
description: 'dummy',
price: 1500
},
{
id: 2,
title: "some note 2",
description: 'dummy',
price: 158
},
{
id: 3,
title: "some note 3",
description: 'dummy',
price: 250
}
]
@Output() onPropetyChange: EventEmitter<string> = new EventEmitter()
inputValue: string = 'Default';
constructor() { }
ngOnInit()
{
console.log(this.notes)
}
logInputValue()
{
console.log(this.inputValue);
this.onPropetyChange.emit(this.inputValue);
}
}
|
640eadf40d0f83de629e7d4abcda82c4783b7aa0
|
TypeScript
|
turms-im/turms
|
/turms-client-js/src/util/input-file-reader.ts
| 3.125
| 3
|
export enum ErrorCode {
ELEMENT_IS_NULL = 1,
IS_NOT_FILE_LIST,
NO_FILES_SELECTED
}
export default class InputFileReader {
private static _reader: FileReader;
static readFileFromHTMLInputElement(element: HTMLInputElement, fileIndex = 0): Promise<string | Uint8Array> {
// element.files instanceof FileList && element.files.length > 0
if (element == null) {
return Promise.reject(ErrorCode.ELEMENT_IS_NULL);
} else if (!(element.files instanceof FileList)) {
return Promise.reject(ErrorCode.IS_NOT_FILE_LIST);
} else if (element.files.length === 0) {
return Promise.reject(ErrorCode.NO_FILES_SELECTED);
}
return this.readFile(element.files[fileIndex]);
}
static readFile(file: File): Promise<string | Uint8Array> {
if (!this._reader) {
this._reader = new FileReader();
}
const promise = new Promise<string | Uint8Array>((resolve, reject): void => {
this._reader.onload = (event): void => {
if (typeof event.target.result === 'string') {
resolve(event.target.result);
} else {
resolve(new Uint8Array(event.target.result));
}
};
this._reader.onerror = (error): void => {
reject(error);
};
});
this._reader.readAsArrayBuffer(file);
return promise;
}
}
|
2b346ad2f1c3ceb572ab2f4002a9743a9e200c9b
|
TypeScript
|
tezos-israel/tezos-react-hooks
|
/src/use-balance.ts
| 2.578125
| 3
|
import { useState, useEffect } from 'react';
import { useTezosContext } from './TezosContext';
import { BalanceHook } from './types';
import BigNumber from 'bignumber.js';
export function useBalance(address = ''): BalanceHook {
const { tezos } = useTezosContext();
const [balance, setBalance] = useState(0);
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
useEffect(() => {
(async () => {
await loadBalance(address);
})();
}, [address]);
return { balance, error, loading, clearError, balanceInTez };
function clearError() {
setError('');
}
function balanceInTez() {
return balance / 10 ** 6;
}
async function loadBalance(address: string) {
if (!address) {
return;
}
if (!tezos) {
throw new Error('Tezos object is undefined');
}
try {
setLoading(true);
const balance: BigNumber = await tezos.tz.getBalance(address);
setBalance(balance.toNumber());
} catch (e) {
setError(e.message);
} finally {
setLoading(false);
}
}
}
|
f4b0414c422409305703ca955abcf5e86cb00f7a
|
TypeScript
|
Jockele/istint
|
/src/utils/output.ts
| 3.265625
| 3
|
import { sprintf } from 'sprintf-js';
/**
* converts sec value in human readable string presentation
* @param t value in sec
*/
export const secAsString = (t : number) : string => {
const minutes = Math.floor(t / 60);
const seconds = Math.trunc(t - minutes*60)
return sprintf("%d:%02d", minutes, seconds);
}
|
65f0f13dad0de80e11ba8917fc2436c94a867a4d
|
TypeScript
|
aleksBobrovs/Home_Task
|
/src/Policy.ts
| 2.5625
| 3
|
import IPolicy from "./interfaces/IPolicy";
import Risk from "./types/Risk";
import {Moment} from "moment";
class Policy implements IPolicy {
private _nameOfInsuredObject: string;
private _validFrom: Moment;
private _validTill: Moment;
private _premium: number;
private _insuredRisks: Risk[];
private test : string[];
get nameOfInsuredObject() : string {
return this._nameOfInsuredObject;
}
set nameOfInsuredObject(name : string) {
this._nameOfInsuredObject = name;
}
get insuredRisks(): Risk[] {
return this._insuredRisks;
}
set insuredRisks(risk: Risk[]) {
this._insuredRisks = risk;
}
get premium(): number {
return this._premium;
}
set premium(premium: number) {
this._premium = premium;
}
get validTill(): Moment {
return this._validTill;
}
set validTill(validTill: Moment) {
this._validTill = validTill;
}
get validFrom(): Moment {
return this._validFrom;
}
set validFrom(validFrom: Moment) {
this._validFrom = validFrom;
}
}
export default Policy;
|
ac46e6379bea5d3cf6a411617ab93ba44a8330b6
|
TypeScript
|
H4ad/omnistack
|
/frontend-react/src/services/api.ts
| 2.6875
| 3
|
//#region Imports
import axios, { AxiosError, AxiosResponse } from 'axios';
import { KeysEnum } from '../models/enums/keys.enum';
import { CreateIncidentPayload } from '../models/payloads/create-incident.payload';
import { CreateOngPayload } from '../models/payloads/create-ong.payload';
import { CreateUserPayload } from '../models/payloads/create-user.payload';
import { LoginPayload } from '../models/payloads/login.payload';
import { IncidentProxy } from '../models/proxies/incident.proxy';
import { OngProxy } from '../models/proxies/ong.proxy';
import { TokenProxy } from '../models/proxies/token.proxy';
import { UserProxy } from '../models/proxies/user.proxy';
//#endregion
const api = axios.create({
baseURL: 'http://127.0.0.1:3010',
});
export default api;
/**
* Método que realiza a autenticação de um usuário
*
* @param loginPayload As informações de autenticação
*/
export async function auth(loginPayload: LoginPayload): Promise<TokenProxy | string> {
const { success, error } = await api.post<TokenProxy>('/auth/local', loginPayload)
.then((success: AxiosResponse<TokenProxy>) => ({ success: success.data, error: void 0 }))
.catch((error: AxiosError<{ message: string[] | string }>) => ({ error: error.response?.data, success: void 0 }));
if (error)
return Array.isArray(error.message) ? error.message[0] : error.message;
const result = success as TokenProxy;
localStorage.setItem(KeysEnum.TOKEN_PROXY, result.token);
return result;
}
/**
* Método que cria um usuário
*
* @param userPayload As informações para a criação do usuário
*/
export async function createUser(userPayload: CreateUserPayload): Promise<UserProxy | string> {
const { success, error } = await api.post<UserProxy>('/users', userPayload)
.then((success: AxiosResponse<UserProxy>) => ({ success: success.data, error: void 0 }))
.catch((error: AxiosError<{ message: string[] | string }>) => ({ error: error.response?.data, success: void 0 }));
if (error)
return Array.isArray(error.message) ? error.message[0] : error.message;
const result = success as UserProxy;
localStorage.setItem(KeysEnum.USER_PROXY, JSON.stringify(result));
return result;
}
/**
* Método que busca as minhas informações
*/
export async function getMe(): Promise<UserProxy | string> {
const token = localStorage.getItem(KeysEnum.TOKEN_PROXY);
const headers = { Authorization: token };
const { success, error } = await api.get<UserProxy>('/users/me', { headers })
.then((success: AxiosResponse<UserProxy>) => ({ success: success.data, error: void 0 }))
.catch((error: AxiosError<{ message: string[] | string }>) => ({ error: error.response?.data, success: void 0 }));
if (error)
return Array.isArray(error.message) ? error.message[0] : error.message;
const result = success as UserProxy;
localStorage.setItem(KeysEnum.USER_PROXY, JSON.stringify(result));
return result;
}
/**
* Método que cria uma ong para o usuário
*
* @param ongPayload As informações para a criação da ong
*/
export async function createOng(ongPayload: CreateOngPayload): Promise<OngProxy | string> {
const token = localStorage.getItem(KeysEnum.TOKEN_PROXY);
const headers = { Authorization: token };
const { success, error } = await api.post<OngProxy>('/ongs', ongPayload, { headers })
.then((success: AxiosResponse<OngProxy>) => ({ success: success.data, error: void 0 }))
.catch((error: AxiosError<{ message: string[] | string }>) => ({ error: error.response?.data, success: void 0 }));
if (error)
return Array.isArray(error.message) ? error.message[0] : error.message;
return success as OngProxy;
}
/**
* Método que retorna os incidentes de uma ong
*
* @param ongId A identificação da ong
*/
export async function getIncidents(ongId: number): Promise<IncidentProxy[] | string> {
const { success, error } = await api.get<IncidentProxy[]>(`/incidents?ongId=${ ongId }`)
.then((success: AxiosResponse<IncidentProxy[]>) => ({ success: success.data, error: void 0 }))
.catch((error: AxiosError<{ message: string[] | string }>) => ({ error: error.response?.data, success: void 0 }));
if (error)
return Array.isArray(error.message) ? error.message[0] : error.message;
return success as IncidentProxy[];
}
/**
* Método que retorna os incidentes de uma ong
*
* @param ongId A identificação da ong
*/
export async function getOngs(): Promise<OngProxy[] | string> {
const userJson = localStorage.getItem(KeysEnum.USER_PROXY);
if (!userJson)
return 'Você não está logado, por favor, entre novamente em sua conta.';
const user = JSON.parse(userJson) as UserProxy;
const { success, error } = await api.get<OngProxy[]>(`/ongs?userId=${ user.id }`)
.then((success: AxiosResponse<OngProxy[]>) => ({ success: success.data, error: void 0 }))
.catch((error: AxiosError<{ message: string[] | string }>) => ({ error: error.response?.data, success: void 0 }));
if (error)
return Array.isArray(error.message) ? error.message[0] : error.message;
return success as OngProxy[];
}
/**
* Método que cria um caso para uma ong
*
* @param incidentPayload As informações para a criação de um caso
*/
export async function createIncident(incidentPayload: CreateIncidentPayload): Promise<IncidentProxy | string> {
const token = localStorage.getItem(KeysEnum.TOKEN_PROXY);
const headers = { Authorization: token };
const { success, error } = await api.post<IncidentProxy>('/incidents', incidentPayload, { headers })
.then((success: AxiosResponse<IncidentProxy>) => ({ success: success.data, error: void 0 }))
.catch((error: AxiosError<{ message: string[] | string }>) => ({ error: error.response?.data, success: void 0 }));
if (error)
return Array.isArray(error.message) ? error.message[0] : error.message;
return success as IncidentProxy;
}
/**
* Método que cria um caso para deletar um incidente
*/
export async function deleteIncident(incidentId: number): Promise<void | string> {
const token = localStorage.getItem(KeysEnum.TOKEN_PROXY);
const headers = { Authorization: token };
const { error } = await api.delete<void>(`/incidents/${ incidentId }`, { headers })
.then((success: AxiosResponse<void>) => ({ success: success.data, error: void 0 }))
.catch((error: AxiosError<{ message: string[] | string }>) => ({ error: error.response?.data, success: void 0 }));
if (error)
return Array.isArray(error.message) ? error.message[0] : error.message;
return void 0;
}
|
59d062a46fd51c0e15ccdd645996e50d0fd8fef6
|
TypeScript
|
xrts/TypeScript
|
/8.函数的类型.ts
| 4.34375
| 4
|
// 函数声明(Function Declaration)
function sum(x, y) {
return x + y;
}
// 函数表达式(Function Expression)
let mySum = function (x, y) {
return x + y;
};
// 函数声明 ts需要考虑输入和输出,输入多余或少于要求都报错
function sum(x: number, y:number): number {
return x + y;
}
// 函数表达式 ts
let mySum = function (x: number, y: number): number {
return x + y;
};
// 上面的代码只对等号右侧的匿名函数进行了类型定义,而等号左边的mysum,是通过赋值操作进行类型推断出来的,如果需要我们手动给mysum添加类型,应该如下
let mySum: (x: number, y:number) => number = function(x:number, y:number): number {
return x +y;
};
// 用接口定义函数的形状
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
return source.search(subString) !== -1;
};
// 可选参数(可选参数必须接在必需参数后面)\
function buildName(firstName: string, lastName?: string) {
if(lastName) {
return firstName + ' ' + lastName;
} else {
return firstName;
}
}
let tomcat = buildName('Tom', 'Cat');
let tom = buildName('Tom');
// 参数默认值 (ts会将添加了默认值的参数识别为可选参数)此时就不受「可选参数必须接在必需参数后面」的限制了
function buildName(firstName: string = 'Tom', lastName: string) {
return firstName + ' ' + lastName;
}
let tomcat = buildName('Tom', 'Cat');
let cat = buildName(undefined, 'Cat');
// 剩余参数 ...rest
function push(array: any[], ...items: any[]) {
items.forEach(function (item) {
array.push(item);
});
}
let a = [];
push(a,1,2,3);
// rest参数只能是最后一个参数
// 重载 (重载允许一个函数接受不同数量或类型的参数时,作出不同的处理)
function reverse(x: number): number;
function reverse(x: string): string;
function reverse(x: number | string): number | string {
if(typeof x === 'number') {
return Number(x.toString().split('').reverse().join(''));
}else if(typeof x === 'string') {
return x.split('').reverse().join('');
}
}
//TypeScript 会优先从最前面的函数定义开始匹配,所以多个函数定义如果有包含关系,需要优先把精确的定义写在前面。
|
7f0371c7e0b89d606ab87ced8c2a1183b548b8e8
|
TypeScript
|
naspinall/studs
|
/src/operators/Operator.ts
| 2.921875
| 3
|
import { ParameterManager } from "../common/ParameterManager";
import { EntityMetadata } from "../metadata/metadata";
import { toSQLValue } from "../utility/encoding";
import { Primitive } from "../utility/types";
export interface OperatorConfiguration {
count?: number;
alias?: string;
column?: string;
metadata?: EntityMetadata;
}
export interface SelectOperator<T> {
configure(configuration: OperatorConfiguration): SelectOperator<T>;
getParameterManager(): ParameterManager;
toSQL(): [string, Array<Primitive>];
}
export const isSelectOperator = <T>(
operator: any
): operator is SelectOperator<T> => {
return (
(operator as SelectOperator<T>).toSQL !== undefined &&
(operator as SelectOperator<T>).configure !== undefined
);
};
export const isSelectOperatorArray = <T>(
operator: Array<any>
): operator is Array<SelectOperator<T>> => {
return operator.some((value) => isSelectOperator(value));
};
export abstract class Operator<T> implements SelectOperator<T> {
protected metadata!: EntityMetadata;
protected column!: string;
protected alias!: string;
protected parameterCount!: number;
protected parameterManager: ParameterManager = new ParameterManager();
configure(config: OperatorConfiguration): Operator<T> {
this.parameterManager.configure({ count: config.count });
this.metadata = config.metadata || ({} as EntityMetadata);
this.column = config.column || "";
this.alias = config.alias || "";
return this;
}
getParamCount(): number {
return this.parameterCount;
}
getParameterManager(): ParameterManager {
return this.parameterManager;
}
getSQLValue(value: Primitive): string;
getSQLValue(value: Array<Primitive>): Array<string>;
getSQLValue(value: Primitive | Array<Primitive>): string | Array<string> {
const SQLType = this.metadata.getSQLType(this.column);
if (Array.isArray(value))
return value.map((value) => toSQLValue(value, SQLType));
else return toSQLValue(value, SQLType);
}
abstract toSQL(): [string, Array<Primitive>];
}
|
d0205bfaaebf036ff9c756487666050f67f289c8
|
TypeScript
|
DanielGiljam/ia-2-017-0-lodge-broker
|
/src/middlewares/resourceExtractor.ts
| 2.6875
| 3
|
import {Request, RequestHandler} from "express"
import {Model} from "mongoose"
import Advert, {IAdvert} from "../models/Advert"
import Booking, {IBooking} from "../models/Booking"
import Cabin, {ICabin} from "../models/Cabin"
import User, {IUser} from "../models/User"
type ResourceName = "user" | "cabin" | "advert" | "booking"
type ResourceMap = {
[K in ResourceName]: {
model: Model<any>
authorIndicatingPath: string
verifyValidity: (
id: any,
resources: Request["resources"],
resource?: IUser | ICabin | IAdvert | IBooking | null,
) => boolean
}
}
const resourceMap: ResourceMap = {
user: {
model: User,
authorIndicatingPath: "_id",
verifyValidity: (id, resources = {}, resource = resources.user) => {
// console.log("VERIFY VALIDITY - USER:", resource != null ? resource._id.equals(id) === true : true)
// console.log("id:", id)
// console.log("resources:", resources)
// console.log("resource:", resource)
return resource != null ? resource._id.equals(id) === true : true
},
},
cabin: {
model: Cabin,
authorIndicatingPath: "owner",
verifyValidity: (id, resources = {}, resource = resources.cabin) => {
// console.log("VERIFY VALIDITY - CABIN:", resource != null ? resource._id.equals(id) === true : true)
// console.log("id:", id)
// console.log("resources:", resources)
// console.log("resource:", resource)
return resource != null
? resource._id.equals(id) === true &&
resourceMap.user.verifyValidity(
(resource as ICabin).owner,
resources,
)
: true
},
},
advert: {
model: Advert,
authorIndicatingPath: "advertiser",
verifyValidity: (id, resources = {}, resource = resources.advert) => {
// console.log("VERIFY VALIDITY - ADVERT:", resource != null ? resource._id.equals(id) === true : true)
// console.log("id:", id)
// console.log("resources:", resources)
// console.log("resource:", resource)
return resource != null
? resource._id.equals(id) === true &&
resourceMap.cabin.verifyValidity(
(resource as IAdvert).cabin,
resources,
)
: true
},
},
booking: {
model: Booking,
authorIndicatingPath: "user",
verifyValidity: (id, resources = {}, resource = resources.booking) => {
// console.log("VERIFY VALIDITY - BOOKING:", resource != null ? resource._id.equals(id) === true : true)
// console.log("id:", id)
// console.log("resources:", resources)
// console.log("resource:", resource)
return resource != null
? resource._id.equals(id) === true &&
resourceMap.advert.verifyValidity(
(resource as IBooking).advert,
resources,
)
: true
},
},
}
const resourceExtractor = (
resourceName: ResourceName,
onlyAuthor?: boolean,
): RequestHandler => {
return async (req, res, next) => {
try {
console.log(
`Extracting ${resourceName} "${req.params[resourceName]}" from URL...`,
)
const {model, authorIndicatingPath, verifyValidity} = resourceMap[
resourceName
]
const resource = await model.findById(req.params[resourceName])
if (
resource == null ||
!verifyValidity(resource?._id, req.resources, resource)
) {
res.status(404).json({status: "Not Found"})
return
}
if (
onlyAuthor === true &&
resource[authorIndicatingPath] !== req.user?.id
) {
res.status(403).json({status: "Forbidden"})
return
}
console.log("resources:", req.resources)
if (req.resources == null) req.resources = {}
req.resources[resourceName] = resource
next()
} catch (error) {
console.error(error)
res.status(404).json({status: "Not Found"})
}
}
}
export default resourceExtractor
|
4c36a18745f0f1aa62dfc14add367b662c15f3e2
|
TypeScript
|
andrewjoll/shipwreck
|
/src/app/components/Motion.ts
| 2.75
| 3
|
import { Entity } from '@/entities';
import { PositionProvider } from '@/components';
import { Vector3 } from 'three';
export default class Motion implements PositionProvider {
entity: Entity;
name: string = 'Motion';
position: Vector3;
velocity: Vector3;
target: Vector3;
targetEntity: Entity;
speed: number;
path: Vector3[];
onPath: boolean = false;
isDirty: boolean = false;
stickToGround: boolean;
constructor(position: Vector3, speed: number, stickToGround: boolean) {
this.velocity = new Vector3(0, 0, 0);
this.position = position;
this.speed = speed;
this.stickToGround = stickToGround;
}
getPosition(): Vector3 {
return this.position;
}
setPath(path: Vector3[]): void {
this.path = path;
if (this.path.length) {
this.onPath = true;
}
}
setTarget(entity: Entity): void {
this.targetEntity = entity;
}
clearPath(): void {
this.path = [];
this.onPath = false;
}
shiftPath() {
this.path.shift();
if (!this.path.length) {
this.onPath = false;
}
}
}
|
1d3357010269bf24cdb3f7ca23834a5aa954081a
|
TypeScript
|
hhiraba/exercises
|
/deno/sample/gcd.ts
| 3.21875
| 3
|
function gcd(a: number, b: number): number {
if (a % b == 0) {
return b;
}
return gcd(b, a % b);
}
console.log(gcd(12, 3));
console.log(gcd(24, 12));
console.log(gcd(126, 34));
|
8a9ce52c93b8f03a7ea5d01b53e7b08cba743e6e
|
TypeScript
|
CoinbaseStablecoin/multi-sig-admin-dashboard
|
/src/models/Contract.ts
| 2.75
| 3
|
import { getTransactableFunctions, parseAbiJson } from "../util/abi";
import { AbiFunction } from "../util/AbiFunction";
import { toChecksumAddress } from "../util/address";
export interface MarshaledContract {
address: string;
name: string;
abi: string;
}
export class Contract {
public readonly address: string;
public readonly name: string;
public readonly abi: string;
public readonly transactableFunctions: Map<string, AbiFunction>;
public constructor(address: string, name: string, abi: string) {
this.address = toChecksumAddress(address);
this.name = name.trim();
this.abi = abi;
const abiItems = parseAbiJson(this.abi);
this.transactableFunctions = new Map(
getTransactableFunctions(abiItems).map((func) => [func.selector, func])
);
}
}
|
6d970207875834ccb7f1a7e3e3411f833b4aaf05
|
TypeScript
|
Sound1ab/NoteHub.Frontend
|
/src/utils/daysToEvent.ts
| 3.078125
| 3
|
const MS_PER_DAY = 1000 * 60 * 60 * 24
export function daysToEvent(date?: string | null) {
if (!date) {
return null
}
const now = new Date()
const event = new Date(date)
const nowUTC = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate())
const eventUTC = Date.UTC(
event.getFullYear(),
event.getMonth(),
event.getDate()
)
return Math.floor((eventUTC - nowUTC) / MS_PER_DAY)
}
|
8d514563ac346d03e3ca16787ff08f176397e706
|
TypeScript
|
vicjune/huit-sec
|
/src/utils/usePlayers.ts
| 2.6875
| 3
|
import { useCallback, useEffect, useMemo } from 'react';
import { v4 as genUuid } from 'uuid';
import { useGlobalState } from '../contexts/GlobalState';
import { storage, STORAGE_PLAYERS_KEY } from './storage';
export interface Player {
id: string;
name: string;
score: number;
nbrAnswered: number;
}
export const getNewPlayer = (name: string) => ({
id: genUuid(),
name,
score: 0,
nbrAnswered: 0,
});
export const usePlayers = () => {
const { globalState, setGlobalState } = useGlobalState();
const {
players: playersGS,
playerAnsweringId,
secondaryPlayerAnsweringId,
playerAskingId,
} = globalState;
useEffect(() => {
if (playersGS === undefined) {
storage.get<string[]>(STORAGE_PLAYERS_KEY).then((playerNames) => {
if (!playerNames) return;
setGlobalState((prev) => ({
...prev,
players: playerNames.map(getNewPlayer),
}));
});
}
}, [playersGS, setGlobalState]);
const players = useMemo(() => playersGS || [], [playersGS]);
const playerAnswering = useMemo(
() => players.find(({ id }) => playerAnsweringId === id),
[playerAnsweringId, players],
);
const secondaryPlayerAnswering = useMemo(
() => players.find(({ id }) => secondaryPlayerAnsweringId === id),
[players, secondaryPlayerAnsweringId],
);
const playerAsking = useMemo(
() => players.find(({ id }) => playerAskingId === id),
[playerAskingId, players],
);
const addPlayer = useCallback(
(playerName: string) => {
storage.set(STORAGE_PLAYERS_KEY, [
...players.map(({ name }) => name),
playerName,
]);
setGlobalState((prev) => ({
...prev,
players: [...(prev.players || []), getNewPlayer(playerName)],
}));
},
[players, setGlobalState],
);
const removePlayer = useCallback(
(toRemoveId: string) => {
const newPlayers = players.filter(({ id }) => id !== toRemoveId);
storage.set(
STORAGE_PLAYERS_KEY,
newPlayers.map(({ name }) => name),
);
setGlobalState((prev) => ({
...prev,
players: newPlayers,
}));
},
[players, setGlobalState],
);
const removeAllPlayers = useCallback(() => {
storage.remove(STORAGE_PLAYERS_KEY);
setGlobalState((prev) => ({
...prev,
players: [],
}));
}, [setGlobalState]);
return {
players,
playerAnswering,
secondaryPlayerAnswering,
playerAsking,
addPlayer,
removePlayer,
removeAllPlayers,
};
};
|
f8b372f32e2d2525d4df7157789a66e6d715ad40
|
TypeScript
|
Isabellalima86/estudandoTypeScript
|
/null.ts
| 3.171875
| 3
|
let altura: number | null = 1.63
altura = null;
type Contato = {
nome: String;
telefone1: string;
telefone2?: string | null;
}// ooperador ? diz que o valor é opcional
const contato: Contato = {
nome: 'Bell',
telefone1: '21 90965-2788',
telefone2: null,
}
|