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
|
|---|---|---|---|---|---|---|
d75d53d4695c3d65166d4a2fb03bbdde0df928b1
|
TypeScript
|
DimitarDKirov/ForumSystemClient
|
/src/app/models/message.ts
| 3.09375
| 3
|
export class Message {
text: string;
isError: boolean;
constructor(text: string, isError: boolean = false) {
this.text = text;
this.isError = isError
}
}
|
345ca349d385224034814c3fde1ed62ed0dc6702
|
TypeScript
|
pbehnke/algorithmx
|
/src/client/utils.ts
| 3.140625
| 3
|
export interface Lookup<T> { readonly [k: string]: T }
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
export type MapDict<D, M> = { [k in keyof D]: M }
export type Primitive = string | number | boolean
export type RPartial<T> = T extends object ? {
readonly [k in keyof T]?: RPartial<T[k]>
} : T
export const mapDict = <T, M>(dict: T, func: ((k: keyof T, v: T[keyof T], i: number) => M)): MapDict<T, M> => {
/* tslint:disable */
let newDict = {}
const keys = Object.keys(dict)
for (let i = 0; i < keys.length; i++) {
const k = keys[i]
newDict[k] = func(k as keyof T, dict[k], i)
}
return newDict as MapDict<T, M>
/* tslint:enable */
}
export const enumValues = <T>(enumeration: T): ReadonlyArray<T[keyof T]> =>
Object.keys(enumeration).map(k => enumeration[k])
export const isNumStr = (value: string): boolean => {
return !isNaN(value as unknown as number) && value !== ''
}
export const isDict = (value: unknown): value is object =>
typeof value === 'object' && value !== null && !Array.isArray(value)
export const isDictEmpty = (dict: object) => Object.keys(dict).length === 0
export const filterError = <T>(value: { [k in keyof T]: T[k] | Error }): T | Error => {
const error = Array.isArray(value) ? value.find(v => v instanceof Error)
: typeof value === 'object' ? Object.values(value).find(v => v instanceof Error)
: value
return error || value
}
type FilterFn<T> = (k: keyof T, v: T[keyof T], i: number) => boolean
export const filterDict = <T extends object>(dict: T, filterFn: FilterFn<T>): Partial<T> => {
return Object.entries(dict).reduce((newDict, [k, v], i) =>
({...newDict, ...(filterFn(k as keyof T, v, i) ? { [k]: v } : {}) }), {})
}
export const removeWhitespace = (s: string) => s.replace(/\s/g, '')
export const randomId = (): string => Math.random().toString(36).substr(2, 9)
|
837ee8d7be9798cb0124c5924fbbcb801c7a33f7
|
TypeScript
|
JonaVDM/adventofcode
|
/2020/day13/index.ts
| 2.984375
| 3
|
import path from 'path';
import fs from 'fs';
import { performance } from 'perf_hooks';
function getInput() {
const file = fs.readFileSync(path.join(__dirname, 'input'));
return file.toString().trim();
}
function numberWithCommas(x: number) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
class Solver {
private time: number;
private schedule: number[];
constructor() {
let input = getInput().split('\n');
this.time = Number(input[0]);
this.schedule = input[1].split(',').map(Number);
}
part1() {
let lines = this.schedule.reduce((prev, curr) => {
if (curr) return [...prev, curr];
return prev
}, []);
for (let i = this.time; i < Infinity; i++) {
for (let line of lines) {
if (i % line == 0) {
return (i - this.time) * line;
}
}
}
}
part2() {
for (let i = Math.floor(100000000000000 / this.schedule[0]); i < Infinity; i++) {
let j = i * this.schedule[0];
console.log(numberWithCommas(j));
let completed = true;
for (let k = 1; k < this.schedule.length; k++) {
if (!this.schedule[k]) {
continue;
}
if ((j + k) % this.schedule[k] != 0) {
completed = false;
break;
}
}
if (completed) {
console.log('GOTHIM');
return j;
}
}
}
}
(async () => {
const t0 = performance.now();
const solver = new Solver();
console.log(`Part 1 ${solver.part1()}`);
console.log(`Part 2 ${solver.part2()}`);
console.log(`Solved? in ${performance.now() - t0}ms`);
})();
|
60dd10cc74915355966edad43c62cd74bfd09f93
|
TypeScript
|
mike-works/sql-fundamentals
|
/test/ex06.create-order.test.ts
| 2.796875
| 3
|
import { assert } from 'chai';
import { suite, test, timeout } from 'mocha-typescript';
import { createOrder, deleteOrder, getAllOrders } from '../src/data/orders';
import { getDb } from '../src/db/utils';
import './helpers/global-hooks';
export const VALID_ORDER_DATA: Pick<
Order,
| 'employeeid'
| 'customerid'
| 'shipcity'
| 'shipaddress'
| 'shipname'
| 'shipvia'
| 'shipregion'
| 'shipcountry'
| 'shippostalcode'
| 'requireddate'
| 'freight'
> = {
employeeid: 4,
customerid: 'BERGS',
shipcity: '',
shipaddress: '',
shipvia: 3,
shipregion: '',
shipname: '',
shipcountry: '',
shippostalcode: '',
requireddate: new Date(2030, 1, 1, 0, 0, 0, 0).toISOString(),
freight: 3.12
};
const INVALID_ORDER_DATA: Partial<Order> = {
customerid: 'BERGS',
shipcity: '',
shipaddress: '',
shipvia: 3,
shipcountry: '',
shippostalcode: '',
requireddate: new Date(2010, 1, 1, 0, 0, 0, 0).toISOString(),
freight: 3.12
};
@suite('EX06: "Create an Order" - Record insertion test')
class CreateOrderTest {
@test('createOrder() creates an order successfully for valid data')
public async createOrderForValidData() {
let o = await createOrder(VALID_ORDER_DATA as any);
assert.ok(o, 'returns a promise that resolves to a non-empty vale');
assert.ok(o.id, 'returns a promise that resolves to something with an id property');
assert.isAtLeast(
parseInt(o.id as string, 10),
1,
'returns a promise that resolves to something with a numeric id property, whose value is > 1'
);
}
@test('createOrder() results in the total number of orders increasing')
public async createOrderAddsRecords() {
let originalNumOrders = (await getAllOrders({ page: 1, perPage: 9999999 })).length;
let { id } = await createOrder(VALID_ORDER_DATA);
let numOrders = (await getAllOrders({ page: 1, perPage: 9999999 })).length;
assert.equal(
numOrders,
originalNumOrders + 1,
'Total number of orders increases as a result of creating an order'
);
await deleteOrder(id);
}
@test(
'createOrder() with some OrderDetail items increases the total number of OrderDetail records'
)
public async createOrderWithItems() {
let db = await getDb();
let { count } = await db.get('SELECT count(id) as count FROM OrderDetail');
let originalNumOrderDetails = parseInt(count, 10);
assert.isAbove(originalNumOrderDetails, 0, 'Nonzero number of OrderDetail records');
let { id } = await createOrder(VALID_ORDER_DATA, [
{ productid: 17, unitprice: 4.11, quantity: 4, discount: 0 },
{ productid: 11, unitprice: 3.37, quantity: 1, discount: 0.1 }
]);
let result = await db.get('SELECT count(id) AS count FROM OrderDetail');
count = result.count;
let numOrderDetails = parseInt(count, 10);
assert.isAbove(numOrderDetails, 0, 'Nonzero number of OrderDetail records');
assert.equal(
numOrderDetails,
originalNumOrderDetails + 2,
'Total number of orders increases as a result of creating an order'
);
await deleteOrder(id);
}
@test('createOrder() rejects invalid data')
public async createOrderForInvalidData() {
let errorMessages: string[] = [];
try {
let o = await createOrder(INVALID_ORDER_DATA as any);
} catch (e) {
errorMessages.push(e.toString());
}
assert.equal(
errorMessages.length,
1,
'An error was thrown when trying to createOrder with invalid data'
);
assert.match(
errorMessages[0].toLowerCase(),
/(null constraint)|(cannot be null)/,
'Error message had to do with a NOT NULL constraint'
);
// assert.ok(o, 'returns a promise that resolves to a non-empty vale');
// assert.ok(o.Id, 'returns a promise that resolves to something with an Id property');
// assert.isAtLeast(parseInt(o.Id as string, 10), 1, 'returns a promise that resolves to something with a numeric Id property, whose value is > 1');
}
}
|
94f7618dccded23d47c35053be78ddf957ac8dbd
|
TypeScript
|
stephenh/ts-proto
|
/integration/value/value-test.ts
| 2.765625
| 3
|
import { Reader } from "protobufjs";
import { ValueMessage } from "./value";
import { ValueMessage as PbValueMessage } from "./pbjs";
describe("values", () => {
it("json value", () => {
const s1 = ValueMessage.fromJSON({
value: "Hello",
anyList: [1, "foo", true],
repeatedAny: [2, "bar", false],
nullValue: null,
});
const s2 = PbValueMessage.decode(Reader.create(ValueMessage.encode(s1).finish()));
expect(s2).toMatchInlineSnapshot(`
{
"anyList": {
"values": [
{
"numberValue": 1,
},
{
"stringValue": "foo",
},
{
"boolValue": true,
},
],
},
"repeatedAny": [
{
"numberValue": 2,
},
{
"stringValue": "bar",
},
{
"boolValue": false,
},
],
"value": {
"stringValue": "Hello",
},
}
`);
});
it("decodes lists of any types correctly", () => {
const s1 = ValueMessage.fromJSON({
anyList: [1, "foo", true],
repeatedAny: [2, "bar", false, { key: "value" }],
});
expect(s1).toEqual({
anyList: [1, "foo", true],
repeatedAny: [2, "bar", false, { key: "value" }],
repeatedStrings: [],
});
});
it("toJson", () => {
const s1 = ValueMessage.fromPartial({
anyList: [1],
repeatedAny: [2],
});
expect(s1).toEqual({ anyList: [1], repeatedAny: [2], repeatedStrings: [] });
});
});
|
0ba70a6cc18cc1fa15437daca0bd9534c8809504
|
TypeScript
|
peterhughesdev/doneyet
|
/src/store/types.ts
| 2.53125
| 3
|
import { Timer } from '../util/timer';
export interface ThemeState {
active: string
}
export interface QueueState {
timers: Timer[];
}
const RUNNING = 'RUNNING';
const STOPPED = 'STOPPED';
const PAUSED = 'PAUSED';
export type ScheduleRunningState = typeof RUNNING | typeof STOPPED | typeof PAUSED;
export interface ScheduleState {
state: ScheduleRunningState;
start: number;
elapsed: number;
timers: Timer[];
}
export const SET_THEME = 'SET_THEME';
interface SetThemeAction {
type: typeof SET_THEME,
theme: string
}
export type ThemeActions = SetThemeAction;
export const TOGGLE_REPEAT = 'TOGGLE_REPEAT';
export const ADD_TIMER = 'ADD_TIMER';
export const REMOVE_TIMER = 'REMOVE_TIMER';
export const CLEAR_QUEUE = 'CLEAR_QUEUE'
export const REORDER_QUEUE = 'REORDER_QUEUE'
interface ToggleRepeatAction {
type: typeof TOGGLE_REPEAT,
payload: Timer
}
interface ClearQueueAction {
type: typeof CLEAR_QUEUE
}
interface ReorderQueueAction {
type: typeof REORDER_QUEUE,
payload: {
timers: Timer[]
}
}
interface AddTimerAction {
type: typeof ADD_TIMER,
payload: Timer
}
interface RemoveTimerAction {
type: typeof REMOVE_TIMER,
payload: {
id: string
}
}
export type QueueActions = ToggleRepeatAction | ReorderQueueAction | ClearQueueAction | AddTimerAction | RemoveTimerAction;
export const SCHEDULE_TIMERS = 'SCHEDULE_TIMERS';
export const STOP_TIMERS = 'STOP_TIMERS';
export const PAUSE_TIMERS = 'PAUSE_TIMERS';
interface ScheduleTimersAction {
type: typeof SCHEDULE_TIMERS,
payload: {
timers: Timer[]
}
};
interface StopTimersAction {
type: typeof STOP_TIMERS
};
interface PauseTimersAction {
type: typeof PAUSE_TIMERS
};
export type ScheduleActions = ScheduleTimersAction | StopTimersAction | PauseTimersAction;
|
b985bc08ea7abdae0656e30aa170e2736e03f8f8
|
TypeScript
|
gustavoam-asdf/algorithm
|
/devsu-code-jam-preparation/7-toeplitzMatrix.ts
| 3.859375
| 4
|
interface DiagonalInitial {
value: number
rowPos: number
colPos: number
}
const existInMatrix = (
m: number[][],
rowPos: number,
colPos: number
): boolean => {
if (!m[rowPos]) return false
if (!m[rowPos][colPos]) return false
return true
}
const getDiagonalInitials = (matrix: number[][]): DiagonalInitial[] => {
return matrix
.map((row: number[], rowPos: number) => {
if (rowPos === 0) {
return row.map((ceil: number, i) => ({
value: ceil,
rowPos: 0,
colPos: i
}))
}
return {
value: row[0],
rowPos,
colPos: 0
}
})
.flat(1)
}
const getDiagonal = ({
diagInit,
matrix
}: {
diagInit: DiagonalInitial
matrix: number[][]
}): number[] => {
const diagonal: number[] = []
let rowIter: number = diagInit.rowPos,
colIter: number = diagInit.colPos
while (existInMatrix(matrix, rowIter, colIter)) {
const element = matrix[rowIter++][colIter++]
diagonal.push(element)
}
return diagonal
}
const isToeplitzMatrix = (diagonals: number[][]): boolean => {
return diagonals.every((diagonal: number[]) =>
diagonal.every((n: number) => n === diagonal[0])
)
}
const amountOfDigits = (toeplitz: number[][]): number => {
const diagonalInitials: DiagonalInitial[] = getDiagonalInitials(toeplitz)
const diagonals: number[][] = diagonalInitials.map(
(diagInit: DiagonalInitial) => getDiagonal({ diagInit, matrix: toeplitz })
)
if (!isToeplitzMatrix(diagonals)) {
return -1
}
return diagonals.length
}
const toeplitz = [
[1, 2, 3, 4, 8, 1],
[5, 1, 2, 3, 4, 8],
[4, 5, 1, 2, 3, 4],
[7, 4, 5, 1, 2, 3]
]
console.log(amountOfDigits(toeplitz))
|
b4d500670b592dc60f8a6d126c295144e0466b90
|
TypeScript
|
tylerlong/ringcentral-typescript
|
/src/definitions/GlipPostEvent.ts
| 2.859375
| 3
|
import {GlipMentionsInfo} from '.';
class GlipPostEvent {
/**
* Internal identifier of a post
*/
id?: string;
/**
* Type of a post event
*/
eventType?: 'PostAdded' | 'PostChanged' | 'PostRemoved';
/**
* Internal identifier of a group a post belongs to
*/
groupId?: string;
/**
* Type of a post. 'TextMessage' - an incoming text message; 'PersonJoined' - a message notifying that person has joined a conversation; 'PersonsAdded' - a message notifying that a person(s) were added to a conversation
*/
type?: 'TextMessage' | 'PersonJoined' | 'PersonsAdded' | 'Card';
/**
* For 'TextMessage' post type only. Message text
*/
text?: string;
/**
* Internal identifier of a user - author of a post
*/
creatorId?: string;
/**
* For PersonsAdded post type only. Identifiers of persons added to a group
*/
addedPersonIds?: string[];
/**
* For PersonsRemoved post type only. Identifiers of persons removed from a group
*/
removedPersonIds?: string[];
/**
* List of at mentions in post text with names.
*/
mentions?: GlipMentionsInfo[];
/**
* Post creation datetime in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format
*/
creationTime?: string;
/**
* Post last change datetime in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format
*/
lastModifiedTime?: string;
}
export default GlipPostEvent;
|
e8c76220bbbcac421ed0215fcb1605c1d2214f55
|
TypeScript
|
BitGo/BitGoJS
|
/modules/sdk-coin-near/src/lib/transferBuilder.ts
| 2.578125
| 3
|
import { BaseCoin as CoinConfig } from '@bitgo/statics';
import { BaseKey, BuildTransactionError, TransactionType } from '@bitgo/sdk-core';
import { TransactionBuilder } from './transactionBuilder';
import { Transaction } from './transaction';
import * as NearAPI from 'near-api-js';
import assert from 'assert';
import BN from 'bn.js';
import BigNumber from 'bignumber.js';
export class TransferBuilder extends TransactionBuilder {
private _amount: string;
constructor(_coinConfig: Readonly<CoinConfig>) {
super(_coinConfig);
}
/**
* Initialize the transaction builder fields using the decoded transaction data
*
* @param {Transaction} tx the transaction data
*/
initBuilder(tx: Transaction): void {
super.initBuilder(tx);
this._amount = tx.nearTransaction.actions[0].transfer.deposit.toString();
}
/** @inheritdoc */
protected async buildImplementation(): Promise<Transaction> {
assert(this._amount, new BuildTransactionError('amount is required before building transfer'));
super.actions([NearAPI.transactions.transfer(new BN(this._amount))]);
const tx = await super.buildImplementation();
tx.setTransactionType(TransactionType.Send);
return tx;
}
/** @inheritdoc */
protected signImplementation(key: BaseKey): Transaction {
const tx = super.signImplementation(key);
tx.setTransactionType(TransactionType.Send);
return tx;
}
/**
* Sets the amount of this transaction.
*
* @param {string} value the amount to be sent in yocto (1 Near = 1e24 yoctos)
* @returns {TransactionBuilder} This transaction builder
*/
public amount(value: string): this {
this.validateValue(new BigNumber(value));
this._amount = value;
return this;
}
}
|
bf50e4cc4370ca8e9bba9cc0a6894470e7361c0c
|
TypeScript
|
spamshaker/lorem-babble
|
/packages/utils/src/utils.ts
| 2.703125
| 3
|
import {Dispatch, Reducer, ReducerState, useReducer} from 'react';
export function useReducerWithMiddleware<R extends Reducer<any, any>, I>(
reducer: R,
initializerArg: I & ReducerState<R>,
middleware?: (action: any) => Promise<any>
): [ReducerState<R>, Dispatch<any>] {
const [state, dispatch] = useReducer(reducer, initializerArg);
const dispatchWithMiddleware: Dispatch<any> = async (action) => {
const next = middleware ? await middleware(action) : action;
dispatch(next);
};
return [state, dispatchWithMiddleware];
}
|
692ccf6a24297a211cb360d264a50a2c029a2bc8
|
TypeScript
|
zhengchaoken/office-ui-fabric
|
/src/components/FacePile/FacePile.ts
| 2.59375
| 3
|
// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See LICENSE in the project root for license information.
/// <reference path="../Persona/Persona.ts"/>
namespace fabric {
/**
* FacePile
*
* A host for FacePile
*
*/
const PERSONA_CLASS = ".ms-Persona";
const PERSONA_INITIALS = ".ms-Persona-initials";
const PERSONA_IMAGE = ".ms-Persona-image";
const PERSONA_PRIMARY_CLASS = ".ms-Persona-primaryText";
const PERSONA_SECONDARY_CLASS = ".ms-Persona-secondaryText";
interface PersonaCollection {
item: Element;
initials: string;
image: string;
primaryText: string;
secondaryText: string;
personaInstance: Persona;
}
export class FacePile {
private _personaCollection: Array<PersonaCollection> = [];
private _facePile: Element;
/**
*
* @param {HTMLElement} container - the target container for an instance of FacePile
* @constructor
*/
constructor(container: Element) {
this._facePile = container;
this._createPersonaCollection();
}
private _createPersonaCollection() {
let _personas = document.querySelectorAll(PERSONA_CLASS);
for (let i = 0; i < _personas.length; i++) {
let _thisPersona = _personas[i];
this._personaCollection.push({
item: _thisPersona,
initials: _thisPersona.querySelector(PERSONA_INITIALS).textContent,
image: _thisPersona.querySelector(PERSONA_IMAGE) ?
_thisPersona.querySelector(PERSONA_IMAGE).getAttribute("src") : null,
primaryText: _thisPersona.querySelector(PERSONA_PRIMARY_CLASS) ?
_thisPersona.querySelector(PERSONA_PRIMARY_CLASS).textContent : "",
secondaryText: _thisPersona.querySelector(PERSONA_SECONDARY_CLASS) ?
_thisPersona.querySelector(PERSONA_SECONDARY_CLASS).textContent : "",
personaInstance: new Persona(_thisPersona)
});
}
}
}
}
|
c29094041ad6f0a94418c6abd6beaa41922b63a8
|
TypeScript
|
vladdelusive/react-movie-version.2.0
|
/src/helpers/overview-editor.ts
| 2.546875
| 3
|
const random = (min = 150, max = 190) => Math.floor(min + Math.random() * (max - min));
export function overviewEditor(text: string): string {
const newText = text.slice(0, random())
const lastDot = newText.lastIndexOf(".");
return newText.slice(0, lastDot) + "...."
}
|
79c168636b43677b3e603a7889f931f14889ccf6
|
TypeScript
|
ipassynk/angular2-learning
|
/src/app/list-observable/item.service.ts
| 2.734375
| 3
|
import {Injectable} from 'angular2/core';
import {Subject} from 'rxjs/Subject';
import {BehaviorSubject} from 'rxjs/Rx';
import {Observable} from 'rxjs/Observable';
export class Item {
constructor(public name:string, public checked:boolean) {
}
}
export interface State {
items: Array<Item>;
}
;
const initItems:Array<Item> = [
new Item('blueberry', true),
new Item('banana', true),
new Item('apple', false),
new Item('orange', false)
];
@Injectable()
export class ObservableItemService {
public items$;
public dispatcher$:Subject<Item> = new Subject<Item>(null);
private store$:BehaviorSubject<State> = new BehaviorSubject<State>({items: initItems});
private reduce$ = new Subject<Item>(null);
constructor() {
this.items$ = this.store$.map((s:State) => s.items);
this.reduce$
.scan((state:State, {name, checked})=> {
let i = state.items.findIndex((x:Item) => x.name === name);
return {
items: [...state.items.slice(0, i),
new Item(checked ? name.toUpperCase() : name.toLowerCase(), checked),
...state.items.slice(i + 1)
]
};
}, {items: initItems})
.subscribe((s:State) => this.store$.next(s));
this.dispatcher$.subscribe(x => this.reduce$.next(x));
}
}
|
56c28aa10cddd255f97716486b8e41cdd5489955
|
TypeScript
|
SergioTx/TypescriptCourse
|
/typescript/app1/app1.ts
| 4
| 4
|
// string
let myName: string = 'Max';
// myName = 28;
// number
let myAge: number = 27.5;
// myAge = 'Max';
// boolean
let hasHobbies: boolean = false;
// hasHobbies = 1;
// assign types
let myRealAge: number;
myRealAge = 27;
// myRealAge = '27';
// array
let hobbies: any[] = ['Cooking', 'Sports'];
hobbies = [100];
// hobbies = 100;
// tuples
let address: [string, number] = ['Superstreet', 99];
// enums
enum Color {
Gray, // 0
Green, // 1
Blue // 2
}
let myColor: Color = Color.Green;
console.log(myColor);
enum Color2 {
Gray, // 0
Green = 100, // 100
Blue // 101
}
let myColor2: Color2 = Color2.Green;
console.log(myColor2);
enum Color3 {
Gray, // 0
Green = 100, // 100
Blue = 2, // 2
Red // 3
}
// any
let car: any = 'BMW';
console.log(car);
car = { brand: 'BNW', series: 3 };
console.log(car);
// functions
function returnMyName(): string {
return myName;
}
console.log(returnMyName());
// functions void
function sayHello(): void {
console.log('Hello!');
}
// argument types
function multiply(value1: number, value2: number): number {
return value1 * value2;
}
// console.log(multiply(2, 'Max'));
console.log(multiply(2, 10));
// function types
let myMultiply: (a: number, b: number) => number;
// myMultiply = sayHello;
// myMultiply();
myMultiply = multiply;
console.log(myMultiply(5, 2));
// objects
let userData: { name: string, age: number } = {
name: 'Max',
age: 27
}
// userData = {};
// userData = {
// a: 'hello',
// b: 22
// }
// complex object
let complex: { data: number[], output: (all: boolean) => number[] } = {
data: [100, 3.99, 10],
output: function (all: boolean): number[] {
return this.data;
}
}
// console.log(complex.output(true));
// type alias
type Complex = { data: number[], output: (all: boolean) => number[] };
let complex2: Complex = {
data: [100, 3.99, 10],
output: function (all: boolean): number[] {
return this.data;
}
};
// union types
let myRealRealAge: number | string = 27;
myRealRealAge = '27';
// myRealRealAge = true;
// check types (during runtime)
let finalValue = 30;
if (typeof finalValue == 'number') {
console.log('finalValue is a number');
}
// never type (typescript 2+)
function neverReturns(): never {
throw new Error('An error');
}
// nullable types (typescript 2+)
let canBeNull = 12;
// canBeNull = null; //tsconfig -> "strictNullChecks": true
let canBeNull2: number | null = 12;
canBeNull2 = null;
let canAlsoBeNull;
canAlsoBeNull = null;
let canThisBeAny = null;
// canThisBeAny by default is now type any and not type null
canThisBeAny = 12;
|
f33477b4beae34a8748c95080f19d50e626867be
|
TypeScript
|
manucho007/pwa-ferias5
|
/src/app/core/firestore.service.ts
| 2.828125
| 3
|
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreDocument, AngularFirestoreCollection} from 'angularfire2/firestore';
import { Observable} from 'rxjs/Observable';
import * as firebase from 'firebase/app';
// The T is a Typescript generic that allows us to use our custom interfaces
type CollectionPredicate<T> = string | AngularFirestoreCollection<T>;
type DocPredicate<T> = string | AngularFirestoreDocument<T>;
@Injectable()
export class FirestoreService {
constructor(private afs: AngularFirestore) { }
// Methods wraps the afsdoc and collection, so the service can be used as a drop and replacement for AngularFirestore
// If we pass a string is going to return a AngularFirestoreCollection ref
// But if we pass a ref, then it'll just returnthe ref
col<T>(ref:CollectionPredicate<T>,queryFn?):AngularFirestoreCollection<T>{
return typeof ref ==='string' ? this.afs.collection<T>(ref,queryFn): ref;
}
doc<T>(ref:DocPredicate<T>):AngularFirestoreDocument<T>{
return typeof ref ==='string' ? this.afs.doc<T>(ref): ref;
}
// Thank to the changes in angularfire2 the Reference is decoupled from the observable data
// ****Get Data ****** Snapshot
doc$<T>(ref: DocPredicate<T>):Observable<T>{
return this.doc(ref).snapshotChanges().map(doc=>{
return doc.payload.data() as T;
})
}
col$<T>(ref:CollectionPredicate<T>,queryFn?):Observable<T[]>{
return this.col(ref, queryFn).snapshotChanges().map(docs =>{
return docs.map(a=>a.payload.doc.data()) as T[];
})
}
// return the collection with the ids
colWithIds$<T>(ref:CollectionPredicate<T>,queryFn?):Observable<any[]>{
return this.col(ref,queryFn).snapshotChanges().map(actions =>{
return actions.map(a=>{
const data = a.payload.doc.data();
const id = a.payload.doc.id;
return {id,...data};
});
});
}
// **Get Data RealTime
realTcol$<T>(ref:CollectionPredicate<T>,queryFn?):Observable<T[]>{
return this.col(ref, queryFn).valueChanges();
}
realTdoc$<T>(ref: DocPredicate<T>):Observable<T>{
return this.doc(ref).valueChanges();
}
// Write Data
// firebase serve timestamp
get timestamp() {
return firebase.firestore.FieldValue.serverTimestamp()
}
//****Custom Methods
// Custom update method
update<T>(ref: DocPredicate<T>, data: any) {
return this.doc(ref).update({
...data,
updatedAt: this.timestamp
})
}
// custom set method
set<T>(ref: DocPredicate<T>, data: any) {
const timestamp = this.timestamp
return this.doc(ref).set({
...data,
updatedAt: timestamp,
createdAt: timestamp
})
}
// Custom add Method
add<T>(ref: CollectionPredicate<T>, data) {
const timestamp = this.timestamp
return this.col(ref).add({
...data,
updatedAt: timestamp,
createdAt: timestamp
})
}
// Use of geopoint
geopoint(lat: number, lng: number) {
return new firebase.firestore.GeoPoint(lat, lng);
}
}
|
7069b6ac04fe002c9bb8966f91627e48cd13c602
|
TypeScript
|
NaturalCycles/time-lib
|
/src/types.ts
| 3.140625
| 3
|
export type ConfigType = string | number | Date | IDayjs
export type OptionType = { locale?: string; format?: string; utc?: boolean } | string
export type UnitTypeShort = 'd' | 'M' | 'y' | 'h' | 'm' | 's' | 'ms'
export type UnitType =
| 'millisecond'
| 'second'
| 'minute'
| 'hour'
| 'day'
| 'month'
| 'year'
| 'date'
| UnitTypeShort
export type OpUnitType = UnitType | 'week' | 'w'
export type QUnitType = UnitType | 'quarter' | 'Q'
export type PluginFunc<T = unknown> = (option: T, c: IDayjsFactory, d: IDayjsFactory) => void
export type WeekdayNames = [string, string, string, string, string, string, string]
export type MonthNames = [
string,
string,
string,
string,
string,
string,
string,
string,
string,
string,
string,
string,
]
export interface IDayjsFactory {
(cfg?: ConfigType, option?: OptionType, locale?: string): IDayjs
(cfg?: ConfigType, option?: OptionType, strict?: boolean): IDayjs
unix: (t: number) => IDayjs
extend: <T = unknown>(plugin: PluginFunc<T>, option?: T) => IDayjsFactory
locale: (
preset?: string | IDayjsLocale,
object?: Partial<IDayjsLocale> | null,
isLocal?: boolean,
) => string
isDayjs: (d: any) => d is IDayjs
// Plugins are copy-pasted there now:
utc: (config?: ConfigType, format?: string) => IDayjs
max: ((dayjs: IDayjs[]) => IDayjs) & ((...dayjs: IDayjs[]) => IDayjs)
min: ((dayjs: IDayjs[]) => IDayjs) & ((...dayjs: IDayjs[]) => IDayjs)
updateLocale: (localeName: string, customConfig: Record<string, any>) => any
Ls: { [localeName: string]: IDayjsLocale }
}
export interface IDayjs {
clone: () => IDayjs
isValid: () => boolean
year: (() => number) & ((value: number) => IDayjs)
month: (() => number) & ((value: number) => IDayjs)
date: (() => number) & ((value: number) => IDayjs)
day: (() => number) & ((value: number) => IDayjs)
hour: (() => number) & ((value: number) => IDayjs)
minute: (() => number) & ((value: number) => IDayjs)
second: (() => number) & ((value: number) => IDayjs)
millisecond: (() => number) & ((value: number) => IDayjs)
set: (unit: UnitType, value: number) => IDayjs
get: (unit: UnitType) => number
add: (value: number, unit: OpUnitType) => IDayjs
subtract: (value: number, unit: OpUnitType) => IDayjs
startOf: (unit: OpUnitType) => IDayjs
endOf: (unit: OpUnitType) => IDayjs
format: (template?: string) => string
diff: (date: ConfigType, unit?: QUnitType | OpUnitType, float?: boolean) => number
// Forbid the method in favor of .unixMillis()
// valueOf(): number
unix: () => number
daysInMonth: () => number
toDate: () => Date
toJSON: () => string
// Forbid the method in favor of .toISODate()
// toISOString(): string
toString: () => string
utcOffset: (() => number) & ((offset: number) => IDayjs)
isBefore: (date: ConfigType, unit?: OpUnitType) => boolean
isSame: (date: ConfigType, unit?: OpUnitType) => boolean
isAfter: (date: ConfigType, unit?: OpUnitType) => boolean
locale: (() => string) &
((preset: string | IDayjsLocale, object?: Partial<IDayjsLocale>) => IDayjs) &
((preset?: string | IDayjsLocale, object?: Partial<IDayjsLocale>, isLocal?: boolean) => string)
// default plugin here
/**
* Returns ISO date, e.g `2018-06-21`
*/
toISODate: () => string
/**
* Returns e.g `2018-06-21 17:54:21`
* or `2018-06-21 17:54` (with seconds=false)
*
* @param seconds defauls to true
*/
toPretty: (seconds?: boolean) => string
/**
* Returns e.g `20180621_1754` or `20180621_175404` (with seconds).
* seconds @default to false
*/
toCompactTime: (seconds?: boolean) => string
/**
* Returns e.g `20180621`
*/
toCompactDate: () => string
/**
* Returns unixtime in milliseconds.
*/
unixMillis: () => number
/**
* Shortcut for .startOf('day')
*
* @deprecated, cause it's not a well-defined method. Should be a Factory-method instead.
*/
today: () => IDayjs
// isoWeekDay plugin here
/**
* 1: Monday
* ...
* 6: Saturday
* 7: Sunday
*/
isoWeekday: (() => number) & ((setWeekday: number) => this)
// weekOfYear plugin here
/**
* Returns iso week number (where week starts on Monday)
*/
week: () => number
/**
* Set date to NEXT date that satisfies the week number.
*/
// week (value: number): Dayjs // not supported
// copy-pasting plugin types here for now
// isBetween
isBetween: (a: ConfigType, b: ConfigType, c?: OpUnitType | null, d?: string) => boolean
utc: () => IDayjs
local: () => IDayjs
isUTC: () => boolean
isSameOrAfter: (date: ConfigType, unit?: OpUnitType) => boolean
isSameOrBefore: (date: ConfigType, unit?: OpUnitType) => boolean
fromNow: (withoutSuffix?: boolean) => string
from: (compared: ConfigType, withoutSuffix?: boolean) => string
toNow: (withoutSuffix?: boolean) => string
to: (compared: ConfigType, withoutSuffix?: boolean) => string
/**
* Returns internal locale data
*/
$locale: () => IDayjsLocale
localeData: () => GlobalLocaleDataReturn
}
export interface IDayjsLocale {
name: string
weekdays: string[]
months: string[] | any // todo
weekStart?: number
yearStart?: number
weekdaysShort?: string[]
monthsShort?: string[]
weekdaysMin?: string[]
meridiem?: any
ordinal?: (n: number) => number | string
formats: Partial<{
LT: string
LTS: string
L: string
LL: string
LLL: string
LLLL: string
}>
relativeTime: Partial<{
future: string
past: string
s: string
m: string
mm: string
h: string
hh: string
d: string
dd: string
M: string
MM: string
y: string
yy: string
}>
}
export interface RelativeTimeThreshold {
l: string
r?: number
d?: string
}
export interface RelativeTimeOptions {
rounding?: (num: number) => number
thresholds?: RelativeTimeThreshold[]
}
export interface GlobalLocaleDataReturn {
firstDayOfWeek: () => number
weekdays: () => WeekdayNames
weekdaysShort: () => WeekdayNames
weekdaysMin: () => WeekdayNames
months: () => MonthNames
monthsShort: () => MonthNames
longDateFormat: (format: string) => string
meridiem: (hour?: number, minute?: number, isLower?: boolean) => string
}
|
5413348b56b30884b59fa37b927e5efac6291c84
|
TypeScript
|
marcospmail/rocketseat-gobarber-13
|
/backend/src/modules/users/repositories/fakes/FakeUsersRepository.ts
| 2.71875
| 3
|
import { v4 } from 'uuid'
import ICreateUserDTO from '@modules/users/dtos/ICreateUserDTO'
import User from '@modules/users/infra/typeorm/entities/User'
import IUsersRepository from '@modules/users/repositories/IUsersRepository'
import IFindAllProvidersDTO from '@modules/users/dtos/IFindAllProvidersDTO'
class FakeUsersRepository implements IUsersRepository {
private users: User[] = []
public async findAllProviders({
except_user_id
}: IFindAllProvidersDTO): Promise<User[]> {
let { users } = this
if (except_user_id) {
users = users.filter(u => u.id !== except_user_id)
}
return users
}
public async findById(id: string): Promise<User | undefined> {
const userFound = this.users.find(u => u.id === id)
return userFound
}
public async findByEmail(email: string): Promise<User | undefined> {
const userFound = this.users.find(u => u.email === email)
return userFound
}
public async create(user: ICreateUserDTO): Promise<User> {
const newUser = new User()
Object.assign(newUser, { id: v4() }, user)
this.users.push(newUser)
return newUser
}
public async save(user: User): Promise<User> {
const userIndex = this.users.findIndex(u => u.id === user.id)
this.users[userIndex] = user
return user
}
}
export default FakeUsersRepository
|
49c309a61cf1f4c4ad6459b13694c13be143c928
|
TypeScript
|
KazumasaYasui/riakuto3.1
|
/04-typescript/03-function-class/composition.ts
| 2.71875
| 3
|
import { Rectangle } from "./rectangle";
export class SquareC {
readonly name = 'square';
side: number;
constructor(side: number) {
this.side = side;
}
getArea = () => new Rectangle(this.side, this.side).getArea();
}
|
80b9b8f651cca82567633a3e6600a223222b924b
|
TypeScript
|
Vermouth1995/MatchThreeGame
|
/src/engine/score.ts
| 2.703125
| 3
|
import PuzzleKeeper from "./puzzle_keeper";
import Goal from "./goal/goal";
import BoardOn from "./board/board_on";
import CoordinateValue from "../concept/coordinate/coordinate_value";
import Coordinate from "../concept/coordinate/coordinate";
import Locus from "../concept/coordinate/locus";
import Font from "../concept/style/font";
import Color from "../concept/style/color";
import Once from "../concept/once/once";
import OnceLast from "../concept/once/once_last";
import EventLocationSetter from "../concept/coordinate/event/event_location_setter";
import EventMove from "../concept/coordinate/event/event_move";
import ListenerDiffusion from "../concept/listener/listener_diffusion";
import Listener from "../concept/listener/listener";
import AtomString from "../render/atom/atom_string";
import Puzzle from "../render/puzzle";
import Render from "../render/render";
export default class Score implements PuzzleKeeper {
private static readonly SIZE = new CoordinateValue(5, 1.5);
private static readonly STEP_ADD_TIME_COST_PER_STEP: number = 200;
private static readonly LEVEL_Z_INDEX: number = 1;
private static readonly GOAL_Z_INDEX: number = 2;
private static readonly STEP_Z_INDEX: number = 1;
private static readonly LEVEL_LOCATION: Coordinate = new CoordinateValue(0.75, 0.75);
private static readonly GOAL_LOCATION: Coordinate = new CoordinateValue(1, 0.25);
private static readonly GOAL_LOCATION_END: Coordinate = new CoordinateValue(4, 0.25);
private static readonly STEP_LOCATION: Coordinate = new CoordinateValue(4.25, 0.75);
private color: Color = new Color(0, 0, 0);
private font: Font = new Font().setSize(0.5).setAlign(Font.ALIGN_CENTER);
private step: number = 1;
private stepRender: Locus<number> = new Locus<number>(this.step);
private level: string = "unknown";
private levelRender: Locus<string> = new Locus<string>(this.level.toString());
private puzzle: Puzzle = new Puzzle();
constructor() {
this.puzzle.setSize(Score.SIZE);
this.puzzle.addAtom(
new AtomString(this.stepRender, new Locus<Color>(this.color), new Locus<Font>(this.font)),
new Locus<Coordinate>(Score.STEP_LOCATION),
Score.STEP_Z_INDEX
);
this.puzzle.addAtom(
new AtomString(this.levelRender, new Locus<Color>(this.color), new Locus<Font>(this.font)),
new Locus<Coordinate>(Score.LEVEL_LOCATION),
Score.LEVEL_Z_INDEX
);
}
private goals: Goal[] = [];
addGoal(goals: Goal[]) {
this.goals = goals;
const successEnd: Once = new OnceLast().setCallback(() => {
this.end(true);
});
this.goals.map((goal: Goal, index: number) => {
const puzzle = goal.getPuzzle();
this.puzzle.addChild(
puzzle,
new Locus<Coordinate>(
new CoordinateValue(
((Score.GOAL_LOCATION_END.getRow() - Score.GOAL_LOCATION.getRow()) / (this.goals.length + 1)) *
(index + 1) +
Score.GOAL_LOCATION.getRow() -
puzzle.size().getRow() / 2,
Score.GOAL_LOCATION.getCol()
)
),
Score.GOAL_Z_INDEX
);
goal.onSuccess.on(successEnd.getCallback());
});
}
private on: BoardOn;
setOn(on: BoardOn) {
this.on = on;
this.on.onStep.on(() => {
this.stepMinus();
});
this.on.onFallEnd.on(() => {
if (this.step == 0) {
this.end(false);
}
});
}
setLevel(level: string) {
this.level = level;
this.levelRender.setEvent(new EventLocationSetter<string>(this.level));
}
setStep(step: number) {
this.step = step;
this.stepRender.setEvent(new EventLocationSetter<number>(this.step));
}
private stepMinus() {
if (this.step == 0) {
return;
}
this.step--;
this.stepRender.setEvent(new EventLocationSetter<number>(this.step));
if (this.step == 0) {
this.onStepEnd.trigger();
}
}
stepAdd(newStep: number) {
const finalStep: number = this.step + newStep;
this.stepRender.setEvent(
new EventMove<number>(
finalStep,
newStep * Score.STEP_ADD_TIME_COST_PER_STEP,
true,
(from, to, timecost, relativeTime) => Math.floor(this.step + (newStep * relativeTime) / timecost)
)
);
this.step = finalStep;
}
private isEnd: boolean = false;
private end(success: boolean) {
if (this.isEnd) {
return;
}
this.isEnd = true;
this.onEnd.trigger(success);
}
readonly onEnd: Listener<void, (success: boolean) => void> = new ListenerDiffusion();
readonly onStepEnd: Listener<void, () => void> = new ListenerDiffusion();
resizePuzzle(size: Coordinate): void {}
getPuzzle(): Puzzle {
return this.puzzle;
}
static LoadStaticResource(render: Render, onSuccess: () => void, onError: (error: Error) => void) {
onSuccess();
}
}
|
169921b9a845cbbe1f4092148d641086e0011361
|
TypeScript
|
Morbden/fluido-nextjs-utils
|
/src/utils.ts
| 2.75
| 3
|
import { fetchAPI } from '@fluido/react-utils'
import deepmerge from 'deepmerge'
interface NextStaticPropsReturn {
props: { [key: string]: any }
revalidate?: number
notFound?: boolean
}
interface ComputeFunctionParams {
params?: {
[key: string]: any
}
preview?: boolean
previewData?: any
locale?: string
locales?: string[]
defaultLocale?: string
}
interface ComputeFunction {
(data: ComputeFunctionParams): any | Promise<any>
}
export const joinStaticProps = (...fns: ComputeFunction[]) => {
let config = {}
if (typeof fns[fns.length - 1] === 'object') {
config = fns.pop()
}
return async (data: ComputeFunctionParams) => {
try {
const results = await Promise.all(fns.map((fn) => fn(data)))
return {
props: results.reduce((prev, cur) => deepmerge(prev, cur), {}),
revalidate: 1,
...config,
} as NextStaticPropsReturn
} catch (err) {
if (err && typeof err === 'object' && !(err instanceof Error))
return {
revalidate: 5,
...config,
...err,
} as NextStaticPropsReturn
return {
revalidate: 5,
notFound: true,
...config,
} as NextStaticPropsReturn
}
}
}
const deepField = (field: string, val: any) => {
if (field.length < 1) throw new Error('invalid field name')
const list = field.split('.')
if (list.length === 1) return { [field]: val }
const lastField = list.pop()
return list.reverse().reduce(
(prev, field) => {
return { [field]: prev }
},
{ [lastField]: val },
)
}
type GetStaticFetchURIType = (data?: ComputeFunctionParams) => RequestInfo
type GetStaticFetchOptionsType = (data?: ComputeFunctionParams) => RequestInit
export const getStaticFetch = (
name: string,
uri: RequestInfo | GetStaticFetchURIType,
opt?: RequestInit | GetStaticFetchOptionsType,
) => {
return async (data: ComputeFunctionParams) => {
const result = await fetchAPI(
typeof uri === 'function' ? uri(data) : uri,
opt ? (typeof opt === 'function' ? opt(data) : opt) : {},
)
if (result.data) {
return deepField(name, result.data || {})
} else {
return deepField(name, result.dataText || '')
}
}
}
type GetStaticInternalFunctionType = (
data: ComputeFunctionParams,
) => any | Promise<any>
export const getStaticInternal = (
name: string,
fn: GetStaticInternalFunctionType,
) => {
return async (data: ComputeFunctionParams) =>
deepField(name, await Promise.resolve(fn(data)))
}
|
6e6a2dc4f83f94855af6125b9ccbc02d6c22cd99
|
TypeScript
|
sanity-io/sanity
|
/packages/sanity/src/core/form/__workshop__/_common/data.ts
| 2.59375
| 3
|
import {Schema} from '@sanity/schema'
import type {Schema as SchemaSchema} from '@sanity/types'
import {keyBy, mapValues} from 'lodash'
import getSimpleDummySchema from './schema/simpleDummySchema'
import getSimpleFieldGroupSchema from './schema/simpleFieldGroupSchema'
export const DUMMY_DOCUMENT_ID = '10053a07-8647-4ebd-9d1d-33a512d30d3a'
interface SchemaMapType {
name: string
title?: string
schema: (props: WorkshopSchemaProps) => unknown
}
type SchemaKey = Readonly<SchemaMapType[]>[number]['name']
export interface WorkshopSchemaProps {
schemaKey?: SchemaKey
hiddenGroup?: boolean
}
export function wrapSchema(schema: unknown) {
return {
name: 'test',
types: [schema],
}
}
const schemaMap: Readonly<SchemaMapType[]> = [
{
name: 'simple',
title: 'Simple',
schema: getSimpleDummySchema,
},
{
name: 'simpleFieldGroup',
title: 'Simple w/ Field Group',
schema: getSimpleFieldGroupSchema,
},
] as const
export const schemaListOptions = mapValues(keyBy(schemaMap, 'title'), 'name')
export function getDummyDocument() {
return {
_createdAt: '2021-11-04T15:41:48Z',
_id: DUMMY_DOCUMENT_ID,
_rev: '5hb8s6-k75-ip4-4bq-5ztbf3fbx',
_type: 'book',
_updatedAt: '2021-11-05T12:34:29Z',
title: 'Hello world',
person: {
name: 'Fred',
},
}
}
export function getDummySchema(props: WorkshopSchemaProps): SchemaSchema {
const {schemaKey = 'simple'} = props
const schemaType = schemaMap.find((s) => s.name === schemaKey)
const schema = schemaType?.schema(props)
return Schema.compile(schema)
}
|
de03a892f5e6acc9df076ece6fa8f018780f15ff
|
TypeScript
|
andhikanugraha/sharades
|
/src/lib/TopicEncoding.ts
| 2.625
| 3
|
import { inflate, deflate } from '@progress/pako-esm';
import type { Topic } from './topic';
import { btoaUrl, atobUrl } from './base64url';
const SEPARATOR = '\x1F';
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder('utf-8');
export async function deflateTopicWords(words: string[]): Promise<Uint8Array> {
return deflate(textEncoder.encode(words.join(SEPARATOR)));
}
export async function inflateTopicWords(
wordsBuffer: Uint8Array,
): Promise<string[]> {
return textDecoder.decode(inflate(wordsBuffer)).split(SEPARATOR);
}
export async function encodeTopic(topicObj: Topic): Promise<string> {
const titleBinary = textEncoder.encode(topicObj.title);
const deflatedWordsBinary = await deflateTopicWords(topicObj.words);
return `${btoaUrl(titleBinary)}.${btoaUrl(deflatedWordsBinary)}`;
}
// For use in Game.vue, receiving path in URL
export async function decodeTopic(topicString: string): Promise<Topic> {
const [titleB64, deflatedWordsB64] = topicString.split('.');
return {
title: textDecoder.decode(atobUrl(titleB64)),
words: await inflateTopicWords(atobUrl(deflatedWordsB64)),
};
}
export async function decodeTopicDeflated(topicString: string): Promise<{
title: string,
deflatedWords: Uint8Array,
}> {
const [titleB64, deflatedWordsB64] = topicString.split('.');
return {
title: textDecoder.decode(atobUrl(titleB64)),
deflatedWords: atobUrl(deflatedWordsB64),
};
}
|
9e7bbfad5e6d0d5a1ccd053c120be5a1da873096
|
TypeScript
|
HaifengDu/ts-ds-tool
|
/src/heap/__test__/Heap.test.ts
| 3.78125
| 4
|
import { MaxHeap } from "../MaxHeap";
import { MinHeap } from "../MinHeap";
describe("MaxHeap test", () => {
test("should create an empty max heap", () => {
const maxHeap = new MaxHeap<number>();
expect(maxHeap).toBeDefined();
expect(maxHeap.peek()).toBeNull();
expect(maxHeap.isEmpty()).toBe(true);
});
test("should add items to the heap and heapify it up", () => {
const maxHeap = new MaxHeap<number>();
maxHeap.add(10);
expect(maxHeap).toBeDefined();
expect(maxHeap.isEmpty()).toBe(false);
expect(maxHeap.peek()).toBe(10);
expect(maxHeap.toString()).toBe("10");
maxHeap.add(5);
expect(maxHeap.peek()).toBe(10);
expect(maxHeap.toString()).toBe("10,5");
maxHeap.add(12);
expect(maxHeap.peek()).toBe(12);
expect(maxHeap.toString()).toBe("12,5,10");
maxHeap.add(3);
expect(maxHeap.peek()).toBe(12);
expect(maxHeap.toString()).toBe("12,5,10,3");
maxHeap.add(7);
expect(maxHeap.peek()).toBe(12);
expect(maxHeap.toString()).toBe("12,7,10,3,5");
expect(maxHeap.poll()).toBe(12);
expect(maxHeap.toString()).toBe("10,7,5,3");
expect(maxHeap.poll()).toBe(10);
expect(maxHeap.toString()).toBe("7,3,5");
expect(maxHeap.poll()).toBe(7);
expect(maxHeap.toString()).toBe("5,3");
expect(maxHeap.poll()).toBe(5);
expect(maxHeap.toString()).toBe("3");
expect(maxHeap.poll()).toBe(3);
expect(maxHeap.isEmpty()).toBe(true);
});
test("should find items in heap", () => {
const maxHeap = new MaxHeap<number>();
maxHeap.add(5);
maxHeap.add(12);
maxHeap.add(7);
expect(maxHeap.find(item => item === 5)).not.toBeNull();
expect(maxHeap.find(5)).not.toBeNull();
expect(maxHeap.findAll(item => item === 5)).toEqual([5]);
expect(maxHeap.findAll(5)).toEqual([5]);
});
test("should poll empty to heap", () => {
const maxHeap = new MaxHeap<number>();
maxHeap.add(5);
expect(maxHeap.poll()).toBe(5);
expect(maxHeap.poll()).toBeNull();
});
test("should entries to heap", () => {
const maxHeap = new MaxHeap<number>();
maxHeap.add(5);
maxHeap.add(7);
expect(maxHeap.entries()).toEqual([7, 5]);
});
});
describe("MinHeap test", () => {
test("should create an empty max heap", () => {
const minHeap = new MinHeap<number>();
expect(minHeap).toBeDefined();
expect(minHeap.peek()).toBeNull();
expect(minHeap.isEmpty()).toBe(true);
});
test("should add items to the heap and heapify it up", () => {
const minHeap = new MinHeap<number>();
minHeap.add(10);
expect(minHeap.isEmpty()).toBe(false);
expect(minHeap.peek()).toBe(10);
minHeap.add(5);
expect(minHeap.peek()).toBe(5);
expect(minHeap.toString()).toBe("5,10");
minHeap.add(7);
expect(minHeap.peek()).toBe(5);
expect(minHeap.toString()).toBe("5,10,7");
minHeap.add(8);
expect(minHeap.peek()).toBe(5);
expect(minHeap.toString()).toBe("5,8,7,10");
minHeap.add(3);
expect(minHeap.peek()).toBe(3);
expect(minHeap.toString()).toBe("3,5,7,10,8");
expect(minHeap.poll()).toBe(3);
expect(minHeap.toString()).toBe("5,8,7,10");
expect(minHeap.poll()).toBe(5);
expect(minHeap.toString()).toBe("7,8,10");
expect(minHeap.poll()).toBe(7);
expect(minHeap.toString()).toBe("8,10");
expect(minHeap.poll()).toBe(8);
expect(minHeap.toString()).toBe("10");
expect(minHeap.poll()).toBe(10);
expect(minHeap.toString()).toBe("");
expect(minHeap.isEmpty()).toBe(true);
});
test("MinHeap delete test", () => {
const minHeap = new MinHeap<number>();
minHeap.add(5);
minHeap.add(15);
minHeap.remove(5);
expect(minHeap.find(5)).toBeNull();
minHeap.add(5);
minHeap.add(7);
minHeap.remove(5);
expect(minHeap.find(5)).toBeNull();
minHeap.add(12);
minHeap.add(6);
minHeap.remove(6);
minHeap.remove(item => item === 12);
minHeap.remove(15);
minHeap.remove(7);
expect(minHeap.find(15)).toBeNull();
expect(minHeap.Size).toBe(0);
minHeap.add(6);
minHeap.add(8);
minHeap.add(10);
minHeap.add(14);
minHeap.add(5);
minHeap.add(7);
minHeap.remove(6);
minHeap.remove(10);
minHeap.remove(5);
minHeap.remove(14);
minHeap.remove(8);
minHeap.remove(7);
expect(minHeap.Size).toBe(0);
});
test("MinHeap empty test", () => {
const minHeap = new MinHeap<number>();
minHeap.add(5);
minHeap.add(15);
minHeap.clear();
expect(minHeap.Size).toBe(0);
});
});
describe("Heap Gen test", () => {
test("MaxHeap Gen test", () => {
const maxHeap = new MaxHeap<{value: number}>("value");
maxHeap.add({value: 10});
expect(maxHeap).toBeDefined();
expect(maxHeap.isEmpty()).toBe(false);
expect(maxHeap.peek()).toEqual({value: 10});
maxHeap.add({value: 5});
expect(maxHeap.peek()).toEqual({value: 10});
maxHeap.add({value: 12});
expect(maxHeap.peek()).toEqual({value: 12});
maxHeap.add({value: 3});
expect(maxHeap.peek()).toEqual({value: 12});
maxHeap.add({value: 7});
expect(maxHeap.peek()).toEqual({value: 12});
expect(maxHeap.poll()).toEqual({value: 12});
expect(maxHeap.poll()).toEqual({value: 10});
expect(maxHeap.poll()).toEqual({value: 7});
expect(maxHeap.poll()).toEqual({value: 5});
expect(maxHeap.poll()).toEqual({value: 3});
expect(maxHeap.isEmpty()).toBe(true);
});
test("MinHeap Gen test", () => {
const minHeap = new MinHeap<{value: number}>("value");
minHeap.add({value: 10});
expect(minHeap.isEmpty()).toBe(false);
expect(minHeap.peek()).toEqual({value: 10});
minHeap.add({value: 5});
expect(minHeap.peek()).toEqual({value: 5});
minHeap.add({value: 7});
expect(minHeap.peek()).toEqual({value: 5});
minHeap.add({value: 8});
expect(minHeap.peek()).toEqual({value: 5});
minHeap.add({value: 3});
expect(minHeap.peek()).toEqual({value: 3});
expect(minHeap.poll()).toEqual({value: 3});
expect(minHeap.poll()).toEqual({value: 5});
expect(minHeap.poll()).toEqual({value: 7});
expect(minHeap.poll()).toEqual({value: 8});
expect(minHeap.poll()).toEqual({value: 10});
expect(minHeap.isEmpty()).toBe(true);
});
});
|
c0d04f1389f81fe9e9c4bec944fa674631b69ad3
|
TypeScript
|
Daria0109/Todolist_ReactTS
|
/src/features/Login/auth-reducer.test.ts
| 2.703125
| 3
|
import {AuthStateType, authReducer, setIsLoggedIn, setLogin} from './auth-reducer';
let startState: AuthStateType;
beforeEach(() => {
startState = {
isLoggedIn: false,
login: null
}
})
test('loggedIn status should be set to the state', () => {
const endState = authReducer(startState, setIsLoggedIn({isLoggedIn: true}))
expect(endState.isLoggedIn).toBeTruthy()
})
test('login should be set to the state', () => {
const endState = authReducer(startState, setLogin({login: 'someuser@email.com'}))
expect(endState.login).toBe('someuser@email.com')
})
|
6457e5781649329f137c09ae4ea55f97bf47d498
|
TypeScript
|
VincentVen/Framing
|
/src2/modules/games/dzpk/newGameScene/caiSanZhangWindow/CaiSanZhangBuyItem.ts
| 2.53125
| 3
|
/**
* 猜三张购买列表item
* @author none
*/
class CaiSanZhangBuyItem extends how.module.ItemView {
public title: eui.Label;
public odds: eui.Label;
public multipleBtn1: how.CheckBox;
public multipleBtn5: how.CheckBox;
public multipleBtn10: how.CheckBox;
public constructor() {
super();
this.skinName = "CaiSanZhangBuyItemSkin";
this.multipleBtn1.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onMultipleBtn1, this);
this.multipleBtn5.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onMultipleBtn5, this);
this.multipleBtn10.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onMultipleBtn10, this);
}
public dataChanged(): void {
this.title.text = this.data.title;
this.odds.text = this.data.odds;
this.multipleBtn1.selected = this.data.selected == 1;
this.multipleBtn5.selected = this.data.selected == 5;
this.multipleBtn10.selected = this.data.selected == 10;
}
public onMultipleBtn1(): void {
this.multipleBtn5.selected = false;
this.multipleBtn10.selected = false;
var caiSanZhangData = base.Utils.getLocalStorageItem(StorageKeys.DZPKCSZData, "Object");
caiSanZhangData.betNumber[this.itemIndex] = 1;
egret.localStorage.setItem(StorageKeys.DZPKCSZData, JSON.stringify(caiSanZhangData));
}
public onMultipleBtn5(): void {
this.multipleBtn1.selected = false;
this.multipleBtn10.selected = false;
var caiSanZhangData = base.Utils.getLocalStorageItem(StorageKeys.DZPKCSZData, "Object");
caiSanZhangData.betNumber[this.itemIndex] = 5;
egret.localStorage.setItem(StorageKeys.DZPKCSZData, JSON.stringify(caiSanZhangData));
}
public onMultipleBtn10(): void {
this.multipleBtn1.selected = false;
this.multipleBtn5.selected = false;
var caiSanZhangData = base.Utils.getLocalStorageItem(StorageKeys.DZPKCSZData, "Object");
caiSanZhangData.betNumber[this.itemIndex] = 10;
egret.localStorage.setItem(StorageKeys.DZPKCSZData, JSON.stringify(caiSanZhangData));
}
}
|
1a735743d9d00b06a5e531101d5cd001f18b127e
|
TypeScript
|
AdanGaitan/ProyectoPracticaAngular
|
/src/app/directiva/directiva.component.ts
| 2.59375
| 3
|
import { Component, OnInit } from '@angular/core';
interface Producto{
nombre:string;
stock:number;
fabricante:string;
fechaVence:Date;
esImportante:boolean;
}
@Component({
selector: 'app-directiva',
templateUrl: './directiva.component.html',
styleUrls: ['./directiva.component.scss']
})
export class DirectivaComponent implements OnInit {
cargando: boolean=true;
nombres : Array<string>=["Maria","Ana","Juan","Pedro"];
pestana:string="";
mostrarCuadrado:boolean = false;
productos : Array<Producto>=[
{
nombre: 'Arroz',
stock:15,
fabricante : 'Distribuidor Industrial',
fechaVence: new Date('04/15/2021'),
esImportante: true
},
{
nombre: 'Fideos',
stock:20,
fabricante : 'Merolio',
fechaVence: new Date('07/15/2021'),
esImportante: false
},
{
nombre: 'Polenta',
stock:200,
fabricante : 'Distribuidor Industrial',
fechaVence: new Date('04/20/2021'),
esImportante: false
}
]
constructor() { }
ngOnInit(): void {
setTimeout(() => {
this.cargando =false;
}, 5000);
}
alternar(){
this.cargando = !this.cargando;
}
cambiarPestana(pestana:string){
this.pestana=pestana;
}
alternarFondo(){
this.mostrarCuadrado = !this.mostrarCuadrado;
}
}
|
c41b30387aea8ea007e2c3850b72ddf900ae22ab
|
TypeScript
|
bravc/myfavoritepart
|
/src/config/passport.ts
| 2.546875
| 3
|
import passport from 'passport';
const LocalStrategy = require('passport-local').Strategy;
import * as bcrypt from 'bcrypt-nodejs';
import { User } from '../models/User';
import { Request } from 'express';
export let local = passport.use('local',
new LocalStrategy({passReqToCallback : true}, async (req: Request, username: string, password: string, done: any) => {
const user = await User.findOne({ where: { username: username } });
if (user) {
if (bcrypt.compareSync(password, user.password)) {
return done(null, user);
}
} else {
const user = new User({
username: username,
password: bcrypt.hashSync(password)
});
await user.save();
console.log(user);
return done(null, user);
}
return done(null, false, {message: 'Invalid Username or Password'});
})
);
passport.serializeUser(function(user: User, done) {
console.log('tried to serialize');
done(null, user.id);
});
passport.deserializeUser(function(id: number, done) {
User.findById(id).then(user => {
done(null, user);
});
});
export default passport;
|
f0a2acd8a1f91644ea0a6adfdf84f4639a161a6a
|
TypeScript
|
tusharmath/qio
|
/packages/benchmarks/Stream/Stream.ts
| 2.671875
| 3
|
/**
* Created by tushar on 09/09/19
*/
import {QIO} from '@qio/core'
import {Suite} from 'benchmark'
import {PrintLn} from '../internals/PrintLn'
import {qioRuntime} from '../internals/RunSuite'
const suite = new Suite('QStream')
const count = 1e6
const arr = new Array<number>()
for (let i = 0; i < count; i++) {
arr.push(i)
}
const qioIteration = QIO.encase((numbers: number[]) => {
let sum = 0
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i]
}
return sum
})
const qioRecursion = (numbers: number[]) => {
const itar = (i: number, sum: number): QIO<number> =>
i === numbers.length
? QIO.resolve(sum)
: QIO.call(itar, i + 1, sum + numbers[i])
return itar(0, 0)
}
suite
.add(
'Recursion',
(cb: IDefer) =>
qioRuntime.unsafeExecute(qioRecursion(arr), () => cb.resolve()),
{defer: true}
)
.add(
'Iterative',
(cb: IDefer) =>
qioRuntime.unsafeExecute(qioIteration(arr), () => cb.resolve()),
{defer: true}
)
.on('cycle', (event: Event) => {
PrintLn(String(event.target))
})
.on('complete', function (this: Suite): void {
PrintLn(
'Fastest is ' +
this.filter('fastest')
.map((i: {name: string}) => i.name)
.join('')
)
})
.run()
|
dbadfc7e6c496ba718179c0c0f21ee00d5e52d74
|
TypeScript
|
kyeah/undercov
|
/src/storageObject.ts
| 2.96875
| 3
|
/**
* Configurable options for each repo.
*/
export type Repo = {
repoName: string,
branchUrlTemplate: string,
prUrlTemplate: string,
pathPrefix: string,
authUrlTemplate: string
}
/**
* Value object to encapsulate options.
*/
export interface IStorageObject {
overlayEnabled: boolean
debugEnabled: boolean
filetreeCoverageEnabled: boolean
debug_url: any
repos: Repo[]
}
export class StorageObject implements IStorageObject {
get overlayEnabled(): boolean {
return this._overlayEnabled
}
set overlayEnabled(value: boolean) {
this._overlayEnabled = value
}
get filetreeCoverageEnabled(): boolean {
return this._filetreeCoverageEnabled
}
set filetreeCoverageEnabled(value: boolean) {
this._filetreeCoverageEnabled = value
}
get debugEnabled(): boolean {
return this._debugEnabled
}
set debugEnabled(value: boolean) {
this._debugEnabled = value
}
get debug_url(): any {
return false
}
get repos(): Repo[] {
return this._repos
}
set repos(value: Repo[]) {
this._repos = value
}
constructor(
private _overlayEnabled: boolean = true,
private _debugEnabled: boolean = false,
private _filetreeCoverageEnabled: boolean = true,
private _repos: Repo[] = []
) {
}
}
|
006fa70f245b867632fa0985d29be7f8d7625cd0
|
TypeScript
|
atayahmet/cs-algorithms
|
/queue/src/index.ts
| 2.65625
| 3
|
import Queue from './queue';
const queue = new Queue;
console.log(queue.isEmpty());
queue.add(1);
queue.add(2);
queue.add(3);
console.log(queue.peek());
console.log('remove->', queue.remove());
console.log(queue.peek());
console.log('remove->', queue.remove());
console.log(queue.peek());
console.log('remove->', queue.remove());
console.log(queue.peek());
|
95821c73d4024893961dc29bcdda331ce04e3085
|
TypeScript
|
amazinglynormal/forex-dashboard
|
/src/utils/calculateOneYearAgo.ts
| 2.578125
| 3
|
export const calculateOneYearAgo = () => {
const today = new Date();
const date = today.getDate();
const month = today.getMonth() + 1;
const year = today.getFullYear() - 1;
return `${year}-${month < 10 ? "0" : ""}${month}-${
date < 10 ? "0" : ""
}${date}..`;
};
|
cb72e60a27f4dd07966ce5aa5950f2d624d11836
|
TypeScript
|
gabrielgouv/rockr
|
/packages/rockr-core/src/utils/string-utils.ts
| 2.71875
| 3
|
import * as _ from 'lodash'
export const parseToKebabCase = (text: string): string => {
return _.kebabCase(text)
}
export const parseToSnakeCase = (text: string): string => {
return _.snakeCase(text)
}
export const generateIdByName = (text: string): string => {
return _.uniqueId(_.snakeCase(text) + '_')
}
|
e0c6c1bc490fc5bb0250eadc550df74fe57dda80
|
TypeScript
|
lmeijvogel/my_node_openzwave
|
/ZWaveValueChangeListener.ts
| 2.59375
| 3
|
import { Configuration } from "./Configuration";
import { Logger } from "./Logger";
import { Node } from "./Node";
import { MyZWave } from "./MyZWave";
export class ZWaveValueChangeListener {
switchPressed: (node: Node, sceneId: number) => void = (_node, _sceneId) => {};
constructor(private readonly myZWave: MyZWave, private config: Configuration) {}
init() {
this.myZWave.onValueChange(this.onValueChange);
}
isSceneEvent(commandClass: number): boolean {
return commandClass === 43;
}
private onValueChange = (node: Node, commandClass, value) => {
if (node.nodeId === 3) {
Logger.error(
"ERROR: Main switch is now probably ignored by OpenZWave. Exiting process so it can be restarted."
);
throw "Main switch erroneously ignored. Exiting!";
}
const lightById = this.config.findLightById(node.nodeId);
if (!lightById) {
Logger.error(`Unknown light with nodeId ${node.nodeId}. Command class: ${commandClass}, value: "${JSON.stringify(value)}"`);
return;
}
const lightName = lightById.name;
const light = this.config.findLightByName(lightName);
if (!light) {
Logger.error(
`Unknown light with name "${lightName}" (id: ${
node.nodeId
}). Command class: ${commandClass}, value: "${JSON.stringify(value)}"`
);
return;
}
if (this.isSceneEvent(parseInt(commandClass, 10))) {
const sceneId = parseInt(value.value, 10);
Logger.debug(`Received scene event from ${lightName}: sceneId: ${sceneId}`);
this.switchPressed(node, sceneId);
return;
}
light.values[commandClass] = value;
Logger.debug(`Received value change from ${node.nodeId}. Raw value: ${JSON.stringify(value)}`);
const valueToString = `${value.value_id}, ${value.label}`;
Logger.debug(`New value for node ${node.nodeId}: ${valueToString}`);
this.myZWave.onNodeEvent((node: Node, event: number) => {
Logger.debug(`Event from node ${node.nodeId}: ${event}. No longer processed.`);
});
}
}
|
6410d9f9714b7f5c0946ef8828a0aec90fe6dd28
|
TypeScript
|
aesthetic-suite/framework
|
/packages/utils/src/toArray.ts
| 3.078125
| 3
|
export function toArray<T>(value: T | T[]): T[] {
if (value === undefined) {
return [];
}
return Array.isArray(value) ? value : [value];
}
|
68f7973f5e36d345c65236fcd3c1e9b6ececf95f
|
TypeScript
|
sk13/MyCalliopeSymCryptoExtension
|
/main.ts
| 2.875
| 3
|
/**
* Functionallity to do symmetric encryption / decryption.
*
*
*/
//% weight=2 color=#f2c10d icon="\uf21b"
//% advanced=true
//% groups=['1 Encryption','2 Communication',]
namespace Crypto {
class KeyValue {
key: number;
value: string;
}
class KeyValueStore {
m_Store: Array<KeyValue>
constructor() {
this.m_Store = [];
}
put(key: number, value: string): KeyValue {
let kv = new KeyValue;
kv.key = key;
kv.value = value;
this.m_Store.push(kv);
return kv;
}
getKeyValue(key: number): KeyValue {
let i: number;
for (i = 0; i < this.m_Store.length; i++) {
if (this.m_Store[i].key == key) {
return this.m_Store[i];
}
}
return null;
}
}
let onReceivedMessageHandler: (args: onReceivedMessageArguments) => void;
let onReceivedBytesHandler: (args: onReceivedMessageArguments) => void;
let receivedMessages: KeyValueStore = new KeyValueStore();
/**
* Encrypt a message with the given key.
*/
//% weight=10
//% blockId=symcrypto_encrypt
//% block="encrypt the message %msg| with key %key"
//% group="Encryption"
export function encrypt(msg: string = "", key: string = ""): number[] {
let inp: number[] = strToUTF8(msg);
let keyb: number[] = strToUTF8(key);
let keylen = keyb.length;
let outp: number[] = [];
//let outstr: string = "";
let i: number;
for (i = 0; i < inp.length; i++) {
let c: number;
c = inp[i] + keyb[i % keylen];
c %= 256;
outp[i] = c;
// outstr += String.fromCharCode(c);
}
return outp;
}
/**
* Decrypt a ciphertext with the given key.
*/
//% weight=9
//% blockId=symcrypto_decrypt
//% block="decrypts the ciphertext %c| with key %key"
//% group="Encryption"
export function decrypt(c: number[], key: string = ""): string {
let keyb: number[] = strToUTF8(key);
let keylen = keyb.length;
let outp: number[] = [];
let outstr: string = "";
let i: number;
for (i = 0; i < c.length; i++) {
let cc: number = c[i];
let p: number;
p = cc - keyb[i % keylen] + 256; //ensure p>0;
p %= 256;
outp.push(p);
}
outstr = UTF8toStr(outp);
return outstr;
}
function internal_sendString(str: string, typeisstring: boolean) {
if (!str)
return;
let len: number = str.length;
let index: number = 0;
let s: string = "";
let space = 19;
while (len > 0) {
if (space > 1) {
s += str.charAt(index);
if (str.charCodeAt(index) > 127) {
space -= 2
}
else {
space -= 1;
}
index++;
len--;
}
else if (space == 1 && str.charCodeAt(index) < 128) {
s += str.charAt(index);
space--;
index++;
len--;
}
else {
radio.sendString(s);
space = 19;
s = "";
}
}
if (s.length > 0) //send remaining part...
{
radio.sendString(s);
}
len = str.length;
if (typeisstring == false) {
len += 10000;
}
radio.sendNumber(len); //end of message
}
/**
* Send a large message (up to 2413 bytes).
*/
//% weight=8
//% blockId=symcrypto_sendmsg block="send the message |%msg|"
//% group="Communication"
export function sendMsg(msg: string = ""): void {
internal_sendString(msg, true);
}
/**
* Send some bytes (up to 2413 bytes).
*/
//% weight=7
//% blockId=symcrypto_sendbytes block="send some bytes |%bytes|"
//% group="Communication"
export function sendBytes(bytes: number[]): void {
let strEncoded: string = encodeBinary(bytes);
internal_sendString(strEncoded, false);
}
/**
* Reads a (possibly long) line (terminate by a Line Feed (Code: 10)) from serial.
*/
//% weight=11
//% blockId=symcrypto_readlinefromserial
//% block="read a line from serial"
//% group="Serial"
/* export function readLineFromSerial(): string {
let s: string = "";
while (true) {
let k: string = serial.readString()
if (k.length > 0) {
s += k
if (k.substr(-1).charCodeAt(0) === 10) {
break;
}
}
}
return s.substr(0, s.length - 1);
}
*/
function proccessReceivedPacket(packet: radio.Packet): void {
let sender: number = packet.serial;
if (sender == 0)//no sender given --> ignore...
{
return;
}
let s: string = packet.receivedString;
let sm: KeyValue = receivedMessages.getKeyValue(sender);
if (!sm) {
sm = receivedMessages.put(sender, "");
}
if (s.length > 0) {
sm.value += s;
return;
}
let n: number = packet.receivedNumber;
if (n > 0) {
let bIsBytes: boolean = false;
if (n >= 10000) {
bIsBytes = true;
n -= 10000;
}
if (n === sm.value.length) {
let args: onReceivedMessageArguments = new onReceivedMessageArguments;
if (bIsBytes === false) //it is a string
{
args.receivedMsg = sm.value;
if (onReceivedMessageHandler) {
onReceivedMessageHandler(args);
}
}
else //they are bytes
{
let bytes: number[] = decodeBinary(sm.value);
args.receivedBytes = bytes;
if (onReceivedBytesHandler) {
onReceivedBytesHandler(args);
}
}
}
sm.value = "";
}
}
export class onReceivedMessageArguments {
receivedMsg: string;
receivedBytes: number[];
}
/**
* Registers code to run after a message was received.
*/
//% mutate=objectdestructuring
//% mutateText="My Arguments"
//% mutateDefaults="receivedMsg"
//% blockId=crypto_on_receive_str
//% block="on msg received"
// draggableParameters=reporter
//% group="Communication"
//% weight=6
export function onReceivedMessage(cb: (args: onReceivedMessageArguments) => void): void {
radio.onDataPacketReceived(proccessReceivedPacket);
onReceivedMessageHandler = cb;
}
/**
* Registers code to run after some bytes were received.
*/
//% mutate=objectdestructuring
//% mutateText="My Arguments"
//% mutateDefaults="receivedBytes"
//% blockId=crypto_on_receive_bytes
//% block="on msg received"
// draggableParameters=reporter
//% group="Communication"
//% weight=5
export function onReceivedBytes(cb: (args: onReceivedMessageArguments) => void): void {
radio.onDataPacketReceived(proccessReceivedPacket);
onReceivedBytesHandler = cb;
}
function createBufferFromArray(bytes: number[], offset: number, len: number): Buffer {
let buf: Buffer = pins.createBuffer(len);
for (let i = 0; i < len; ++i)
buf[i] = bytes[i + offset];
return buf;
}
function encodeBinary(bytes: number[]): string {
let s: string = "";
let i: number = 0;
for (i = 0; i < bytes.length; i++) {
let b: number = bytes[i]
if (b < 3) { // encode 0 --> 2 2 ; 1 --> 2 2; 2 --> 2 3
s += String.fromCharCode(2);
s += String.fromCharCode(b + 2);
}
else {
s += String.fromCharCode(b);
}
}
return s;
}
function decodeBinary(str: string): number[] {
let s: string = "";
let i: number = 0;
let bytes: number[] = [];
while (i < str.length) {
let b: number = str.charCodeAt(i++);
if (b == 2) {
b = str.charCodeAt(i++) - 2;
}
bytes.push(b);
}
return bytes;
}
function UTF8toStr(bytes: number[]): string {
let len: number = bytes.length;
let str: string = "";
let i: number = 0;
let b1: number;
let b2: number;
while (i < len) {
b1 = bytes[i++];
if (b1 < 0x80) {
str += String.fromCharCode(b1);
}
else {
b2 = bytes[i++];
let code: number = b1 - 0xC0;
code <<= 6;
b2 -= 0x80;
code += b2;
str += String.fromCharCode(code);
}
}
return str;
}
function strToUTF8(str: string): number[] {
let utf8: number[] = [];
for (let i = 0; i < str.length; i++) {
let charcode = str.charCodeAt(i);
if (charcode < 0x80) utf8.push(charcode);
else if (charcode < 0x800) {
utf8.push(0xc0 | (charcode >> 6));
utf8.push(0x80 | (charcode & 0x3f));
}
else if (charcode < 0xd800 || charcode >= 0xe000) {
utf8.push(0xe0 | (charcode >> 12));
utf8.push(0x80 | ((charcode >> 6) & 0x3f));
utf8.push(0x80 | (charcode & 0x3f));
}
// surrogate pair
else {
i++;
charcode = ((charcode & 0x3ff) << 10) | (str.charCodeAt(i) & 0x3ff)
utf8.push(0xf0 | (charcode >> 18));
utf8.push(0x80 | ((charcode >> 12) & 0x3f));
utf8.push(0x80 | ((charcode >> 6) & 0x3f));
utf8.push(0x80 | (charcode & 0x3f));
}
}
return utf8;
}
}
/*
namespace pxsim.Crypto {
export function getRxBufferSize(): number {
return 0;
}
}
*/
|
987fbad614f4a151583d1d892537dcd6cc82954d
|
TypeScript
|
emilybache/SupermarketReceipt-Refactoring-Kata
|
/typescript/src/model/ProductQuantity.ts
| 2.578125
| 3
|
import {Product} from "./Product"
export class ProductQuantity {
constructor(public readonly product: Product,
public readonly quantity: number) {
this.product = product;
this.quantity = quantity;
}
}
|
2d450bccf9de0e8116212fa1a7caddddb4aea1b1
|
TypeScript
|
makeevvd/Table
|
/my-app/src/hooks/useChildrenSort.ts
| 2.59375
| 3
|
import {DataInterface, DataInterfaceWithChildren} from "../components/Table/Table";
import {useMemo} from "react";
export const useChildrenSort = (tableData: DataInterface[]): DataInterfaceWithChildren[] => {
const parentElements = tableData.filter((dataElement) => dataElement.parentId === 0);
const parentsWithChildren = useMemo(() => {
const parents = parentElements.map(
(parentElem) => {
const childrenElements = tableData.filter((childElem) => childElem.parentId === parentElem.id);
return { ...parentElem, childElements: childrenElements}
}
);
return parents
}
, []);
return parentsWithChildren
}
|
baed1519c7ca5ea7da723cae74f120297d322b27
|
TypeScript
|
saffi-codefresh/datadog-api-client-typescript
|
/packages/datadog-api-client-v2/models/IncidentFieldAttributesMultipleValue.ts
| 2.640625
| 3
|
/**
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2020-Present Datadog, Inc.
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { IncidentFieldAttributesValueType } from "./IncidentFieldAttributesValueType";
import { ObjectSerializer } from "./ObjectSerializer";
/**
* A field with potentially multiple values selected.
*/
export class IncidentFieldAttributesMultipleValue {
"type"?: IncidentFieldAttributesValueType;
/**
* The multiple values selected for this field.
*/
"value"?: Array<string>;
"unparsedObject"?: any;
static readonly discriminator: string | undefined = undefined;
static readonly attributeTypeMap: {
[key: string]: { baseName: string; type: string; format: string };
} = {
type: {
baseName: "type",
type: "IncidentFieldAttributesValueType",
format: "",
},
value: {
baseName: "value",
type: "Array<string>",
format: "",
},
};
static getAttributeTypeMap() {
return IncidentFieldAttributesMultipleValue.attributeTypeMap;
}
static deserialize(data: {
[key: string]: any;
}): IncidentFieldAttributesMultipleValue {
const res = new IncidentFieldAttributesMultipleValue();
if (
[
"multiselect",
"textarray",
"metrictag",
"autocomplete",
undefined,
].includes(data.type)
) {
res.type = data.type;
} else {
const raw = new IncidentFieldAttributesMultipleValue();
raw.unparsedObject = data;
return raw;
}
res.value = ObjectSerializer.deserialize(data.value, "Array<string>", "");
return res;
}
static serialize(data: IncidentFieldAttributesMultipleValue): {
[key: string]: any;
} {
const attributeTypes =
IncidentFieldAttributesMultipleValue.getAttributeTypeMap();
const res: { [index: string]: any } = {};
for (const [key, value] of Object.entries(data)) {
if (!(key in attributeTypes)) {
throw new TypeError(`${key} attribute not in schema`);
}
}
if (data?.unparsedObject !== undefined) {
return data.unparsedObject;
}
if (
[
"multiselect",
"textarray",
"metrictag",
"autocomplete",
undefined,
].includes(data.type)
) {
res.type = data.type;
} else {
throw TypeError(`invalid enum value ${data.type} for type`);
}
res.value = ObjectSerializer.serialize(data.value, "Array<string>", "");
return res;
}
public constructor() {}
}
|
7c963352725e36713222d1348fb7a45a0fdb7b17
|
TypeScript
|
softwaresauna/ts-template
|
/src/hello.ts
| 3.015625
| 3
|
export class Person {
constructor(public readonly name: string) {}
}
export function hello(person: Person): string {
return `Hello, ${person.name}!`;
}
|
e14d96169f27cd463060a99d351d56d61be4af6b
|
TypeScript
|
haimich/copyundpasta
|
/test/utils/CategoryUtilTest.ts
| 2.65625
| 3
|
import CategoryUtil from "@/utils/CategoryUtil";
describe("getAllArticleCategories", () => {
test("should return parent and child categories", () => {
let categories = CategoryUtil.getAllArticleCategories();
// console.log(categories);
});
});
describe("getAllRecipeCategories", () => {
test("should return parent and child categories", () => {
let categories = CategoryUtil.getAllRecipeCategories();
// console.log(categories);
});
});
describe("getUniqueArticleCategoryId", () => {
test("should return empty string if category is invalid", () => {
let categories = CategoryUtil.getAllArticleCategories();
expect(CategoryUtil.getUniqueArticleCategoryId("blablupp", categories.categoriesById)).toEqual("");
});
// TODO comment in when category with parent is introduced
// test("should return concatenated id", () => {
// let categories = CategoryUtil.getAllArticleCategories();
// expect(CategoryUtil.getUniqueArticleCategoryId("rezepte", categories.categoriesById)).toEqual("rezepte_herzhaft");
// });
test("should return category id when no parent is present", () => {
let categories = CategoryUtil.getAllArticleCategories();
expect(CategoryUtil.getUniqueArticleCategoryId("rezepte", categories.categoriesById)).toEqual("rezepte");
});
});
describe("getUniqueRecipeCategoryId", () => {
test("should return empty string if category is invalid", () => {
let categories = CategoryUtil.getAllRecipeCategories();
expect(CategoryUtil.getUniqueRecipeCategoryId("blablupp", categories.categoriesById)).toEqual("");
});
test("should return concatenated id", () => {
let categories = CategoryUtil.getAllRecipeCategories();
expect(CategoryUtil.getUniqueRecipeCategoryId("frostings", categories.categoriesById)).toEqual("kuchen_frostings");
});
test("should return category id when no parent is present", () => {
let categories = CategoryUtil.getAllRecipeCategories();
expect(CategoryUtil.getUniqueRecipeCategoryId("desserts", categories.categoriesById)).toEqual("desserts");
});
});
describe("getFullArticleCategoryName", () => {
test("should return empty string is category is invalid", () => {
let categories = CategoryUtil.getAllArticleCategories();
expect(CategoryUtil.getFullArticleCategoryName("blablupp", categories.categoriesById)).toEqual("");
});
// TODO comment in when category with parent is introduced
// test("should return category and parent name", () => {
// let categories = CategoryUtil.getAllArticleCategories();
// expect(CategoryUtil.getFullArticleCategoryName("herzhaft", categories.categoriesById)).toEqual("Rezepte Herzhaft");
// });
test("should return category name when no parent is present", () => {
let categories = CategoryUtil.getAllArticleCategories();
expect(CategoryUtil.getFullArticleCategoryName("rezepte", categories.categoriesById)).toEqual("Rezepte");
});
});
describe("getFullRecipeCategoryName", () => {
test("should return empty string is category is invalid", () => {
let categories = CategoryUtil.getAllRecipeCategories();
expect(CategoryUtil.getFullRecipeCategoryName("blablupp", categories.categoriesById)).toEqual("");
});
test("should return category and parent name", () => {
let categories = CategoryUtil.getAllRecipeCategories();
expect(CategoryUtil.getFullRecipeCategoryName("frostings", categories.categoriesById)).toEqual("Kuchen Frostings");
});
test("should return category name when no parent is present", () => {
let categories = CategoryUtil.getAllRecipeCategories();
expect(CategoryUtil.getFullRecipeCategoryName("kuchen", categories.categoriesById)).toEqual("Kuchen");
});
});
|
ca39cfd9b951882f29e3cbd38b705dc020902ff5
|
TypeScript
|
viniciusstroher/app-delivery-poc
|
/src/domain/common/IValueObject.ts
| 2.796875
| 3
|
export interface IValueObject{
equals(compareEntity: IValueObject):boolean;
}
|
456cb7ebffa79e1d829bc9a1a5ec5867caf4c339
|
TypeScript
|
Tidyzq/Blog-Front-Console
|
/src/utils/redux.ts
| 2.703125
| 3
|
import { Action, Reducer } from 'redux'
import { ThunkAction } from 'redux-thunk'
export const handleActions = <S>(reducerMap: { [type: string]: Reducer<S, any> }, defaultState: S): Reducer<S> => (prevState, action) => {
const state = prevState || defaultState
const actionType = action.type
if (actionType && reducerMap[actionType]) return reducerMap[actionType](state, action)
return state
}
export const createThunkAction = <R, S, E, A extends Action>(thunkAction: ThunkAction<R, S, E, A>): ThunkAction<R, S, E, A> & R => thunkAction as ThunkAction<R, S, E, A> & R
|
12976e5d7853ec16844d50008e14694c86169028
|
TypeScript
|
Akachu/five-gigabyte-of-free-storage
|
/src/modules/fileManager/reducer.ts
| 2.671875
| 3
|
import { createReducer } from 'typesafe-actions';
import { FileManagerAction } from './types';
import { FileManagerState } from './interface';
import {
REQUEST_FILE_UPLOAD,
REQUEST_FILE_DOWNLOAD,
COMPLETE_FILE_REQUEST,
} from './actions';
const initialState: FileManagerState = {
requests: [],
};
const fileManage = createReducer<FileManagerState, FileManagerAction>(
initialState,
{
[REQUEST_FILE_UPLOAD]: (state, action) => {
const { requests } = state;
const newRequest = [...requests, action.payload];
return {
...state,
requests: newRequest,
};
},
[REQUEST_FILE_DOWNLOAD]: (state, action) => {
const { requests } = state;
const newRequest = [...requests, action.payload];
return {
...state,
requests: newRequest,
};
},
[COMPLETE_FILE_REQUEST]: (state, action) => {
const { key } = action.payload;
const { requests } = state;
const index = requests.findIndex((info) => info.key === key);
if (index !== -1) {
requests[index].completed = true;
}
return {
requests,
};
},
},
);
export default fileManage;
|
0ccd5dbf001bae980fe62113e63bb7e7a4141e53
|
TypeScript
|
cyrt63/demos
|
/JSXGraph/conic.ts
| 2.515625
| 3
|
var graph = JXG.JSXGraph;
var popUp: Window = open("", "", "width=800, height=600");
var css = '<link rel="stylesheet" type="text/css" href="http://jsxgraph.uni-bayreuth.de/distrib/jsxgraph.css" />';
popUp.document.documentElement.innerHTML = css+'<div id="box" class="jxgbox" style="width:800px; height:600px;"></div>'
popUp.document.title = "JXG.Conic";
popUp.document.body.style.backgroundColor = "CCCCCC";
popUp.document.body.style.overflow = "hidden";
var div = popUp.document.getElementById("box");
div.style.width = "760px";
div.style.height = "560px";
var board = graph.initBoard("box", {axis:true, grid:true, keepaspectratio: true, showCopyright:false, document: popUp.document});
// Create a conic section through the points A, B, C, D, and E.
var A = board.create('point', [1,5]);
var B = board.create('point', [1,2]);
var C = board.create('point', [2,0]);
var D = board.create('point', [0,0]);
var E = board.create('point', [-1,5]);
var conic = board.create('conic', [A, B, C, D, E]);
function tick(time: number) {
// We can use the variables to drive other windows!
}
function terminate(time: number) {
return false;
}
function setUp() {
}
function tearDown() {
popUp.close();
}
// May need to make sure that JSXGraph and animationRunner play well together?
var war = eight.animationRunner(tick, terminate, setUp, tearDown, popUp.window);
war.start();
|
317a9ab2125d3ccb0fd6a484beb4e48ca514e033
|
TypeScript
|
edgars1337/nim-js
|
/src/nim/node.ts
| 3.234375
| 3
|
import {isEqual} from 'lodash-es';
export class Node {
// TODO - fix accesses
public piles: number[] = [];
public heuristicValue: number = 0;
public childList: Node[] = [];
constructor(piles: number[], parent: Node | null = null) {
if (parent === null) {
this.piles = piles;
this.childList = [];
} else {
parent.childList.push(this);
this.piles = piles;
this.childList = [];
}
}
// creating a "new" array so in Nim class we aren't editing this nodes array
getPiles = (): number[] => JSON.parse(JSON.stringify(this.piles));
getChildList = (): Node[] => this.childList;
getHeuristicValue = (): number => this.heuristicValue;
setHeuristicValue = (val: number): void => {
this.heuristicValue = val;
}
isEmpty = (): boolean => this.piles.every((val) => val === 0);
equals = (givenNode: Node | null): boolean => {
if (givenNode === this) {
return true;
}
if (givenNode === null) {
return false;
}
return isEqual(this.piles, givenNode.piles)
}
}
export default Node;
|
ab4ad5e3c997d8542f9aab8a0341ddc0c9232542
|
TypeScript
|
grok88/gato
|
/src/app/reducers/auth-reducer.ts
| 2.671875
| 3
|
const initialState = {};
type AuthStateType = typeof initialState;
export const authReducer = (state: AuthStateType = initialState, action: ActionsType): AuthStateType => {
return state
}
type ActionsType = any;
|
3176a00e99eb0d6b49d7ed777f7255a851744ef1
|
TypeScript
|
PRossetti/wp-typescript-expressjs-api
|
/src/routes/artist/releaseData/releaseData.controller.ts
| 2.59375
| 3
|
import { Request, Response, NextFunction } from 'express';
import AritstReleaseDataService, { queryMany } from '@services/ArtistReleaseData.service';
class ArtistReleaseDataController {
static async get(req: Request, res: Response, next: NextFunction): Promise<void> {
try {
const {
params: { id, name },
} = req;
const query = { id, name };
const result = await AritstReleaseDataService.getOne(query);
res.json(result || null);
} catch (err) {
next(err);
}
}
static async getMany(req: Request, res: Response, next: NextFunction): Promise<void> {
try {
const { query } = req;
const result = await AritstReleaseDataService.getMany(query as queryMany);
res.json(result);
} catch (err) {
next(err);
}
}
}
export default ArtistReleaseDataController;
|
3115eb8d8a37ae7612aa8c4125d07df9390c629e
|
TypeScript
|
arturdedela/patterns-lab2
|
/src/commands/ChangeBorderWidthCommand.ts
| 2.53125
| 3
|
import { Command } from "./abstract/Command";
import { IShapeEditor } from "../Editor/Editor";
export class ChangeBorderWidthCommand extends Command {
private readonly width: number;
constructor(editor: IShapeEditor, width: number) {
super(editor);
this.width = width;
}
execute(): void {
this.saveBackup();
this.editor.changeBorderWidth(this.width);
}
}
|
6708a5bb15ffe01dc692f7c4a039d6d1248ab8b4
|
TypeScript
|
udacity-jhon/serveless-typescript
|
/src/functions/auth/rs256Auth0Authorizer/handler.ts
| 2.59375
| 3
|
import { CustomAuthorizerEvent, CustomAuthorizerResult } from 'aws-lambda'
import 'source-map-support/register';
import {JwtToken} from "../aut0Authorizer/JwtToken";
import {verify} from 'jsonwebtoken';
const cert = `-----BEGIN CERTIFICATE-----
MIIDDTCCAfWgAwIBAgIJRDj/IhBbmmVAMA0GCSqGSIb3DQEBCwUAMCQxIjAgBgNV
BAMTGWRldi00a2FzY3BhOC51cy5hdXRoMC5jb20wHhcNMjEwMTEwMjA1NDM4WhcN
MzQwOTE5MjA1NDM4WjAkMSIwIAYDVQQDExlkZXYtNGthc2NwYTgudXMuYXV0aDAu
Y29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzFAI98mMeMz+zLNR
SgSAx2vAJklwsGIYCW0Zd2mjERJUq9MEai5dF3DDqrDaU4utthdyIRinAzb3+rsK
+pAUZgb5pgPq0br9ZbAnDhLIXYNw/Cau0l8/oVpNeThqViJZNSydMtgt4xn5f1CJ
XSBxdzUGHnRVAhViURKkuifBb4btOt3L1chIzpzg27c8cdQ2tKFVn3vDX/0Ns/wX
KoSTHW/0ImRvkHEj6Lo030+g7nRXmTtn9MBHOUp9058/+CHzdduAc+7XVOBE2jEW
sp8QgEXce1jW+pguYsJO40DIt+DIjFl1Tu2U0pQo9AWllo2DbpNr92mugdCsHmH6
ElFdewIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBT1m+14JEiB
Uj4a90EEcfQQnFcj4jAOBgNVHQ8BAf8EBAMCAoQwDQYJKoZIhvcNAQELBQADggEB
AHQ9L5sjIo6vHTAGLWwnFRhNZvkf44CpQjtDzjClfGxEm8tH+CsKo1snNX0Qu38C
yYIPLfWoD7Fd1fv08IGfdlCprc/4Lup63F7Br/Dop1Y4/xojNGbNBYUI/XHCyPNy
izhUYl2EEFnV61Sm7pJXMIC+wyLiDmcAcpG16bC3JAxGRWG4tluAG8SVYEaDMLhl
Jg9D3agFY/PHI48D54AHWTBksgYOCG65eFnDyT9qenGzoCTx1ieywKJ/7yAbMHRR
Z1ecg7HcAe+phRU+g4m2VY98DVpv7PhwlOlgF767F3Sk1JVnI7w88gUoflfxNFIT
4JrWsdZzwLRL/TSUSOwqtqY=
-----END CERTIFICATE-----`
async function verifyToken(authorizationToken: string) {
if (!authorizationToken) {
throw new Error("No authorization header");
}
if (!authorizationToken.toLocaleLowerCase().startsWith("bearer ")) {
throw new Error("Invalid authorization header");
}
const split = authorizationToken.split(" ");
const token = split[1];
console.log("Doing the verification", token, cert.toString());
return verify(
token, // Token from an HTTP header to validate
cert, // A certificate copied from Auth0 website
{algorithms: ['RS256']} // We need to specify that we use the RS256 algorithm
) as JwtToken
}
export const main = async (event: CustomAuthorizerEvent): Promise<CustomAuthorizerResult> => {
try {
const decodedToken = await verifyToken(event.authorizationToken)
console.log('User was authorized', decodedToken.sub)
return {
principalId: decodedToken.sub,
policyDocument: {
Version: '2012-10-17',
Statement: [
{
Action: 'execute-api:Invoke',
Effect: 'Allow',
Resource: '*'
}
]
}
}
} catch (e) {
console.log('User was not authorized', e.message)
return {
principalId: 'user',
policyDocument: {
Version: '2012-10-17',
Statement: [
{
Action: 'execute-api:Invoke',
Effect: 'Deny',
Resource: '*'
}
]
}
}
}
}
|
ccaa9874c526422fd895949b50de2ab218823937
|
TypeScript
|
risen619/swapi
|
/src/app/store/effects/character.effects.ts
| 2.578125
| 3
|
import { Injectable } from '@angular/core';
import { Actions, Effect, ofType } from '@ngrx/effects';
import { Action } from '@ngrx/store';
import { Observable, of } from 'rxjs';
import { mergeMap, catchError, switchMap } from 'rxjs/operators';
import * as CActions from '../actions/character.actions';
import * as FActions from '../actions/film.actions';
import * as SpeciesActions from '../actions/species.actions';
import * as StarshipsActions from '../actions/starship.actions';
import { CharactersApiService } from 'src/app/services/api';
import { CharacterModel } from 'src/app/models/character';
@Injectable()
export class CharacterEffects
{
constructor(private actions$: Actions, private api: CharactersApiService) { }
private getActionsForField<T extends Action>(models: CharacterModel[], field: FieldTypes, TYPE: { new(id: string): T; }) : T[]
{
const set = models.reduce((p, c) => {
c[field].forEach(i => p.add(i));
return p;
}, new Set<String>());
let actions = [];
for(let i of set)
{
const id = (i.match(/\/(\d+)\/?/) || [])[1];
id && actions.push(new TYPE(id));
}
return actions;
}
private fetchSubsets(models: CharacterModel[])
{
return [
...this.getActionsForField(models, 'films', FActions.LoadFilm),
...this.getActionsForField(models, 'species', SpeciesActions.LoadOneSpecies),
...this.getActionsForField(models, 'starships', StarshipsActions.LoadStarship)
];
}
@Effect()
getCharacters$: Observable<Action> = this.actions$.pipe(
ofType<CActions.LoadCharacters>(CActions.CharacterActionTypes.LoadCharacters),
mergeMap(() =>
{
return this.api.getCharacters().pipe(
switchMap(r => [new CActions.LoadCharactersSuccess(r.results), ...this.fetchSubsets(r.results)]),
catchError(e => of(new CActions.LoadCharactersFailed(e)))
);
})
);
@Effect()
getCharacter$: Observable<Action> = this.actions$.pipe(
ofType<CActions.LoadCharacter>(CActions.CharacterActionTypes.LoadCharacter),
mergeMap(a =>
{
return this.api.getCharacter(a.payload).pipe(
switchMap(r => [new CActions.LoadCharacterSuccess(r), ...this.fetchSubsets([r])]),
catchError(e => of(new CActions.LoadCharacterFailed(e)))
);
})
);
}
type FieldTypes = 'films' | 'species' | 'starships';
|
624dc7bc42059d461cb1af39af0b510543cf966c
|
TypeScript
|
TiE23/somethingjunk
|
/typescript/quizzes/src/tictactoe/__tests__/index.test.ts
| 3.421875
| 3
|
import { Game } from "../index";
describe("Tic-Tac-Toe Game", () => {
it("should work correctly", () => {
expect(true).toBe(true);
});
describe("given a full board with X as the winner", () => {
const game = new Game();
game.makeMove({ player: "X", coord: [0, 0] });
game.makeMove({ player: "O", coord: [1, 0] });
game.makeMove({ player: "X", coord: [2, 0] });
game.makeMove({ player: "O", coord: [0, 1] });
game.makeMove({ player: "X", coord: [1, 1] });
game.makeMove({ player: "O", coord: [2, 1] });
game.makeMove({ player: "X", coord: [1, 2] });
game.makeMove({ player: "O", coord: [0, 2] });
game.makeMove({ player: "X", coord: [2, 2] });
it("should report X as the winner", () => {
const winner = game.getWinner();
expect(winner).toBe("X");
});
it("should report no moves are left", () => {
const movesLeft = game.anyMovesLeft();
expect(movesLeft).toBe(false);
});
});
describe("given a full board with no winner", () => {
const game = new Game();
game.makeMove({ player: "X", coord: [0, 0] });
game.makeMove({ player: "O", coord: [1, 0] });
game.makeMove({ player: "X", coord: [2, 0] });
game.makeMove({ player: "O", coord: [1, 1] });
game.makeMove({ player: "X", coord: [0, 1] });
game.makeMove({ player: "O", coord: [2, 1] });
game.makeMove({ player: "X", coord: [1, 2] });
game.makeMove({ player: "O", coord: [0, 2] });
game.makeMove({ player: "X", coord: [2, 2] });
it("should report no winner", () => {
const winner = game.getWinner();
expect(winner).toBeNull();
});
it("should report no moves are left", () => {
const movesLeft = game.anyMovesLeft();
expect(movesLeft).toBe(false);
});
});
describe("given a new game", () => {
it("should report correct state as the game progresses", () => {
const game = new Game();
game.makeMove({ player: "X", coord: [0, 0] });
expect(game.turn).toBe("O");
expect(game.anyMovesLeft()).toBe(true);
expect(game.getWinner()).toBeNull();
game.makeMove({ player: "O", coord: [0, 1] });
expect(game.turn).toBe("X");
expect(game.anyMovesLeft()).toBe(true);
expect(game.getWinner()).toBeNull();
game.makeMove({ player: "X", coord: [1, 0] });
expect(game.turn).toBe("O");
expect(game.anyMovesLeft()).toBe(true);
expect(game.getWinner()).toBeNull();
game.makeMove({ player: "O", coord: [0, 2] });
expect(game.turn).toBe("X");
expect(game.anyMovesLeft()).toBe(true);
expect(game.getWinner()).toBeNull();
game.makeMove({ player: "X", coord: [2, 0] });
expect(game.turn).toBe("O");
expect(game.anyMovesLeft()).toBe(true);
expect(game.getWinner()).toBe("X");
});
it("should reject a move made by a player out of turn", () => {
const game = new Game();
expect(() => game.makeMove({ player: "X", coord: [0, 0] })).not.toThrow();
expect(() => game.makeMove({ player: "X", coord: [0, 1] })).toThrow();
expect(() => game.makeMove({ player: "O", coord: [0, 1] })).not.toThrow();
});
it("should reject a move out of bounds", () => {
const game = new Game();
// Need TypeScript to ignore this as it is a compile time error.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
expect(() => game.makeMove({ player: "X", coord: [5, -2] })).toThrow();
});
});
});
|
37c3cf4ed1c98b8b473b728cefc9d51247043fbf
|
TypeScript
|
EslavaDev/bingo-unique-co
|
/backend/functions/src/helpers/functions-helpers.ts
| 2.671875
| 3
|
import { limits } from "./dictionary";
export const randomValueBoard = (label: string) => {
const {min, max} = limits(label);
return Math.floor(Math.random() * ((max+1) - min)) + min;
}
export const randomValueGame = () => {
return Math.floor(Math.random() * ((75+1) - 1)) + 1;
}
|
48837edadc923e068b682648a64b61bb4a898408
|
TypeScript
|
Roman1137/saas-template-automation
|
/framework/dataProvider/name.ts
| 3.21875
| 3
|
import {String} from "../helperTypes";
import {RandomDataGenerator} from "./randomDataGenerator";
export class Name {
public static LengthMax(): number {
return 1024;
}
public static LengthMin(): number {
return 3;
}
public static Empty(): string {
return String.Empty;
}
public static Valid(): string {
return RandomDataGenerator.getRandomName(this.nameLengthDefault);
}
public static StartingFromSpace(): string {
return " " + RandomDataGenerator.getRandomName(this.nameLengthDefault);
}
public static WithLengthOf(length: number): string {
return RandomDataGenerator.getRandomName(length);
}
public static ContainingNumers(): string {
const containNumbers = true;
return RandomDataGenerator.getRandomName(this.nameLengthDefault, containNumbers);
}
private static nameLengthDefault: number = 10;
}
|
496a73e8a3f6129ce548a5acb94cf1dc0af47309
|
TypeScript
|
aszecsei/electric-irc
|
/app/renderer/reducers/view-channel.ts
| 2.796875
| 3
|
import { ElectricState } from '../store'
import { IViewChannelAction } from '../actions'
export default function sendMessage(
state: ElectricState,
action: IViewChannelAction
): ElectricState {
let newState = state
newState = newState.set('currentConnectionId', undefined)
newState = newState.set('currentChannelId', undefined)
const conn = state.connections.find(connection => {
return connection.id === action.serverId
})
// If the specified connection exists
if (conn) {
newState = newState.set('currentConnectionId', action.serverId)
const chan = conn.channels.find(channel => {
return channel.id === action.channelId
})
// If the specified channel exists
if (chan) {
newState = newState.set('currentChannelId', action.channelId)
}
}
// console.log(newState.currentChannelId)
return newState
}
|
8554594c56c3d6745c9be1f54cf1cc6880e10dde
|
TypeScript
|
jhonpedro/github-clone
|
/server/src/controllers/RepositoryStarsController.ts
| 2.75
| 3
|
import { Request, Response } from 'express'
import slugify from 'slugify'
import Repository from '../models/Repository.model'
import RepositoryStars from '../models/RepositoryStars.model'
import User from '../models/User.model'
import AppError from '../utils/errors/AppError'
export default {
async star(req: Request, res: Response) {
const userName = req.params.userName as string
const repositorySlug = req.params.repositorySlug as string
const userWhoStarred = await User.findByPk(req.user.id, {
attributes: ['username', 'name'],
})
const trueRepositorySlug = repositorySlug.replace(
`${slugify(userWhoStarred.name.toLocaleLowerCase())}-`,
''
)
const repository = await Repository.findOne({
where: { ownerusername: userName, slug: trueRepositorySlug },
attributes: ['id', 'ispublic'],
})
if (!repository) {
throw new AppError('no repository found for this slug and username', 400)
}
if (!repository.ispublic) {
throw new AppError('this repository is private', 403)
}
const newRepositoryStar = await RepositoryStars.create({
repositoryid: repository.id,
usernamewhostarred: userWhoStarred.username,
})
res.status(201).json({ ...newRepositoryStar.get() })
},
async unstar(req: Request, res: Response) {
const userName = req.params.userName as string
const repositorySlug = req.params.repositorySlug as string
const userWhoStarred = await User.findByPk(req.user.id, {
attributes: ['username'],
})
const trueRepositorySlug = repositorySlug.slice(
repositorySlug.indexOf('-') + 1
)
const repository = await Repository.findOne({
where: { ownerusername: userName, slug: trueRepositorySlug },
attributes: ['id', 'ispublic'],
})
if (!repository) {
throw new AppError('no repository found for this slug and username', 400)
}
if (!repository.ispublic) {
throw new AppError('this repository is private', 403)
}
const isUserFollowingThisRepository = await RepositoryStars.findOne({
where: {
repositoryid: repository.id,
usernamewhostarred: (await userWhoStarred).username,
},
})
if (isUserFollowingThisRepository) {
isUserFollowingThisRepository.destroy()
res.sendStatus(200)
}
throw new AppError('user dont follows this repository', 403)
},
}
|
a97d4a5c332bdf216e38a4b0404e5b7c5af7f523
|
TypeScript
|
rawagner/console
|
/frontend/packages/git-service/src/utils/build-tool-detector.ts
| 2.859375
| 3
|
import { BuildTool, BuildTools, BuildType } from '../types';
export function detectBuildType(files: string[]): BuildType[] {
const buildTypes = BuildTools.map((t: BuildTool) => {
const matchedFiles = files.filter((f: string) => t.expectedRegexps.test(f));
return { buildType: t.type, language: t.language, files: matchedFiles };
});
return buildTypes
.filter((b: BuildType) => b.files.length > 0)
.sort((a, b) => b.files.length - a.files.length);
}
|
5bdd105c44cf469affac100f74e61ac20fa2daeb
|
TypeScript
|
aubert-creation/tmdb-api
|
/src/models/Genre.ts
| 2.890625
| 3
|
export class Genre {
id!: string
name!: string
constructor(init: Genre) {
Object.assign(this, init)
}
}
|
ea9c35511b5e924d825c78ab6a1891d65672a0f9
|
TypeScript
|
tolley/shop
|
/shopfront/src/actions/CartActions.ts
| 3.265625
| 3
|
import { Product } from '../types';
export interface CartState {
items: Array<Product>,
totalPrice: number,
showSummary?: boolean
};
export interface CartData {
items: Array<Product>
};
export type CartAction =
{ type: 'CART_ADD', payload: CartData } |
{ type: 'CART_REMOVE', payload: number };
// Adds product to the shopping cart
export function addToCart(product:Product): CartAction {
return {
type: 'CART_ADD',
payload: {
items: [product]
}
};
}
// Removes product from the shopping cart, assuming it's in the cart
// If it's not in the cart, the current state is returned unchanged
export function removeFromCart(cartPos:number): CartAction {
return {
type: 'CART_REMOVE',
payload: cartPos
};
}
|
d3fa3d9ccb22b53eb693f5b2a81e4f86607da2b0
|
TypeScript
|
SWDV-665/final-project-dking74
|
/server/src/exceptions/ServerErrorResponse.ts
| 2.71875
| 3
|
import BaseErrorResponse from './BaseErrorResponse';
export default class ServerErrorResponse extends BaseErrorResponse {
constructor(errorMessage?: string) {
super(
'An internal server occurred. ' +
`Original Error: ${errorMessage ? errorMessage : ''}`,
500
);
}
}
|
2fb45df83949e7a9bd298a1d52637ec7b9a28a9c
|
TypeScript
|
adanfm/estudos-ts
|
/server/app/errorHandlerApp.ts
| 2.546875
| 3
|
import { Request, Response, ErrorRequestHandler, NextFunction } from 'express'
export function errorHandlerApp(err: ErrorRequestHandler, req: Request, res: Response, next: NextFunction) {
console.error(`APP error handler foi executado: ${err}`);
res.status(500).json({
errorCode: 'ERR-001',
message: 'Internal Server Error'
});
next();
}
|
7f05049ba061762ae0b89a059fec8f0109181df3
|
TypeScript
|
mesfinmetekia/Angular-Login-Page
|
/src/app/dashboard/dashboard.component.ts
| 2.515625
| 3
|
import { Component, OnInit, Output } from '@angular/core';
import { User } from "../user";
import { FormGroup, FormControl, Validators } from '@angular/forms';
import * as EventEmitter from 'events';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
private errorMessage;
private gender;
@Output() getobject = new EventEmitter();
countries: string[] = [
'India',
'USA',
'UK',
'Canada',
'France',
'China',
'Italy'
];
selected(genderType: string) {
this.gender = genderType;
}
validate(password1: string, password2: string) {
if (password1 != password2) {
this.errorMessage = " Confirm Password is not matched !";
}
else {
this.errorMessage = "";
}
}
userList: User[] = [];
form: FormGroup;
Details;
success;
addUser(form) {
this.userList.push(this.form.value);
console.log(this.userList);
this.Details = this.userList;
this.success = true;
}
constructor() { }
ngOnInit() {
this.form = new FormGroup({
name: new FormControl("", [Validators.required,
Validators.pattern("[a-zA-Z][a-zA-Z ]+")]),
userId: new FormControl("", [Validators.required,
Validators.pattern("[a-zA-Z][a-zA-Z0-9_]+")]),
password: new FormControl("", [Validators.required,
, Validators.minLength(5),
Validators.maxLength(15)]),
confirmPassword: new FormControl("", Validators.required),
dateOfBirth: new FormControl("", Validators.required),
gender: new FormControl("male", Validators.required),
country: new FormControl("", Validators.required),
address: new FormControl("", [Validators.required,
Validators.minLength(15), Validators.maxLength(50)]),
pincode: new FormControl("", [Validators.required,
Validators.pattern('[0-9]*'), Validators.maxLength(6),
Validators.maxLength(6)]),
mobileNumber: new FormControl("", [Validators.required,
Validators.pattern('^[6|7|8|9][0-9]*'), Validators.minLength(10),
Validators.maxLength(10)]),
email: new FormControl("", [Validators.required, Validators.email])
})
}
// To check in console whether data is submitting or not
ngSubmit = function (userList) {
this.getobject.emit(userList);
}
}
|
14ccabb735e10262bfd281a01d952cd73eb6dd5d
|
TypeScript
|
JarLob/imodeljs
|
/core/quantity/test/Parsing.test.ts
| 2.671875
| 3
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) 2019 Bentley Systems, Incorporated. All rights reserved.
* Licensed under the MIT License. See LICENSE.md in the project root for license terms.
*--------------------------------------------------------------------------------------------*/
import { assert } from "chai";
import { Parser } from "../src/Parser";
import { UnitProps, BadUnit } from "../src/Interfaces";
import { Format } from "../src/Formatter/Format";
import { Quantity } from "../src/Quantity";
import { TestUnitsProvider } from "./TestUtils/TestHelper";
describe("Parsing tests:", () => {
it("Bad unit", async () => {
let testUnit: UnitProps = new BadUnit();
assert.isTrue(testUnit.name.length === 0);
assert.isTrue(testUnit.label.length === 0);
assert.isTrue(testUnit.unitFamily.length === 0);
assert.isTrue(testUnit.isValid === false);
});
it("Quantity constructor", async () => {
let noUnitQty = new Quantity();
assert.isTrue(noUnitQty.magnitude === 0);
assert.isTrue(noUnitQty.isValid === false);
});
it("Quantity convert Meters to inches", async () => {
const unitsProvider = new TestUnitsProvider();
const inchUnit = await unitsProvider.findUnit("in", "Units.LENGTH");
const meterUnit = await unitsProvider.findUnit("m", "Units.LENGTH");
const meterQty = new Quantity(meterUnit, 1.0);
const conversion = await unitsProvider.getConversion(meterUnit, inchUnit);
let inchesQty = meterQty.convertTo(inchUnit, conversion);
assert.isTrue(meterQty.magnitude === 1.0);
assert.isTrue(inchesQty!.magnitude === meterQty.magnitude * conversion.factor);
});
it("Convert units", async () => {
const expectedConversionResults = [
{ label: "FT", unitContext: "", cvtTo: [{ label: "\"", factor: 12.0 }] },
{ label: "yd", unitContext: "", cvtTo: [{ label: "\'", factor: 3.0 }, { label: "\"", factor: 36.0 }] },
{ label: "mi", unitContext: "", cvtTo: [{ label: "yrd", factor: 1760.0 }, { label: "\'", factor: 5280.0 }, { label: "\"", factor: 63360.0 }] },
{ label: "°", unitContext: "Units.ANGLE", cvtTo: [{ label: "deg", factor: 1.0 }, { label: "min", factor: 60.0 }, { label: "sec", factor: 3600.0 }] },
{ label: "'", unitContext: "Units.ANGLE", cvtTo: [{ label: "min", factor: 1.0 }, { label: "sec", factor: 60.0 }] },
{ label: "\"", unitContext: "Units.ANGLE", cvtTo: [{ label: "sec", factor: 1.0 }] },
];
const unitsProvider = new TestUnitsProvider();
for (const tstVal of expectedConversionResults) {
const unitContext = tstVal.unitContext.length > 0 ? tstVal.unitContext : undefined;
const fromUnit = await unitsProvider.findUnit(tstVal.label, unitContext);
for (const toVal of tstVal.cvtTo) {
const toUnit = await unitsProvider.findUnit(toVal.label, fromUnit.unitFamily);
const conversionData = await unitsProvider.getConversion(fromUnit, toUnit);
assert.isTrue(Math.fround(conversionData.factor) === toVal.factor);
}
}
});
it("Generate Parse Tokens", async () => {
const format = new Format("test");
const testStrings = ["", "0/1", "1/0", "1/2", "-1/2", "+1/2", "2 /", "1.616252eggs", "1.616252E-35eggs", "-1.616252E-35eggs", "756345.345", "12,345.345", "3.6252e3 Miles", "-1 1/2 FT", "+1 1/2 FT", "-135°11'30.5\"", "-2FT 6IN", "135°11'30.5\"", "2FT 6IN", "1 1/2 FT"];
const expectedTokens = [
[],
[{ value: 0 }],
[{ value: 1 }],
[{ value: 0.5 }],
[{ value: -0.5 }],
[{ value: 0.5 }],
[{ value: 2 }],
[{ value: 1.616252 }, { value: "eggs" }],
[{ value: 1.616252e-35 }, { value: "eggs" }],
[{ value: -1.616252e-35 }, { value: "eggs" }],
[{ value: 756345.345 }],
[{ value: 12345.345 }],
[{ value: 3625.2 }, { value: "Miles" }],
[{ value: -1.5 }, { value: "FT" }],
[{ value: 1.5 }, { value: "FT" }],
[{ value: -135 }, { value: "°" }, { value: 11 }, { value: "'" }, { value: 30.5 }, { value: "\"" }],
[{ value: -2 }, { value: "FT" }, { value: 6 }, { value: "IN" }],
[{ value: 135 }, { value: "°" }, { value: 11 }, { value: "'" }, { value: 30.5 }, { value: "\"" }],
[{ value: 2 }, { value: "FT" }, { value: 6 }, { value: "IN" }],
[{ value: 1.5 }, { value: "FT" }],
];
let i = 0;
for (const strVal of testStrings) {
const tokens = Parser.parseQuantitySpecification(strVal, format);
assert.isTrue(tokens.length === expectedTokens[i].length);
// tslint:disable-next-line:prefer-for-of
for (let j = 0; j < tokens.length; j++) {
assert.isTrue(tokens[j].value === expectedTokens[i][j].value);
}
i = i + 1;
}
});
it("Look up units", async () => {
const expectedLookupResults = [
{ label: "FT", name: "Units.FT", unitContext: "" },
{ label: "'", name: "Units.FT", unitContext: "Units.LENGTH" },
{ label: "ft", name: "Units.FT", unitContext: "" },
{ label: "\"", name: "Units.IN", unitContext: "Units.LENGTH" },
{ label: "in", name: "Units.IN", unitContext: "" },
{ label: "IN", name: "Units.IN", unitContext: "" },
{ label: "°", name: "Units.ARC_DEG", unitContext: "Units.ANGLE" },
{ label: "'", name: "Units.ARC_MINUTE", unitContext: "Units.ANGLE" },
{ label: "\"", name: "Units.ARC_SECOND", unitContext: "Units.ANGLE" },
];
const unitProvider = new TestUnitsProvider();
for (const lookupEntry of expectedLookupResults) {
const unit = await unitProvider.findUnit(lookupEntry.label, (lookupEntry.unitContext.length > 0) ? lookupEntry.unitContext : undefined);
assert.isTrue(unit.name === lookupEntry.name);
}
});
it("Convert units", async () => {
const expectedConversionResults = [
{ label: "FT", unitContext: "", cvtTo: [{ label: "\"", factor: 12.0 }] },
{ label: "yd", unitContext: "", cvtTo: [{ label: "\'", factor: 3.0 }, { label: "\"", factor: 36.0 }] },
{ label: "mi", unitContext: "", cvtTo: [{ label: "yrd", factor: 1760.0 }, { label: "\'", factor: 5280.0 }, { label: "\"", factor: 63360.0 }] },
{ label: "°", unitContext: "Units.ANGLE", cvtTo: [{ label: "deg", factor: 1.0 }, { label: "min", factor: 60.0 }, { label: "sec", factor: 3600.0 }] },
{ label: "'", unitContext: "Units.ANGLE", cvtTo: [{ label: "min", factor: 1.0 }, { label: "sec", factor: 60.0 }] },
{ label: "\"", unitContext: "Units.ANGLE", cvtTo: [{ label: "sec", factor: 1.0 }] },
];
const unitsProvider = new TestUnitsProvider();
for (const tstVal of expectedConversionResults) {
const unitContext = tstVal.unitContext.length > 0 ? tstVal.unitContext : undefined;
const fromUnit = await unitsProvider.findUnit(tstVal.label, unitContext);
for (const toVal of tstVal.cvtTo) {
const toUnit = await unitsProvider.findUnit(toVal.label, fromUnit.unitFamily);
const conversionData = await unitsProvider.getConversion(fromUnit, toUnit);
assert.isTrue(Math.fround(conversionData.factor) === toVal.factor);
}
}
});
it("Parse into Length Quantities", async () => {
const formatData = {
composite: {
includeZero: true,
spacer: "",
units: [
{
label: "'",
name: "Units.FT",
},
],
},
formatTraits: ["keepSingleZero", "applyRounding", "showUnitLabel"],
precision: 4,
type: "Decimal",
uomSeparator: "",
};
const testData = [
{ value: "12,345.345", quantity: { magnitude: 12345.345, unitName: "Units.FT" } },
{ value: "3.6252e3 Miles", quantity: { magnitude: 3625.2, unitName: "Units.MILE" } },
{ value: "3.6252e-3 Miles", quantity: { magnitude: 0.0036252, unitName: "Units.MILE" } },
{ value: "3.6252e+3 Miles", quantity: { magnitude: 3625.2, unitName: "Units.MILE" } },
{ value: "-1 1/2FT", quantity: { magnitude: -1.5, unitName: "Units.FT" } },
{ value: "-2FT 6IN", quantity: { magnitude: -2.5, unitName: "Units.FT" } },
{ value: "1 1/2 FT", quantity: { magnitude: 1.5, unitName: "Units.FT" } },
{ value: "2FT 6IN", quantity: { magnitude: 2.5, unitName: "Units.FT" } },
{ value: "-3IN", quantity: { magnitude: -3.0, unitName: "Units.IN" } },
];
const unitsProvider = new TestUnitsProvider();
const format = new Format("test");
await format.fromJson(unitsProvider, formatData).catch(() => { });
assert.isTrue(format.hasUnits);
for (const testEntry of testData) {
const quantityProps = await Parser.parseIntoQuantity(testEntry.value, format, unitsProvider);
assert.isTrue(Math.fround(quantityProps.magnitude) === Math.fround(testEntry.quantity!.magnitude));
assert.isTrue(quantityProps.unit.name === testEntry.quantity!.unitName);
}
});
it("Parse into Length Quantities w/uom separator", async () => {
const formatData = {
composite: {
includeZero: true,
spacer: "",
units: [
{
label: "'",
name: "Units.FT",
},
],
},
formatTraits: ["keepSingleZero", "applyRounding", "showUnitLabel"],
precision: 4,
type: "Decimal",
uomSeparator: "*",
};
const testData = [
{ value: "12,345.345", quantity: { magnitude: 12345.345, unitName: "Units.FT" } },
{ value: "3.6252e3*Miles", quantity: { magnitude: 3625.2, unitName: "Units.MILE" } },
{ value: "-1 1/2*FT", quantity: { magnitude: -1.5, unitName: "Units.FT" } },
{ value: "-2*FT 6*IN", quantity: { magnitude: -2.5, unitName: "Units.FT" } },
{ value: "1 1/2*FT", quantity: { magnitude: 1.5, unitName: "Units.FT" } },
{ value: "2*FT 6*IN", quantity: { magnitude: 2.5, unitName: "Units.FT" } },
{ value: "-3*IN", quantity: { magnitude: -3.0, unitName: "Units.IN" } },
];
const unitsProvider = new TestUnitsProvider();
const format = new Format("test");
await format.fromJson(unitsProvider, formatData).catch(() => { });
assert.isTrue(format.hasUnits);
for (const testEntry of testData) {
const quantityProps = await Parser.parseIntoQuantity(testEntry.value, format, unitsProvider);
assert.isTrue(Math.fround(quantityProps.magnitude) === Math.fround(testEntry.quantity!.magnitude));
assert.isTrue(quantityProps.unit.name === testEntry.quantity!.unitName);
}
});
it("Parse into Station Quantities", async () => {
const unitsProvider = new TestUnitsProvider();
const formatData = {
"composite": {
"includeZero": true,
"spacer": " ",
"units": [
{
"label": "ft",
"name": "Units.FT"
}
]
},
"formatTraits": ["trailZeroes", "keepSingleZero", "keepDecimalPoint"],
"minWidth": 2,
"precision": 2,
"stationOffsetSize": 2,
"type": "Station"
};
const testData = [
{ value: "7563+45.345", quantity: { magnitude: 756345.345, unitName: "Units.FT" } },
{ value: "-7563+45.345", quantity: { magnitude: -756345.345, unitName: "Units.FT" } },
];
const format = new Format("test");
await format.fromJson(unitsProvider, formatData).catch(() => { });
assert.isTrue(format.hasUnits);
for (const testEntry of testData) {
const quantityProps = await Parser.parseIntoQuantity(testEntry.value, format, unitsProvider);
assert.isTrue(Math.fround(quantityProps.magnitude) === Math.fround(testEntry.quantity!.magnitude));
assert.isTrue(quantityProps.unit.name === testEntry.quantity!.unitName);
}
});
it("Parse into Angle Quantities", async () => {
const formatData = {
"composite": {
"includeZero": true,
"spacer": "",
"units": [
{
"label": "°",
"name": "Units.ARC_DEG"
},
{
"label": "'",
"name": "Units.ARC_MINUTE"
},
{
"label": "\"",
"name": "Units.ARC_SECOND"
}
]
},
"formatTraits": ["keepSingleZero", "keepDecimalPoint", "showUnitLabel"],
"precision": 4,
"type": "Decimal",
"uomSeparator": ""
};
const testData = [
{ value: "-135°11'30.5\"", defaultUnit: "Units.ARC_DEG", quantity: { magnitude: -135.19180555555556, unitName: "Units.ARC_DEG" } },
{ value: "135°11'30.5\"", defaultUnit: "Units.ARC_DEG", quantity: { magnitude: 135.19180555555556, unitName: "Units.ARC_DEG" } },
];
const unitsProvider = new TestUnitsProvider();
const format = new Format("test");
await format.fromJson(unitsProvider, formatData).catch(() => { });
assert.isTrue(format.hasUnits);
for (const testEntry of testData) {
const quantityProps = await Parser.parseIntoQuantity(testEntry.value, format, unitsProvider);
assert.isTrue(Math.fround(quantityProps.magnitude) === Math.fround(testEntry.quantity!.magnitude));
assert.isTrue(quantityProps.unit.name === testEntry.quantity!.unitName);
}
});
it("Parse into Length Quantities with Fraction dash", async () => {
const formatData = {
formatTraits: ["keepSingleZero", "showUnitLabel", "fractionDash"],
precision: 8,
type: "Fractional",
uomSeparator: " ",
};
const testData = [
{ value: "-1-1/2FT", quantity: { magnitude: -1.5, unitName: "Units.FT" } },
{ value: "1-1/2 FT", quantity: { magnitude: 1.5, unitName: "Units.FT" } },
{ value: "FT", quantity: { magnitude: 0.0, unitName: "Units.FT" } },
];
const unitsProvider = new TestUnitsProvider();
const format = new Format("test");
await format.fromJson(unitsProvider, formatData).catch(() => { });
assert.isTrue(!format.hasUnits);
for (const testEntry of testData) {
const quantityProps = await Parser.parseIntoQuantity(testEntry.value, format, unitsProvider);
assert.isTrue(Math.fround(quantityProps.magnitude) === Math.fround(testEntry.quantity!.magnitude));
assert.isTrue(quantityProps.unit.name === testEntry.quantity!.unitName);
}
});
});
|
cba8b50d1933ef0691da001022858388940175dc
|
TypeScript
|
Artezio/SURVEYBUILDER
|
/packages/models/src/factories/itemFactory.ts
| 2.546875
| 3
|
import TextItem from "../models/questionItems/textItem";
import BooleanItem from "../models/questionItems/booleanItem";
import Item from "../models/item";
import GroupItem from "../models/groupItem";
import IItemCollection from "../interfaces/IItemCollection";
import StringItem from "../models/questionItems/stringItem";
import IGroupItem from "../interfaces/IGroupItem";
import ITextItem from "../interfaces/questionItems/ITextItem";
import IStringItem from "../interfaces/questionItems/IStringItem";
import IDecimalItem from "../interfaces/questionItems/IDecimalItem";
import DecimalItem from "../models/questionItems/decimalItem";
import IBooleanItem from "../interfaces/questionItems/IBooleanItem";
import TimeItem from "../models/questionItems/timeItem";
import ITimeItem from "../interfaces/questionItems/ITimeItem";
import IDateItem from "../interfaces/questionItems/IDateItem";
import DateItem from "../models/questionItems/dateItem";
import IDateTimeItem from "../interfaces/questionItems/IDateTimeItem";
import DateTimeItem from "../models/questionItems/dateTimeItem";
import IAttachmentItem from "../interfaces/questionItems/IAttachmentItem";
import AttachmentItem from "../models/questionItems/attachmentItem";
import OpenChoiceItem from "../models/questionItems/openChoiceItem";
import IChoiceItem from "../interfaces/questionItems/IChoiceItem";
import ChoiceItem from "../models/questionItems/choiceItem";
import IOpenChoiceItem from "../interfaces/questionItems/IOpenChoiceItem";
import IItem from "../interfaces/IItem";
import IMultiChoiceItem from "../interfaces/questionItems/IMultiChoiceItem";
import MultiChoiceItem from "../models/questionItems/multiChoiceItem";
export class ItemFactory {
parent?: IItemCollection;
constructor(parent?: IItemCollection) {
this.parent = parent;
}
createItem(item?: Partial<Omit<IItem, 'type'>>) {
return new Item(item, this.parent)
}
createGroupItem(item?: Partial<Omit<IGroupItem, 'type'>>) {
return new GroupItem(item, this.parent);
}
createTextItem(item?: Partial<Omit<ITextItem, 'type'>>) {
return new TextItem(item, this.parent);
}
createStringItem(item?: Partial<Omit<IStringItem, 'type'>>) {
return new StringItem(item, this.parent);
}
createDecimalItem(item?: Partial<Omit<IDecimalItem, 'type'>>) {
return new DecimalItem(item, this.parent);
}
createBooleanItem(item?: Partial<Omit<IBooleanItem, 'type'>>) {
return new BooleanItem(item, this.parent);
}
createTimeItem(item?: Partial<Omit<ITimeItem, 'type'>>) {
return new TimeItem(item, this.parent);
}
createDateItem(item?: Partial<Omit<IDateItem, 'type'>>) {
return new DateItem(item, this.parent);
}
createDateTimeItem(item?: Partial<Omit<IDateTimeItem, 'type'>>) {
return new DateTimeItem(item, this.parent);
}
createAttachmentItem(item?: Partial<Omit<IAttachmentItem, 'type'>>) {
return new AttachmentItem(item, this.parent);
}
createChoiceItem(item?: Partial<Omit<IChoiceItem, 'type'>>) {
return new ChoiceItem(item, this.parent);
}
createOpenChoiceItem(item?: Partial<Omit<IOpenChoiceItem, 'type'>>) {
return new OpenChoiceItem(item, this.parent);
}
createMultiChoiceItem(item?: Partial<Omit<IMultiChoiceItem, 'type'>>) {
return new MultiChoiceItem(item, this.parent);
}
}
export default ItemFactory;
|
fc8e49dc22eae6c4301f1b5a812445a2e021d568
|
TypeScript
|
Rasukarusan/express-mongodb-react-app
|
/api/src/services/orderService.ts
| 2.6875
| 3
|
import Order from '../models/orders';
let faker = require("faker/locale/ja")
export default class OrderService {
public async getAll() {
try {
return Order.find().exec();
}catch(err) {
throw err;
}
}
public async getById(id: string) {
try {
return Order.findById(id).exec();
} catch (e) {
throw e;
}
}
public async save(files: Express.Multer.File[]) {
files.map((file: Express.Multer.File) => {
console.log(file);
});
try {
let mocks = [];
let malls = ['amazon', 'rakuten', 'ebay', 'futureshop'];
for(let i = 0;i < 1000; ++i) {
let mall = malls[Math.floor(Math.random() * malls.length)];
let mock = {
mall: mall,
orderNumber: faker.finance.bitcoinAddress() ,
buyerPostCode: faker.address.zipCode(),
buyerName: faker.name.findName(),
buyerAddress: faker.address.state() + ' ' + faker.address.streetAddress(),
total: faker.commerce.price(),
};
mocks.push(mock);
}
return Order.insertMany(mocks);
} catch (e) {
throw e;
}
}
public async update() {
try {
return Order.updateMany({ name: 'hoge' }, { name: 'hogehoge' });
} catch (e) {
throw e;
}
}
public async delete(where: { [key: string] : any }) {
try {
return Order.deleteMany(where);
} catch (e) {
throw e;
}
}
}
|
da96c3c52faae241b83728f9115d4308b1e95cc9
|
TypeScript
|
kentotakeuchi/data-structures-and-algorithms
|
/leetcode/easy/can-place-flowers.ts
| 3.65625
| 4
|
// https://leetcode.com/problems/can-place-flowers/
// MINE..
/*
function canPlaceFlowers(flowerbed: number[], n: number): boolean {
let newFlowers = 0;
const empties = flowerbed.join('').split('1'); // ['', '000', '']
console.log({empties})
for(let i=0; i<empties.length; ++i) {
// edge
if((i === 0 || i === empties.length-1) && empties[i].length%2 === 0) {
newFlowers += empties[i].length/2
}
// odd
else if(empties[i].length && empties[i].length%2 === 1) {
newFlowers += Math.floor(empties[i].length/2)
}
// even
else if(empties[i].length && empties[i].length%2 === 0) {
newFlowers += empties[i].length/2-1
}
}
console.log({newFlowers})
return newFlowers >= n
};
*/
// ANSWER
/*
function canPlaceFlowers(flowerbed: number[], n: number): boolean {
let i = 0
let count = 0
while(i < flowerbed.length) {
if(flowerbed[i] === 0 && (i === 0 || flowerbed[i-1] === 0) && (i === flowerbed.length-1 || flowerbed[i+1] === 0)) {
flowerbed[i] = 1
++count
}
++i
}
return count >= n
}
*/
// ANSWER: optimize the above
function canPlaceFlowers(flowerbed: number[], n: number): boolean {
let i = 0
let count = 0
while (i < flowerbed.length) {
if (
flowerbed[i] === 0 &&
(i === 0 || flowerbed[i - 1] === 0) &&
(i === flowerbed.length - 1 || flowerbed[i + 1] === 0)
) {
flowerbed[i] = 1
++count
}
if (count >= n) return true
++i
}
return count >= n
}
|
ddb9942fb251c339cdaa2fa14f6f98c3b9138eab
|
TypeScript
|
sunseekker1/cas-fee
|
/abend-06-27/uebung Modularisierung/Loesung/binder.ts
| 2.78125
| 3
|
export class Binder{
bind(data : any) : void {
// would bind the view to the controller
console.log('Data bound: ' + data);
}
}
|
ee75f9bd662c62614eccd8473ab441b8d15684ea
|
TypeScript
|
alexey-kozlenkov/ng-movies-demo
|
/src/app/page-movie-list/movie-card/country-flag.pipe.ts
| 2.546875
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
const languageCodeToFlag = {
'en': '🇺🇸',
'it': '🇮🇹',
'lt': '🇱🇹',
};
@Pipe({
name: 'languageToFlag'
})
export class LanguageToFlagPipe implements PipeTransform {
transform(code: string): string {
return languageCodeToFlag[code] || '🤷♀️';
}
}
|
e370ebc28ef5f5328db08d12616d49090a1b290a
|
TypeScript
|
9andresc/typescript-deep-dive
|
/3-future-javascript/sample-18.ts
| 3.640625
| 4
|
// `const`
const foo; // Error: `const` declarations must be initialized
const foo = 123;
foo = 456; // Error: Cannot redeclare block-scoped variable `foo`
const foo = 123;
if (true) {
const foo = 456; // Allowed as it's a new variable limited to this `if` block
}
const foo = { bar: 123 };
foo.bar = 456;
console.log(foo); // -> { bar: 456 }
|
2c1698ae683cf00d380e74ea8ac87021c9444f3b
|
TypeScript
|
krawaller/algol5
|
/modules/ui/src/helpers/useDemo.ts
| 2.609375
| 3
|
import { useState, useEffect, useRef } from "react";
import { AlgolDemo, AlgolHydratedDemo, AlgolDemoPatch } from "../../../types";
import { hydrateDemoFrame, emptyDemo, hydrateDemoBase } from "../../../common";
import { GameId } from "../../../games/dist/list";
const FRAME_LENGTH_MS = 1500;
const WIN_FRAME_FACTOR = 5;
type UseDemoOptions = {
demo: AlgolDemo;
playing?: boolean;
restart?: boolean;
gameId: GameId;
};
type HydrationInfo = {
demo: AlgolHydratedDemo | null;
patches: AlgolDemoPatch[];
count: number;
gameId: GameId;
};
export const useDemo = (opts: UseDemoOptions) => {
const { demo = emptyDemo, playing, restart, gameId } = opts;
const [hydrInfo, setHydrInfo] = useState<HydrationInfo>({
demo: null,
patches: demo.patches,
count: 0,
gameId,
});
const timeout = useRef<null | ReturnType<typeof setTimeout>>();
const frameCount = demo.patches.length + 1;
// initial hydration (for performance with many demos running, make them pop one at a time)
useEffect(() => {
if (!hydrInfo.demo) {
setTimeout(() => {
setHydrInfo({
...hydrInfo,
demo: hydrateDemoBase(demo),
});
}, 0);
}
}, [demo, hydrInfo.demo]);
// when we switch game
useEffect(() => {
if (gameId !== hydrInfo.gameId) {
if (timeout.current) {
clearTimeout(timeout.current);
timeout.current = null;
}
setHydrInfo({
demo: hydrateDemoBase(demo),
count: 0,
gameId,
patches: demo.patches,
});
}
}, [gameId, hydrInfo.gameId]);
// start/stop
useEffect(() => {
if (!playing) {
// user stopped the demo. clear eventual timeout, and eventually restart count
if (timeout.current) {
clearTimeout(timeout.current);
timeout.current = null;
if (restart) {
setHydrInfo({
...hydrInfo,
count: 0,
});
}
}
} else if (hydrInfo.demo) {
// we're playing, should tick!
if (!timeout.current) {
timeout.current = setTimeout(() => {
timeout.current = null;
setHydrInfo({
...hydrInfo,
...(hydrInfo.patches.length && {
demo: hydrateDemoFrame(hydrInfo.demo!, hydrInfo.patches[0]),
patches: hydrInfo.patches.slice(1),
}),
count: (hydrInfo.count + 1) % frameCount,
});
}, FRAME_LENGTH_MS * (hydrInfo.count === frameCount - 1 ? WIN_FRAME_FACTOR : 1));
}
}
return () => {
if (timeout.current) {
clearTimeout(timeout.current);
}
};
}, [hydrInfo.patches, hydrInfo.demo, hydrInfo.count, playing, restart]);
return { frame: hydrInfo.count, hydrDemo: hydrInfo.demo };
};
|
4d6ff0b4df59c3fa5e6ffc1c9a4fed6da98566b6
|
TypeScript
|
zachhardesty7/semantic-styled-ui
|
/src/components/IconLink/IconLinkGroup.d.ts
| 2.609375
| 3
|
import * as React from "react"
import { JustifyProp, PaddedVerticalProp } from "../../types"
export type IconLinkGroupPadding =
| "compact"
| "tight"
| "base"
| "relaxed"
| "loose"
export interface IconLinkGroupProps {
/**
* flex alignment of icon container
*/
justify?: JustifyProp
/**
* spacing around element exists
*/
padded?: PaddedVerticalProp
/**
* control amount of spacing around element
*/
padding?: IconLinkGroupPadding
/**
* additional or pass thru classes for composition
*/
className?: string
/**
* primary content of icon(s)
*/
children: React.ReactNode
}
// export const IconGroup: React.FC<IconGroupProps>
declare const IconLinkGroup: React.FC<IconLinkGroupProps>
|
c0d7aeaed8c34b9e0ee3bfea3af4fec68fb83163
|
TypeScript
|
SimoesFO/vaibem
|
/server/src/app/validations/authenticationValidate.ts
| 2.703125
| 3
|
import * as Yup from 'yup';
const authSchema = Yup.object().shape({
email: Yup.string()
.email('E-mail inválido')
.required('O campo E-mail é obrigátorio'),
password: Yup.string()
.min(5, 'A senha deve ter entre 5 e 20 caracteres.')
.max(20, 'A senha deve ter entre 5 e 20 caracteres.')
.required('A senha é obrigátorio'),
});
export default authSchema;
|
995f0813689ca6498b3eac2cf2273e2b75242a32
|
TypeScript
|
keymanapp/s.keyman.com
|
/kmw/engine/17.0.97/src/engine/main/text/prediction/modelManager.ts
| 2.6875
| 3
|
// Defines the KeyboardManager and its related types.
///<reference path="../../keyboards/kmwkeyboards.ts" />
namespace com.keyman.text.prediction {
export class ModelManager {
// Tracks registered models by ID.
private registeredModels: {[id: string]: ModelSpec} = {};
// Allows for easy model lookup by language code; useful when switching keyboards.
languageModelMap: {[language:string]: ModelSpec} = {};
init() {
let keyman = com.keyman.singleton;
// Registers this module for keyboard (language) and model change events.
keyman['addEventListener']('keyboardchange', this.onKeyboardChange.bind(this));
}
onKeyboardChange(kbdInfo?: keyboards.KeyboardChangeData | string) {
let keyman = com.keyman.singleton;
let core = keyman.core;
if(typeof kbdInfo == 'string') { // This case refers to the active language code.
kbdInfo = {
['internalName']: keyman.keyboardManager.getActiveKeyboardName(),
['languageCode']: kbdInfo,
['indirect']: true
}
}
let lgCode = kbdInfo['languageCode']?.toLowerCase();
let model = this.languageModelMap[lgCode];
var loadPromise: Promise<void>;
if(core.activeModel) {
core.languageProcessor.unloadModel();
}
if(model) {
loadPromise = core.languageProcessor.loadModel(model);
}
}
// Accessible publicly as keyman.modelManager.register(model: ModelSpec)
register(model: ModelSpec): void {
let keyman = com.keyman.singleton;
let activeLanguage = keyman.keyboardManager.getActiveLanguage();
// Forcibly lowercase the model ID before proceeding.
model.id = model.id.toLowerCase();
if(JSON.stringify(model) == JSON.stringify(this.registeredModels[model.id])) {
// We are already registered, let's not go through and re-register
// because we'll already have the correct model active
return;
}
this.registeredModels[model.id] = model;
// Register the model for each targeted language code variant.
let mm = this;
model.languages.forEach(function(code: string) {
// Prevent null / undefined codes; they're invalid.
if(!code) {
console.warn("Null / undefined language codes are not permitted for registration.");
return;
}
mm.languageModelMap[code] = model;
// The model's for our active language! Activate it!
if(code == activeLanguage) {
// Manually trigger our model-update event function.
mm.onKeyboardChange(code);
}
});
}
deregister(modelId: string): void {
let keyman = com.keyman.singleton;
let core = keyman.core;
let model: ModelSpec;
modelId = modelId.toLowerCase();
// Remove the model from the id-lookup associative array.
if(this.registeredModels[modelId]) {
model = this.registeredModels[modelId];
delete this.registeredModels[modelId];
} else {
return;
}
// Is it the active model?
if(core.activeModel && core.activeModel.id == modelId) {
core.languageProcessor.unloadModel();
}
// Ensure the model is deregistered for each targeted language code variant.
let mm = this;
model.languages.forEach(function(code: string) {
if(mm.languageModelMap[code].id == modelId) {
delete mm.languageModelMap[code];
}
});
}
isRegistered(model: ModelSpec): boolean {
return !! this.registeredModels[model.id.toLowerCase()];
}
}
}
|
66a501d1885bb72b3b0c1d9d94c39b225f2a03e3
|
TypeScript
|
ehog90/aggrid-test
|
/src/app/mappers.ts
| 2.59375
| 3
|
import {IStatEntry, IStroke, ITenminStat, ITenminStatEntry, ITimeAndCountry} from './interfaces';
import {getCountryName} from "./country-resolver";
/**
* Created by ehog on 2017. 04. 14..
*/
export function mapTenminStat(data: any[]): ITenminStat {
return {
timeStart: new Date(data[0]),
all: data[1],
entries: data[2].map(entry => mapTenminStatEntry(entry))
};
}
export function mapTenminStatEntry(data: any[]): ITenminStatEntry {
return {
countryCode: data[0],
countryName: getCountryName(data[0], 'hu'),
count: data[1]
};
}
export function mapTimeAndCountry(dataString: string): ITimeAndCountry {
const data = JSON.parse(dataString);
return {
time: new Date(data[0]),
countryCode: data[1]
};
}
export function mapStatEntry(data: any[]): IStatEntry {
return {
countryCode: data[0],
countryName: getCountryName(data[0], 'hu'),
count: data[1],
lastStroke: new Date(data[2]),
percent: data[3]
};
}
export function mapStroke(data: any[]): IStroke {
return {
id: data[0],
latLng: data[1],
countryCode: data[2],
countryName: getCountryName(data[2], 'hu'),
region: data[3],
subRegion: data[4],
settlement: data[5],
street: data[6],
suburb: data[7],
azimuth: data[8],
time: new Date(data[9]),
sunElevation: data[10]
};
}
|
3d71dd44519dc29e543021d88482d8f1123a4ec4
|
TypeScript
|
hapinessjs/hapiness
|
/src/extensions/http-server/enums.ts
| 2.640625
| 3
|
export enum LifecycleHooksEnum {
OnPreAuth = <any>'onPreAuth',
OnPostAuth = <any>'onPostAuth',
OnPreHandler = <any>'onPreHandler',
OnPostHandler = <any>'onPostHandler',
OnPreResponse = <any>'onPreResponse'
}
export enum LifecycleEventsEnum {
OnPreAuth = <any>'onPreAuth',
OnPostAuth = <any>'onPostAuth',
OnPreHandler = <any>'onPreHandler',
OnPostHandler = <any>'onPostHandler',
OnPreResponse = <any>'onPreResponse'
}
export enum LifecycleComponentEnum {
OnEvent = <any>'onEvent'
}
export enum RouteMethodsEnum {
OnGet = <any>'onGet',
OnPost = <any>'onPost',
OnPut = <any>'onPut',
OnDelete = <any>'onDelete',
OnPatch = <any>'onPatch',
OnOptions = <any>'onOptions'
}
export function enumByMethod(method: string): RouteMethodsEnum {
switch (method) {
case 'get':
return RouteMethodsEnum.OnGet;
case 'post':
return RouteMethodsEnum.OnPost;
case 'put':
return RouteMethodsEnum.OnPut;
case 'patch':
return RouteMethodsEnum.OnPatch;
case 'options':
return RouteMethodsEnum.OnOptions;
case 'delete':
return RouteMethodsEnum.OnDelete;
default:
throw new Error('Method does not exist');
}
}
|
7caf57acdbe723cc8cbf5ff6091261b165e4aa6d
|
TypeScript
|
cpsoneghett/typescript_e2e_automation_tutorial
|
/tests/e2e/ts/specs/cenario02.spec.ts
| 2.765625
| 3
|
import { InicioPage } from "../pages/inicio.page";
import { Reports } from "../components/reports.component";
describe('Teste cenário 02 - Funcionalidades gerais', () => {
var Inicio: InicioPage = new InicioPage(); //Declaramos uma instância da nossa página aqui!
afterEach(function () {
Reports.tiraPrint();
});
it('Soma dois números (no caso, 1 e 3)', () => {
Inicio.realizaOperacao('+', 1, 3);
expect(Inicio.resultado.getText()).toEqual('4');
});
it('Valida inclusão no histórico', () => {
expect(Inicio.historico.count()).toEqual(1);
});
it('Realiza o módulo de dois números (5 e 2)', () => {
Inicio.realizaOperacao('%', 5, 2);
expect(Inicio.resultado.getText()).toEqual('1');
});
});
|
13ca8fe63eccbe7ccf4d278ef7182159c1eb2c20
|
TypeScript
|
marcprux/setup-swift
|
/src/get-version.ts
| 2.5625
| 3
|
import { exec } from "@actions/exec";
export async function getVersion(
command: string = "swift",
args: string[] = ["--version"]
) {
let output = "";
let error = "";
const options = {
listeners: {
stdout: (data: Buffer) => {
output += data.toString();
},
stderr: (data: Buffer) => {
error += data.toString();
},
},
};
await exec(command, args, options);
if (error) {
throw new Error(error);
}
const match = output.match(/(?<version>[0-9]+\.[0-9+]+(\.[0-9]+)?)/) || {
groups: { version: null },
};
if (!match.groups || !match.groups.version) {
return null;
}
return match.groups.version;
}
|
44d6b69654c8dd8e902af5817dee1b2b05689c43
|
TypeScript
|
vdmchpg/TZ-1
|
/source/api/index.ts
| 2.78125
| 3
|
import { NewsBlock } from '../state/modules/news';
const API_KEY = '8ce44c3a6df140b3a6b01bd6f0c29392';
const API_URL = 'https://newsapi.org/v2/top-headlines';
const timeout = (delay: number): () => Promise<{}> => () => new Promise(resolve => setTimeout(resolve, delay));
export type API = {
checkToken: () => LoginResponse;
login: (params: LoginParams) => LoginResponse;
logout: () => LogoutResponse;
getNews: (params: NewsParams) => NewsResponse;
}
export function checkToken() {
return new Promise((resolve, reject) => {
if (localStorage.getItem('token') === 'admin') {
resolve({ username: 'Admin' });
} else {
reject();
}
});
}
export type LoginParams = { username: string; password: string }
export type LoginResponse = Promise<{ username: string }>
export function login(params: LoginParams): LoginResponse {
return Promise.resolve()
.then(timeout(300))
.then(() => {
const { username, password } = params;
if ((username === 'Admin' && password === '12345')) {
localStorage.setItem('token', 'admin');
return { username };
}
throw new Error('Имя пользователя или пароль введены не верно');
});
}
export type LogoutResponse = Promise<void>;
export function logout(): Promise<void> {
localStorage.removeItem('token');
return Promise.resolve();
}
type NewsResponse = Promise<{
articles: NewsBlock[];
totalResults: number;
}>
export type NewsParams = {
page: number;
}
export function getNews(params: NewsParams): NewsResponse {
const url = `${API_URL}?country=ru&apiKey=${API_KEY}&page=${params.page || 1}&pageSize=10`;
return fetch(url)
.then((response) => {
if (!response.ok) {
return response.json().then(error => Promise.reject(error));
}
return response.json();
});
}
|
5411e114ab29beb9803fcf4ee4a6c9681a432313
|
TypeScript
|
paullessing/natasha-smart-home
|
/src/server/appliances/appliance.converter.ts
| 2.703125
| 3
|
import {Component} from '../../util';
import {Appliance} from '../../shared/appliance.interface';
import {Device} from '../devices/device.interface';
@Component()
export class ApplianceConverter {
public convertDevice(device: Device): Appliance[] {
const baseAppliance: Appliance = {
id: device.id,
name: device.name,
location: device.location,
isOn: device.isOn,
isToggleOnly: !!(device.commands.on && device.commands.off)
};
const appliances = [baseAppliance];
if (device.alternativeNames) {
for (let i = 0; i < device.alternativeNames.length; i++) {
const name = device.alternativeNames[i];
appliances.push(Object.assign({}, baseAppliance, { id: device.id + '#' + i, name }));
}
}
return appliances;
}
}
|
86e988a10dcc0aee6cbf09ea38174a1403221499
|
TypeScript
|
donascimentomarcelo/finansys-angular
|
/src/app/in-memory-database.ts
| 2.53125
| 3
|
import { InMemoryDbService } from 'angular-in-memory-web-api';
import { Category } from './pages/categories/shared/Category';
import { Entry } from './pages/entries/shared/entry.model';
export class InMemoryDatabase implements InMemoryDbService {
createDb() {
const categories: Category[] = [
{ id: 1, name: 'Teste 1', description: 'blablabla'},
{ id: 2, name: 'Teste 2', description: 'blablabla'},
{ id: 3, name: 'Teste 3', description: 'blablabla'},
{ id: 4, name: 'Teste 4', description: 'blablabla'},
{ id: 5, name: 'Teste 5', description: 'blablabla'},
];
const entries: Entry[] = [
{
id: 1,
name: 'Teste 1',
categoryId: categories[0].id,
category: categories[0],
paid: true,
date: '14/10/2018',
amount: '10',
type: 'expense',
description: 'hala hala hala hala'
} as Entry,
{
id: 2,
name: 'Teste 2',
categoryId: categories[1].id,
category: categories[1],
paid: false,
date: '14/10/2018',
amount: '154',
type: 'revenue'
} as Entry,
{
id: 3,
name: 'Teste 3',
categoryId: categories[2].id,
category: categories[2],
paid: true,
date: '14/10/2018',
amount: '800',
type: 'expense',
description: 'hala hala hala hala'
} as Entry,
{
id: 4,
name: 'Teste 4',
categoryId: categories[3].id,
category: categories[3],
paid: false,
date: '14/10/2018',
amount: '90',
type: 'expense'
} as Entry,
{
id: 5,
name: 'Teste 5',
categoryId: categories[4].id,
category: categories[4],
paid: true,
date: '14/10/2018',
amount: '1500',
type: 'revenue',
description: 'hala hala hala hala'
} as Entry,
];
return { categories, entries };
}
}
|
83d8173b48ca9f588dc1e753b02b0fe5476d27a8
|
TypeScript
|
FiberJW/design-starter-kit
|
/styles/typography.ts
| 2.859375
| 3
|
export function rem(multiple: number) {
return multiple * 16;
}
export function lineHeight(fontSize: number, multiple: number = 1.2) {
return fontSize * multiple;
}
export type fontSize = number;
export type typeScale = (note: number) => fontSize;
export function genTypeScale(ratio: number): typeScale {
return function typeScale(note: number) {
return rem(1 * Math.pow(ratio, note));
};
}
export const minorSecond = genTypeScale(1.067);
export const majorSecond = genTypeScale(1.125);
export const minorThird = genTypeScale(1.2);
export const majorThird = genTypeScale(1.25);
export const perfectFourth = genTypeScale(1.333);
export const augmentedFourth = genTypeScale(1.414);
export const perfectFifth = genTypeScale(1.5);
export const goldenRatio = genTypeScale(1.618);
|
011d69cfdf66989ad83a710b2fe1928510b1ac07
|
TypeScript
|
tanle-bmd/050-shipping-backend-2.0
|
/src/services/StaffService.ts
| 2.65625
| 3
|
import { Service } from "@tsed/common";
import { CoreService } from "../core/services/CoreService";
import { Staff } from "../entity/Staff";
import { validatePassword } from "../util/passwordHelper";
import { Permission } from '../entity/Permission';
import { Exception } from "ts-httpexceptions";
@Service()
export class StaffService extends CoreService {
/**
* =====================LOGIN=====================
*/
public async login(username: string, password: string): Promise<Staff> {
//because select password is false for config
const staff = await Staff.findOneOrThrowOption({
select: ["password", "id", "isBlock"],
where: { username },
})
let validate = await validatePassword(password, staff.password)
if (!validate)
return null
return staff
}
/**
* =====================IS VALID PASSWORD=====================
* Return null if not valid
* Else return admin
*/
public async isValidPassword(id: number, password: string): Promise<Staff> {
//because select password is false for config
const staff = await Staff.findOneOrThrowOption({
select: ["password", "id"],
where: { id }
})
let validate = await validatePassword(password, staff.password)
if (!validate)
return null
return staff
}
/**
* =====================GET PERMISSION=====================
*/
public async getPermission(staffId: number): Promise<Permission[]> {
return Permission.createQueryBuilder("p")
.leftJoin("p.roles", "r")
.leftJoin("r.staff", "a")
.where("a.id = :staffId", { staffId })
.getMany()
}
/**
* =====================CHECK DUPLICATE=====================
*/
async checkDuplicate(staff: Staff, userId: number = null) {
const { username, phone, email } = staff
const oldStaff = await Staff.findOne({
where: [
{ username },
{ phone },
{ email }
]
})
let message = ""
if (oldStaff && oldStaff.id != userId) {
if (oldStaff.username == staff.username) {
message = "Tài khoản"
}
else if (oldStaff.phone == staff.phone) {
message = "Số điện thoại"
}
else if (oldStaff.email == staff.email) {
message = "Email"
}
throw new Exception(400, `Trùng ${message} với nhân viên khác`)
}
}
}
|
b909c72280733d347a8c8932d7b249dab790cdfa
|
TypeScript
|
scalvert/ember-cli-checkup
|
/src/results/project-info-task-result.ts
| 2.703125
| 3
|
import { ITaskResult, IConsoleWriter } from '../types';
export default class ProjectInfoTaskResult implements ITaskResult {
type!: string;
name!: string;
version!: string;
toConsole(writer: IConsoleWriter) {
writer.heading('Project Information');
writer.column({
Name: this.name,
Type: this.type,
Version: this.version,
});
writer.line();
}
toJson() {
return { name: this.name, type: this.type, version: this.version };
}
}
|
bb3cd8c1200806dac3230a47970a1769f3db2bf6
|
TypeScript
|
LedgerHQ/ledger-live-common
|
/src/families/solana/bridge/mock.ts
| 2.640625
| 3
|
import { flow, isArray, isEqual, isObject } from "lodash/fp";
import { isUndefined, mapValues, omitBy } from "lodash/fp";
import { cached, ChainAPI, Config, getChainAPI, logged, queued } from "../api";
import { makeBridges } from "./bridge";
import { makeLRUCache } from "../../../cache";
import { getMockedMethods } from "./mock-data";
import { minutes } from "../api/cached";
function mockChainAPI(config: Config): ChainAPI {
const mockedMethods = getMockedMethods();
const api = new Proxy(
{ config },
{
get(_, propKey) {
if (propKey in api) {
return api[propKey];
}
if (propKey === "then") {
return undefined;
}
const method = propKey.toString();
const mocks = mockedMethods.filter((mock) => mock.method === method);
if (mocks.length === 0) {
throw new Error(`no mock found for api method: ${method}`);
}
return function (...args: any[]) {
const definedArgs = removeUndefineds(args);
const mock = mocks.find(({ params }) => isEqual(definedArgs)(params));
if (mock === undefined) {
const argsJson = JSON.stringify(args);
throw new Error(
`no mock found for api method ${method} with args ${argsJson}`
);
}
return Promise.resolve(mock.answer);
};
},
}
);
return api as ChainAPI;
}
function removeUndefineds(input: any) {
return isObject(input)
? isArray(input)
? input.map(removeUndefineds)
: flow(omitBy(isUndefined), mapValues(removeUndefineds))(input)
: input;
}
// Bridge with this api will log all api calls to a file.
// The calls data can be copied to mock-data.ts from the file.
// Uncomment fs module in logged.ts
/* eslint-disable-next-line @typescript-eslint/no-unused-vars */
function createMockDataForAPI() {
const apiGetter = makeLRUCache(
(config: Config) =>
Promise.resolve(
cached(queued(logged(getChainAPI(config), "/tmp/log"), 100))
),
(config) => config.endpoint,
minutes(1000)
);
return {
getAPI: apiGetter,
getQueuedAPI: apiGetter,
getQueuedAndCachedAPI: apiGetter,
};
}
function getMockedAPIs() {
const mockedAPI = mockChainAPI({ cluster: "mock" } as any);
return {
getAPI: (_: Config) => Promise.resolve(mockedAPI),
getQueuedAPI: (_: Config) => Promise.resolve(mockedAPI),
getQueuedAndCachedAPI: (_: Config) => Promise.resolve(mockedAPI),
};
}
//export default makeBridges(createMockDataForAPI());
export default makeBridges(getMockedAPIs());
|
965d5ce6274566d5148ce59c305fa4ff173b818d
|
TypeScript
|
yujuiting/jtable
|
/packages/core/src/types/context.ts
| 2.828125
| 3
|
/**
* @packageDocumentation
* @module core/context
*/
import { AnyAction } from './action';
export interface Store<T = unknown> {
sourceData: T[];
visibleData: T[];
pageCurrent: number;
pageTotal: number;
pageSize: number;
sortKey: string;
sortOrder: 'asc' | 'desc';
columns: ColumnInfo<T>[];
}
export interface TableService<T = unknown> {
state: Store<T>;
dispatch: React.Dispatch<AnyAction>;
}
export interface RowService<T = unknown> {
data: T;
index: number;
}
/**
* @internal
*/
export interface WithTable<T = unknown> {
table: TableService<T>;
}
/**
* @internal
*/
export interface WithRow<T = unknown> {
data?: T;
index?: number;
}
export interface ColumnInfo<T = unknown> {
/**
* unique id for each column
*/
columnId: string;
/**
* if `accessor` provide, it will take `fieldId`'s place when access data.
*/
accessor?: string | ((data: T) => React.ReactNode);
sortor?: (a: T, b: T) => number;
/**
* As row key
*/
asKey?: boolean;
}
|
11995b872165b5ca7a4e14a3729781cd1b42b351
|
TypeScript
|
sarker24/eesmiley-fromtend
|
/service-foodwaste/app/src/services/guest-registrations/hooks/validate-guest-registration.ts
| 2.5625
| 3
|
/**
* Validate for 2 conditions:
* If user has given guest type id, validates the record exists and is active.
* If user has guest types enabled, validates the registration has guest type id
*
* Before hook: CREATE / PATCH
*/
import * as errors from '@feathersjs/errors';
import { Hook, HookContext } from '@feathersjs/feathers';
const subModule = 'validate-guest-registration';
export default (): Hook => {
return async (hook: HookContext) => {
const sequelize = hook.app.get('sequelize');
const { requestId, sessionId } = hook.params;
const guestRegistration = hook.data;
let hasEnabledGuestTypes;
try {
hasEnabledGuestTypes = 1 === (await sequelize.models.settings.count({
where: {
customerId: guestRegistration.customerId,
current: { enableGuestTypes: true }
}
}));
} catch (error) {
throw new errors.GeneralError('Could not finish request - unexpected error occurred', {
errorCode: 500,
subModule,
requestId,
sessionId
});
}
if (!guestRegistration.guestTypeId && !hasEnabledGuestTypes) {
return hook;
}
if (!guestRegistration.guestTypeId && hasEnabledGuestTypes) {
throw new errors.GeneralError('No guest type id given but guest types are enabled', {
errorCode: 'E270',
subModule,
requestId,
sessionId
});
}
let guestType;
try {
guestType = await sequelize.models.guest_type.findOne({
raw: true,
where: {
id: guestRegistration.guestTypeId,
customerId: guestRegistration.customerId,
active: true
}
});
} catch (error) {
throw new errors.GeneralError('Could not finish request - unexpected error occurred', {
errorCode: 500,
subModule,
requestId,
sessionId
});
}
if (!guestType) {
throw new errors.GeneralError('No active guest type exists for given id', {
errorCode: 'E269',
subModule,
requestId,
sessionId
});
}
return hook;
};
};
|
1853c2205b6b58d8cccbbbe35b380340dea961fe
|
TypeScript
|
FabianGosebrink/real-time-cross-platform-aspnetcore-angular-signalr
|
/client/src/app/food/validators/isInRange.validator.ts
| 2.625
| 3
|
import { Attribute, Directive, forwardRef } from '@angular/core';
import {
FormControl,
NG_VALIDATORS,
ValidationErrors,
Validator,
} from '@angular/forms';
const INT_MAX = 2147483647;
@Directive({
selector:
'[app-isInRange][formControlName],[app-isInRange][formControl],[app-isInRange][ngModel]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => IsInRangeValidator),
multi: true,
},
],
})
export class IsInRangeValidator implements Validator {
private _minValue: number;
private _maxValue: number;
constructor(
@Attribute('minValue') minValue: number,
@Attribute('maxValue') maxValue: number
) {
this._minValue = minValue || 0;
this._maxValue = maxValue || INT_MAX;
}
validate(c: FormControl): ValidationErrors | null {
if (+c.value > this._maxValue || +c.value < this._minValue) {
return {
isInRange: {
valid: false,
},
};
}
return null;
}
}
|
aa822e69300db188d812b5c0579a6614883d3562
|
TypeScript
|
jguyon/check
|
/test/oneOf.test.ts
| 3.125
| 3
|
import * as check from "../src";
test("check succeeds when at least one child check succeeds", () => {
const checkValue = check.oneOf(
check.number(),
check.chain(check.string(), check.toLower()),
check.chain(check.string(), check.toUpper()),
);
const result = checkValue("Jerome");
expect(result).toEqual({
isOk: true,
value: "jerome",
});
});
test("check fails with error from last failing child check", () => {
const checkValue = check.oneOf(
check.string(),
check.number(),
check.boolean(),
);
const result = checkValue(null);
expect(result).toEqual({
isOk: false,
error: "is not a boolean",
invalidValue: null,
path: [],
});
});
test("additional arguments are passed to the child checks", () => {
const checkValue = check.oneOf(check.fail(), (value, ...args) =>
check.ok(args),
);
const result = checkValue(null, "one", "two");
expect(result).toEqual({
isOk: true,
value: ["one", "two"],
});
});
|
b752506a987c2fbb4fd694d15ff4725961992bf4
|
TypeScript
|
akira345/gitbeaker
|
/packages/gitbeaker-requester-utils/src/RequesterUtils.ts
| 2.6875
| 3
|
import FormData from 'form-data';
import { decamelizeKeys } from 'xcase';
import { Agent } from 'https';
import { stringify } from 'query-string';
export interface RequesterType {
get(service: object, endpoint: string, options?: object): Promise<any>;
post(service: object, endpoint: string, options?: object): Promise<any>;
put(service: object, endpoint: string, options?: object): Promise<any>;
delete(service: object, endpoint: string, options?: object): Promise<any>;
stream?(service: object, endpoint: string, options?: object): Promise<any>;
}
export interface Service {
headers: Record<string, string | string[]>;
requestTimeout: number;
url: string;
rejectUnauthorized?: boolean;
}
export type DefaultRequestOptions = {
body?: FormData | object;
query?: object;
sudo?: string;
method: string;
};
const methods = ['get', 'post', 'put', 'delete', 'stream'];
export function formatQuery(options) {
return stringify(decamelizeKeys(options || {}) as object, { arrayFormat: 'bracket' });
}
export function defaultRequest(
service: Service,
{ body, query, sudo, method }: DefaultRequestOptions = { method: 'get' },
): Record<string, string | number | FormData | Record<string, string | string[]>> {
const { headers } = service;
let agent;
let bod;
if (sudo) headers.sudo = sudo;
if (typeof body === 'object' && !(body instanceof FormData)) {
bod = JSON.stringify(decamelizeKeys(body));
headers['content-type'] = 'application/json';
} else {
bod = body;
}
if (service.url.includes('https')) {
agent = new Agent({
rejectUnauthorized: service.rejectUnauthorized,
});
}
return {
agent,
headers,
timeout: service.requestTimeout,
method,
searchParams: formatQuery(query),
prefixUrl: service.url,
body: bod,
};
}
export function createInstance(optionsHandler, requestHandler): RequesterType {
const requester: RequesterType = {} as RequesterType;
methods.forEach((m) => {
/* eslint func-names:0 */
requester[m] = function (service, endpoint, options) {
const requestOptions = optionsHandler(service, { ...options, method: m });
return requestHandler(endpoint, requestOptions);
};
});
return requester;
}
|
007629feeb3b639b34c4fcbdf6301e682fff9e77
|
TypeScript
|
ZhangMYihua/angular-ssr
|
/source/transpile/transpile.ts
| 2.65625
| 3
|
import {ScriptTarget} from 'typescript';
import {transform} from 'babel-core';
import {TranspileException} from 'exception';
export type TranspileResult<R> = {
load(): R;
}
const transpiled = new Map<string, TranspileResult<any>>();
const cache = {
read<T>(moduleId: string, factory?: () => TranspileResult<T>): TranspileResult<T> {
let cached = transpiled.get(moduleId);
if (cached == null) {
if (factory) {
cached = factory();
}
}
return cached;
},
write<T>(moduleId: string, moduleResult: TranspileResult<T>) {
transpiled.set(moduleId, moduleResult);
return moduleResult;
},
clear() {
transpiled.clear();
}
};
export const transpile = <R>(moduleId: string, source: string, sourceType = ScriptTarget.ES2015): TranspileResult<R> => {
return cache.read(moduleId, () => factory<R>(moduleId, source, sourceType));
};
export const factory = <R>(moduleId: string, source: string, sourceType: ScriptTarget): TranspileResult<R> => {
const filename = require.resolve(moduleId);
try {
const {code} = transform(source, {presets: [sourceToPreset(sourceType)], sourceMaps: false, filename});
if (code == null) {
throw new TranspileException(`Catastrophic transpilation unknownm error: ${moduleId}`);
}
let executed = undefined;
return <TranspileResult<R>> {
load: (): R => {
if (executed === undefined) {
const execute = new Function('exports', code);
const exports = {};
execute(exports);
cache.write(moduleId, {load: () => exports});
executed = exports;
}
return executed;
}
};
}
catch (exception) {
throw new TranspileException(`Transpilation of ${moduleId} failed`, exception);
}
};
const sourceToPreset = (sourceType: ScriptTarget): string => {
switch (sourceType) {
case ScriptTarget.ES2015:
return 'es2015';
default:
throw new TranspileException(`${ScriptTarget[sourceType]} not supported by installed Babel plugins`);
}
};
|
ebe8ae2f8a1884c682d28317d341a8e11c57b4f1
|
TypeScript
|
mcnguyen/type-plus
|
/src/function/AnyFunction.spec.ts
| 3.09375
| 3
|
import { AnyFunction, assertType } from '..'
test('basic', () => {
const foo: AnyFunction = x => x
foo()
const result = foo(false)
// only any can be boolean here
assertType.isBoolean(result)
})
test('define param as tuple', () =>{
const foo: AnyFunction<[number,string]> = x => x
foo(1, 'a')
})
test('define result type', () => {
const foo: AnyFunction<any[], string> = x => x
assertType.isString(foo('a'))
})
|
673023cc04e91b7b13a6aa209729a0af99fbeeab
|
TypeScript
|
chiqui3d/stencil-head
|
/src/helper/style.ts
| 3.15625
| 3
|
export default class Style{
private document: Document = document;
/**
* Create and render in the dom the style tags
*/
public create(styles): void {
this.setStyles(styles)
}
/**
* Return the style tags in HTML|String format, so you can manipulate.
* Note: this does not add it to the Dom.
*/
public html(styles: string[]): Node[] {
const stylesForHtml = [];
styles.forEach((style)=> {
stylesForHtml.push(Style.createNode(style));
});
return stylesForHtml;
}
private setStyles(styles: string[]): void{
const stylesForRender = [];
styles.forEach((style: string)=> {
stylesForRender.push(Style.createNode(style))
});
if (stylesForRender){
const lastMetaNode = this.document.querySelector('head').getElementsByTagName('style');
const last = lastMetaNode && lastMetaNode[lastMetaNode.length-1];
if (last){
stylesForRender.forEach((element, index) => {
const refElement = index === 0 ? last : stylesForRender[index - 1];
refElement.parentNode.insertBefore(element, refElement.nextSibling);
});
}else{
document.querySelector('head').append(...stylesForRender)
}
}
}
private static createNode(style: string): Node {
const styleElement = document.createElement('style');
styleElement.setAttribute('type', 'text/css');
styleElement.innerHTML = style;
return styleElement;
}
}
|
fc4d612f170a3ac162102201edd7b6064a947668
|
TypeScript
|
adam-saland/layouts-service
|
/src/provider/config/ConfigUtil.ts
| 3.25
| 3
|
import {ApplicationScope, RegEx, Rule, Scope, WindowScope} from '../../../gen/provider/config/layouts-config';
/**
* Defines the relative precedence of each available scope. The names of the constants match the `Scopes` type (and it
* is important that all scopes are included in the enum). Because of this alignment, the enum can be used as a mapping
* between `Scopes` values and precedence values.
*
* ```ts
* const scope: Scopes = 'desktop';
* const priority: number = ScopePrecedence[scope];
* const scope2: Scopes = ScopePrecedence[priority] as Scopes;
* ```
*
* Precedence rules are important, as it is expected that each rule passed to the store will only contain a small
* subset of the available parameters. A query must always return a "full" config object with all parameters specified,
* so these precedence levels determine the order in which the rules are applied in order to build the final config
* object.
*
* The lower the number returned by this enum, the lower the priority of that scope - i.e. the smaller the number, the
* more likely it is that config at that scope will get overridden by another rule.
*/
export enum ScopePrecedence {
service = 0,
desktop = 1,
application = 2,
window = 3
}
/**
* Helper type - like the built-in `Required<T>` util, but will apply the modifier recursively, to any non-primitive
* values within T.
*
* The helper contains one exception. Any 'rules' member will always be left unmodified, this is a work-around to allow
* this util to work as intended with the `ConfigWithRules<T>` type.
*/
export type RequiredRecursive<T> = {
[P in keyof T] -?: T[P] extends number|string|boolean|'rules' ? T[P] : RequiredRecursive<T[P]>;
};
/**
* Helper type - takes any object type and transforms it into a "Mask" of that type.
*
* A mask type has all the same members as the original type, but all primitive values are replaced with `boolean`. Any
* non-primitive values are masked in a recursive manner.
*
* These masks are for querying a limited subset of a config tree. The masks are used to specify which value(s) from
* the "full" config object should be extracted and returned.
*
* Querying with a mask can reduce the amount of work required when querying, by not iterating through parts of the
* config tree that aren't required by the callee.
*/
export type Mask<T> = {
[P in keyof T]: T[P] extends number|string|boolean ? boolean : boolean|Mask<T[P]>;
};
/**
* Represents a concrete type that has had a mask applied. The template argument T is the original type, and M is the
* mask that was applied to T. To use this util, the mask type `M` must be known at compile-time. There is no way for
* TypeScript to validate any masks that are specified during runtime.
*
* NOTE: The TypeScript to support masking can get rather complicated... Some parts of the utils for masking will use
* `any` types, but these utils *are* type-safe, so long as the value used for the mask strictly matches type `M` (with
* no missing or additional fields).
*/
export type Masked<T, M extends Mask<T>> = MaskedHelper<T, M, keyof T&keyof M>;
type MaskedHelper<T, M, K extends(keyof T)&(keyof M)> = {
[P in K]: M[P] extends true ? (T[P] extends number|string|boolean ? T[P] : (M[P] extends Mask<T[P]>? Masked<T[P], M[P]>: never)) : never;
};
/**
* Collection of miscellaneous utils for use with configuration, scopes and rules.
*/
export class ConfigUtil {
/**
* Takes a scope or rule and converts it to a canonical string that can be used as a cache key, or in logging
* output.
*
* @param scope The scope/rule to stringify
*/
public static getId(scope: Rule|Scope): string {
switch (scope.level) {
case 'application':
return `${scope.level}:${ConfigUtil.stringifyParam(scope.uuid)}`;
case 'window':
return `${scope.level}:${ConfigUtil.stringifyParam(scope.uuid)}/${ConfigUtil.stringifyParam(scope.name)}`;
default:
return scope.level;
}
}
/**
* Tests if two scopes are exactly equal.
*
* {@link matchesScope} can be used as a "fuzzy" equality check, to check if any item that matches one scope will
* also match the other.
*
* @param a First scope
* @param b Second scope
*/
public static scopesEqual(a: Scope, b: Scope): boolean {
if (a.level !== b.level) {
return false;
} else {
switch (a.level) {
case 'application':
return a.uuid === (b as ApplicationScope).uuid;
case 'window':
return a.uuid === (b as WindowScope).uuid && a.name === (b as WindowScope).name;
default:
// No additional data to check
return true;
}
}
}
/**
* Tests if two rules are "functionally" exactly equal.
*
* Check is performed in a way that allows for optional fields to evaluate as equal if one is undefined and the
* other is defined but with the default value.
*
* @param a First rule
* @param b Second rule
*/
public static rulesEqual(a: Rule, b: Rule): boolean {
function paramEqual(a: string|RegEx, b: string|RegEx): boolean {
if (typeof a !== typeof b) {
return false;
} else if (typeof a === 'string') {
return a === b;
} else if (typeof b !== 'string') { // Redundant since expression will always be true, but allows TypeScript to infer type of 'b'
return a.expression === b.expression && (a.flags || '') === (b.flags || '') && (a.invert || false) === (b.invert || false);
}
return false;
}
if (a.level !== b.level) {
return false;
} else {
switch (a.level) {
case 'application':
return paramEqual(a.uuid, (b as ApplicationScope).uuid);
case 'window':
return paramEqual(a.uuid, (b as WindowScope).uuid) && paramEqual(a.name, (b as WindowScope).name);
default:
// No additional data to check
return true;
}
}
}
/**
* Ensures that 'value' is compatible with the 'spec' scope.
*
* This means that any config with 'spec' scope will also apply to the 'value' scope.
*
* @param spec The "tester" scope - will assert that any item which matches 'value' will also match this scope
* @param value The "subject" scope - will assert that this is a strict subset of the 'spec' scope
*/
public static matchesScope(spec: Scope, value: Scope): boolean {
const levelSpec: number = ScopePrecedence[spec.level];
const levelValue: number = ScopePrecedence[value.level];
if (levelSpec !== levelValue) {
return levelSpec < levelValue;
} else {
return this.scopesEqual(spec, value);
}
}
/**
* Checks that `rule` is allowed to be defined within config with a source of `scope`.
*
* The service prevents config sources from specifying rules in scopes that are "higher" than the scope at which the
* config is being loaded at. This util ensures the rule operates "at or below" the given scope.
*
* @param rule The rule being added to the store
* @param scope The scope of whoever is trying to add this rule to the store
*/
public static ruleCanBeAddedInScope(rule: Rule, scope: Scope): boolean {
return ScopePrecedence[rule.level] >= ScopePrecedence[scope.level];
}
/**
* Returns if `rule` applies to `scope`.
*
* Rules apply to the scope at which they are defined, and any scopes below that in the hierarchy. For example, an
* 'application'-scoped rule's config should be applied to application and window scopes only, and not a query at
* desktop or service scope.
*
* Rules can be used in any scope that exists "at-or-above" the scope at which it acts.
*
* @param rule The rule being considered for execution
* @param scope The scope being queried
*/
public static ruleCanBeUsedInScope(rule: Rule, scope: Scope): boolean {
return ScopePrecedence[rule.level] <= ScopePrecedence[scope.level];
}
/**
* Checks that 'scope' matches the given rule.
*
* @param rule The rule to execute
* @param scope The scope to execute the rule on
*/
public static matchesRule(rule: Rule, scope: Scope): boolean {
if (!this.ruleCanBeUsedInScope(rule, scope)) {
console.warn(`No way that a "${scope.level}" scope can pass a "${rule.level}" rule`);
return false;
} else {
switch (rule.level) {
case 'window': {
const winScope = scope as WindowScope;
if (!this.checkPattern(rule.name, winScope.name)) {
return false;
} else if (rule.uuid && !this.checkPattern(rule.uuid, winScope.uuid)) {
return false;
}
return true;
}
case 'application': {
const appScope = scope as ApplicationScope;
if (rule.uuid && !this.checkPattern(rule.uuid, appScope.uuid)) {
return false;
}
return true;
}
default:
return true;
}
}
}
/**
* Tests if the value matches the given filter.
*
* @param filter A string or RegEx pattern to use to test 'value'
* @param value The string to test against the given filter
*/
public static checkPattern(filter: string|RegEx, value: string): boolean {
if (!filter) {
return true;
} else if (typeof filter === 'string') {
return filter === value;
} else {
const regex = new RegExp(filter.expression, filter.flags);
return regex.test(value) === !filter.invert;
}
}
public static deepCopy<T extends {}>(value: T): T {
if (!(value instanceof Object)) {
// Primitive value, no need to clone these
return value;
} else {
// Start with a shallow copy of 'value'
const out = Object.assign({}, value);
// Recursively deep-copy each non-primitive child member
for (const key in out) {
if (out[key] instanceof Object) {
out[key] = ConfigUtil.deepCopy(out[key]);
}
}
return out;
}
}
public static deepAssign<T extends {}>(target: T, value: T): void {
for (const key in value) {
if (!target.hasOwnProperty(key)) {
target[key] = ConfigUtil.deepCopy(value[key]);
} else if (target[key] instanceof Object) {
ConfigUtil.deepAssign(target[key], value[key]);
} else {
target[key] = value[key];
}
}
}
public static deepAssignMask<T extends {}, M extends Mask<T>>(target: Masked<T, M>, value: T, mask: M|boolean): void {
const keys = Object.keys(mask instanceof Object ? mask : value) as (keyof T)[];
if (mask === false) {
return;
}
for (const key of keys) {
if (value.hasOwnProperty(key) && ConfigUtil.inMask(mask, key)) {
ConfigUtil.assignProp<T, M>(target, value, key as keyof T, mask);
}
}
}
public static containsConfig<T extends {}>(config: T): boolean {
for (const key in config) {
if (key !== 'rules') {
return true;
}
}
return false;
}
/**
* Returns true if ANY of the fields specified in 'mask' exist within 'value'.
*/
public static matchesMask<T extends {}, M extends Mask<T>>(value: T, mask: M|boolean): boolean {
if (mask instanceof Object) {
const maskObj: M = mask as M;
const keys = Object.keys(mask) as (keyof T)[];
// Check if ANY of the keys within the mask exist within 'value'.
return keys.findIndex((key: keyof T) => {
const type = typeof maskObj[key];
if (type === 'boolean') {
// Matches if mask is enabled, and corresponding property exists within value
return maskObj[key] && value.hasOwnProperty(key);
} else if (type === 'object') {
// Recurse into sub-mask, unless property doesn't exist within value
return value.hasOwnProperty(key) ? this.matchesMask(value[key], maskObj[key]) : false;
} else {
console.warn('Unexpected value found within mask:', mask, key);
return false;
}
}) >= 0;
} else if (typeof mask === 'boolean') {
// A mask of 'true' will always pass, a mask of 'false' will always fail
return mask;
} else {
// Invalid mask
console.warn('Unexpected value found within mask:', mask, 'when applying mask to', value);
return false;
}
}
private static stringifyParam(param: string|RegEx): string {
if (typeof param === 'string') {
return param;
} else {
return `${param.invert ? '!' : ''}/${param.expression}/${param.flags || ''}`;
}
}
private static assignProp<T extends {}, M extends Mask<T>>(target: Masked<T, M>, value: T, key: keyof T, mask: M|boolean): void {
// The types get a bit complicated here, so a few "any"'s are required to prevent compile errors...
// TypeScript can't figure out the type of T[key], since 'key' is a runtime argument.
if (!(value[key] instanceof Object)) {
// tslint:disable-next-line:no-any
target[key] = value[key] as any;
} else if (value[key]) {
if (!target.hasOwnProperty(key)) {
(target[key] as {}) = {};
}
// tslint:disable-next-line:no-any
ConfigUtil.deepAssignMask<any, any>(target[key], value[key], typeof mask === 'object' ? mask[key] : mask);
}
}
private static inMask<T>(mask: boolean|Mask<T>, key: keyof T): mask is Mask<T> {
if (typeof mask === 'boolean') {
return mask;
} else {
return (typeof mask[key] === 'object') || mask[key] === true;
}
}
}
|
7e4bb1aec47318b0bdfcd9ab4b98118261e3abbc
|
TypeScript
|
nrfm/umbrella
|
/packages/rasterize/src/shader.ts
| 2.890625
| 3
|
import type { IGrid2D, TypedArray } from "@thi.ng/api";
import type { IRandom } from "@thi.ng/random";
import { SYSTEM } from "@thi.ng/random/system";
import type { Shader2D } from "./api.js";
export const defPattern = <T extends any[] | TypedArray, P>(
pattern: IGrid2D<T, P>
): Shader2D<P> => {
const [w, h] = pattern.size;
return (x, y) => pattern.getAtUnsafe(x % w, y % h);
};
export interface StripeShaderOpts<T> {
dir: "h" | "v" | "d";
size: number;
sizeA: number;
a: T;
b: T;
}
export const defStripes = <T = number>({
dir,
size,
sizeA,
a,
b,
}: StripeShaderOpts<T>): Shader2D<T> =>
dir === "h"
? (x) => (x % size < sizeA ? a : b)
: dir === "v"
? (_, y) => (y % size < sizeA ? a : b)
: (x, y) => ((x + y) % size < sizeA ? a : b);
export interface RandomShaderOpts<T> {
probability?: number;
rnd?: IRandom;
a: T;
b: T;
}
export const defNoise = <T = number>(
opts: RandomShaderOpts<T>
): Shader2D<T> => {
const { probability, rnd, a, b } = {
probability: 0.5,
rnd: SYSTEM,
...opts,
};
return () => (rnd.float() < probability ? a : b);
};
|
ff68921c6f5ab09f094cdab388253e06e3d45bd7
|
TypeScript
|
Marcos240/common-2scool
|
/@helper/network/HttpQuere.ts
| 2.90625
| 3
|
export default class HttpQueue {
private requesting: boolean;
private stack: Array<{
input: any;
resolve: any;
reject: any;
}>;
private queryFunction: Function;
constructor (queryFunction: Function) {
this.requesting = false;
this.stack = [];
this.queryFunction = queryFunction;
}
handle({ input }: { input: any }) {
if (this.stack.length < 2) {
return new Promise ((resolve, reject) => {
this.stack.push({
input,
resolve,
reject
});
this.makeQuery();
})
}
return new Promise ((resolve, reject) => {
this.stack[1] = {
input,
resolve,
reject
};
this.makeQuery();
})
}
getLength() {
return this.stack.length;
}
private makeQuery () {
if (! this.stack.length || this.requesting) {
return null;
}
this.requesting = true;
this.queryFunction(this.stack[0].input).then((response: any) => {
this.stack[0].resolve(response);
}).catch((error: any) => {
this.stack[0].reject(error);
}).finally(() => {
this.requesting = false
this.stack.splice(0, 1);
this.makeQuery();
})
}
}
|
0b2dd94e3e3d041d701d387397869f6c5a203e30
|
TypeScript
|
yhaskell/af-filtering-matches
|
/backend/src/routes/matches.ts
| 2.78125
| 3
|
import { RequestHandler } from 'express'
import { Types } from 'mongoose'
import { default as People, Person } from '../db/person'
import { validateFilter, setFilters, setDistanceFilter } from '../filter'
import * as response from './response'
import * as log from '../lib/logger'
/**
* Returns all matches that are available in the DB
*/
export const getAll: RequestHandler = async (req, rsp, next) => {
const people = await People.find()
response.success(rsp, people)
}
/**
* Returns one match that corresponds to the Id specified
*/
export const byId: RequestHandler = async (req, rsp, next) => {
const id = req.params.id
if (!Types.ObjectId.isValid(id))
return response.error(rsp, 400, "Incorrect Id format")
const person = await People.findById(id)
return person != null
? response.success(rsp, [person])
: response.error(rsp, 404, "Match not found")
}
/**
* Returns the list of matches that actually match the search terms.
* We have the following parameters that we have to check:
* Has photo Boolean
* In contact Boolean
* Favourite Boolean
* Compatibility Score Range from 1% to 99%
* Age Range from 18 years old until > 95 years old
* Height Range from 135cm to > 210cm
* Distance in km Single selection: lower bound < 30 km, upper bound > 300 km
*/
export const bySearchTerms: RequestHandler = async (req, rsp, next) => {
if (!req.body || typeof req.body !== "object")
return response.error(rsp, 400, "No query provided")
try {
const filter = validateFilter(req.body)
const queryWithFilters = setFilters(filter)
if (filter.distance !== null)
setDistanceFilter(queryWithFilters, filter.distance, req.body.location)
const people = await queryWithFilters.exec()
return response.success(rsp, people)
} catch (err) {
log.error(err.message, { url: req.url })
return response.error(rsp, 400, err.message)
}
}
|
d3d61a2cd1baf4e8f1e564e5e4eeb5803d68f13a
|
TypeScript
|
ravensinth/retro
|
/frontend/src/utils/user.utils.ts
| 2.828125
| 3
|
import { removeFirstOccurenceFromArray } from ".";
export const ROLE_MODERATOR = "moderator";
export const ROLE_PARTICIPANT = "participant";
export function getUser(boardId: string) {
const userObject = localStorage.getItem(boardId);
if (userObject !== null) {
return JSON.parse(userObject);
}
return null;
}
export function setUser(propertyName: string, newValue: any, boardId: string) {
const userObject = getUser(boardId);
if (userObject !== null) {
userObject[propertyName] = newValue;
saveToLocalStorage(boardId, JSON.stringify(userObject));
}
}
export function setVotedItem(
cardId: string,
boardId: string,
isUpvote: boolean
) {
const userObject = getUser(boardId);
if (userObject !== null) {
const votedItems = userObject["votedItems"];
if (isUpvote) votedItems.push(cardId);
else removeFirstOccurenceFromArray(votedItems, cardId);
userObject["votedItems"] = votedItems;
saveToLocalStorage(boardId, JSON.stringify(userObject));
}
}
export function setMaxVoteCountAndReset(newVoteCount: number, boardId: string) {
const userObject = getUser(boardId);
if (userObject !== null) {
userObject["maxVoteCount"] = newVoteCount;
userObject["votesLeft"] = newVoteCount;
userObject["votedItems"] = [];
saveToLocalStorage(boardId, JSON.stringify(userObject));
}
}
export function hasVotedFor(cardId: string, boardId: string) {
const userObject = getUser(boardId);
if (userObject !== null) {
const votedItems = userObject["votedItems"];
if (votedItems.includes(cardId)) {
return true;
}
}
return false;
}
export function createRole(
role: string,
boardId: string,
maxVoteCount: number
) {
const data = JSON.stringify({
role,
name: "",
maxVoteCount,
votesLeft: maxVoteCount,
votedItems: [],
});
saveToLocalStorage(boardId, data);
}
function saveToLocalStorage(boardId: string, data: string) {
localStorage.setItem(boardId, data);
}
|
7c9a92efe30957ba718ed2a95c50f110f926c596
|
TypeScript
|
d-klotz/google-dashboard
|
/src/app/dashboard/dados.service.ts
| 2.703125
| 3
|
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { observable } from '../../../node_modules/rxjs';
@Injectable()
export class DadosService {
readonly dados = [
['Janeiro', 33],
['Fevereiro', 68],
['Março', 49],
['Abril', 15],
['Maio', 80],
['Junho', 27],
];
constructor() { }
/**
* Retorna um observable com os dados
* a serem exibidos no grafico
* @return Observable<any>
*/
obterDados(): Observable<any> {
return new Observable(obs => {
obs.next(this.dados);
obs.complete();
});
}
}
|
23219bb8be6b16beb7e6150fe223bf862616d3cb
|
TypeScript
|
cahilfoley/utils
|
/src/transforms/toProperList.ts
| 4.09375
| 4
|
/**
* @module transforms
*/
/**
*
* Joins together several strings or numbers in a properly formatted English list. The last two items are seperated by the word
* 'and' and the remaining items are seperated by a comma and space.
*
* @param items Array of strings
*
* @example
* ```typescript
*
* const itemsString = toProperList(['apples', 'pears', 'bananas']) // => 'apples, pears and bananas'
* ```
*
*/
export function toProperList(items: string[]): string
export function toProperList(...items: string[]): string
export function toProperList(...items: any[]): string {
const parts: string[] = Array.isArray(items[0]) ? items[0] : items
// If you have 1 - 2 items in the array
if (parts.length < 3) return parts.join(' and ')
// There are 3 or more items in the array
return (
parts
// Traverse all elements of the array adds the correct grammar according to the English language
.map((item, index) => {
// If it is the penultimate array item
if (index === parts.length - 2) return `${item} and `
// If it is the last item in the array
if (index === parts.length - 1) return item
// If it is the first or some element before the penultimate one
return `${item}, `
})
.join('')
)
}
export default toProperList
|
fabdcb3d92319f086d29f758d7a9b166cb2a8df8
|
TypeScript
|
michael8090/function-component
|
/src/functionComponent/functionComponent.ts
| 2.75
| 3
|
import { CrossList as CL, CrossListNode } from './CrossLinkedList';
import { MemoryPool } from './MemoryPool';
import { Queue } from './Queue';
// accessing a Module Symbol has overhead
const CrossList = CL;
const addCrossListNode = CrossList.add;
const walkCrossListNode = CrossList.walk;
const walkModifiedCrossListNode = CrossList.walkAlongModifiedList;
const removeCrossListNode = CrossList.remove;
interface ConstructorOf<T> {new (...args: any[]): T}
interface StackNode extends CrossListNode {
C: ConstructorOf<Component<any, any>>;
/**
* component instance
*/
i?: Component<any, any>;
/**
* component function
*/
f?: (...data: any[]) => void;
/**
* marked to be force updated
*/
// fu?: boolean;
}
function disposeNode(node: StackNode) {
const instance = node.i;
if (instance !== undefined) {
instance.__isUnmounted = true;
instance.cachedArgs = undefined;
instance.__context = undefined;
if (instance.componentWillUnmount !== undefined) {
instance.componentWillUnmount();
}
node.i = undefined;
}
// node.c = undefined;
// node.nS = undefined;
context!.memoryPool.put(node);
}
interface Context {
// the variables shared by all function calls of a root
/**
* lastCallStack
*/
lastCallStack: StackNode | undefined;
/**
* memoryPool
*/
memoryPool: MemoryPool;
isBatchedUpdate: boolean;
skippedNodes?: Queue<StackNode>;
// root variables definition end
// the variables shared inside a layer of a subtree
/**
* parentView
*/
parentView: any | undefined;
/**
* parentInCurrentCallStack
*/
parentInCurrentCallStack: StackNode | undefined;
/**
* preSiblingInCurrentCallStack
*/
preSiblingInCurrentCallStack: StackNode | undefined;
/**
* lastNode
*/
lastNode: StackNode | undefined;
// subtree layer variables definition end
}
let context: Context | undefined;
export class Component<TData extends any[] = any[], TView = {}> {
// tslint:disable-next-line:variable-name
__stackNode: StackNode;
// tslint:disable-next-line:variable-name
__forcedUpdate: boolean;
// tslint:disable-next-line:variable-name
__isUnmounted: boolean;
// tslint:disable-next-line:variable-name
__context: Context | undefined;
cachedArgs: TData = [] as any;
view: TView | undefined;
onInit?(parent: TView): void;
shouldComponentUpdate?(...data: TData): boolean;
componentWillMount?(...data: TData): void;
componentWillUpdate?(...data: TData): void;
componentWillUnmount?(): void;
componentDidUpdate?(...data: TData): void;
componentDidMount?(...data: TData): void;
render?(...data: TData): void;
forceUpdate() {
if (this.__isUnmounted === true) {
// tslint:disable-next-line:no-console
console.error(`trying to update an unmounted component: ${this.constructor.name}`);
return;
}
if (context !== undefined && context.isBatchedUpdate === true) {
this.__forcedUpdate = true;
return;
}
const {cachedArgs, __context} = this;
const contextBackup = context;
context = __context!;
context.lastNode = this.__stackNode;
this.__forcedUpdate = true;
this.__stackNode.f!.apply(null, cachedArgs);
context = contextBackup;
}
}
function MACRO_GET_VARIABLE_NAME(...args: any[]) {
//
}
export function toFunctionComponent<TData extends any[], TView = {}>
(vg: ConstructorOf<Component<TData, TView>>): (...data: TData) => void {
// const {componentWillMount: componentWillMount, componentWillUpdate: componentWillUpdate, render} = vg;
const Cls = vg;
function functionComponent(MACRO_ARGS: any) {
// const data = arguments as any as TData;
// avoid accessing closure
const currentContext = context;
if (currentContext === undefined) {
throw new Error(
`A function component should be wrapped inside a Root (use getRoot())`
);
}
const currentCls = Cls;
let currentNode: StackNode;
let lastCls: ConstructorOf<Component<any, any>>;
let lastNodeNextSibling: StackNode | undefined;
const {lastNode} = currentContext;
if (lastNode !== undefined) {
lastCls = lastNode.C;
lastNodeNextSibling = lastNode.nS;
currentNode = lastNode;
} else {
currentNode = currentContext.memoryPool.get();
}
let isUpdateSkipped = false;
let isMount = false;
if (lastCls! === currentCls) {
// update
const instance = currentNode.i!;
if (instance.__forcedUpdate !== true) {
if (instance.shouldComponentUpdate !== undefined) {
isUpdateSkipped = instance.shouldComponentUpdate('MACRO_ARGS') === false;
}
} else {
instance.__forcedUpdate = false;
}
if (isUpdateSkipped === false) {
if (instance.componentWillUpdate !== undefined) {
instance.componentWillUpdate('MACRO_ARGS');
}
}
} else {
let isCreate = false;
if (lastCls! === undefined) {
if (currentContext.lastCallStack === undefined) {
// create currentStack
currentContext.lastCallStack = currentNode;
}
isCreate = true;
} else {
// dispose last view and create current view
removeCrossListNode(lastNode!, currentContext.parentInCurrentCallStack!, currentContext.preSiblingInCurrentCallStack);
const instance = lastNode!.i!;
instance.__isUnmounted = true;
instance.cachedArgs = undefined;
instance.__context = undefined;
if (instance.componentWillUnmount !== undefined) {
instance.componentWillUnmount();
}
const lastNodeChild = lastNode!.c;
lastNode!.c = undefined;
if (lastNodeChild !== undefined) {
walkCrossListNode(lastNodeChild, disposeNode);
}
// the node is completely gone and we'll not visit its child
isCreate = true;
}
if (isCreate === true) {
isMount = true;
// create current view
// todo: if use currentCls, 3.2ms to 4.8ms
const instance = new currentCls('MACRO_ARGS');
instance.__stackNode = currentNode;
instance.__context = currentContext;
if (instance.onInit !== undefined) {
instance.onInit(currentContext.parentView);
}
if (instance.componentWillMount !== undefined) {
(instance.componentWillMount as any)('MACRO_ARGS');
}
currentNode.i = instance;
currentNode.C = currentCls;
currentNode.nS = undefined;
currentNode.c = undefined;
currentNode.f = f;
// currentNode.qn = undefined;
if (currentContext.parentInCurrentCallStack !== undefined) {
// add the currentNode to the currentCallStack
addCrossListNode(currentNode, currentContext.parentInCurrentCallStack, currentContext.preSiblingInCurrentCallStack);
}
}
}
const currentInstance = currentNode.i!;
// this line will be compiled, don't change any thing inside it.
MACRO_GET_VARIABLE_NAME(currentInstance)
if (isUpdateSkipped === false) {
// done with the node, now for the children
if (currentInstance.render !== undefined) {
const parentViewBackup = currentContext.parentView;
const parentInCurrentCallStackBackup = currentContext.parentInCurrentCallStack;
const view = currentInstance.view;
if (view !== undefined) {
currentContext.parentView = view;
}
currentContext.parentInCurrentCallStack = currentNode;
currentContext.preSiblingInCurrentCallStack = undefined;
// const lastNodeChild = lastNode && lastNode.c;
// it's the same as above one
const lastNodeChild = currentNode.c;
currentContext.lastNode = lastNodeChild;
// !!!children enter!!!
(currentInstance.render as any)('MACRO_ARGS');
// !!!children done!!!
const preSiblingInCurrentCallStack = currentContext.preSiblingInCurrentCallStack as StackNode | undefined;
if (preSiblingInCurrentCallStack !== undefined) {
const nodeToBeDisposed = preSiblingInCurrentCallStack.nS;
if (nodeToBeDisposed !== undefined) {
walkCrossListNode(nodeToBeDisposed, disposeNode);
preSiblingInCurrentCallStack.nS = undefined;
}
} else if (lastNodeChild !== undefined) {
lastNode!.c = undefined;
walkCrossListNode(lastNodeChild, disposeNode);
}
currentContext.parentView = parentViewBackup;
currentContext.parentInCurrentCallStack = parentInCurrentCallStackBackup;
}
if (currentInstance.componentDidUpdate !== undefined) {
currentInstance.componentDidUpdate.apply(currentInstance, currentInstance.cachedArgs);
}
} else {
const {skippedNodes} = currentContext;
if (skippedNodes !== undefined) {
const currentChild = currentNode.c;
if (currentChild !== undefined) {
skippedNodes.push(currentChild);
}
}
}
if (isMount === true) {
if (currentInstance.componentDidMount !== undefined) {
currentInstance.componentDidMount.apply(currentInstance, currentInstance.cachedArgs);
}
}
/** set the layer variables */
// tell the next sibling, the pre sibling is me
currentContext.preSiblingInCurrentCallStack = currentNode;
currentContext.lastNode = lastNodeNextSibling;
/** done setting the layer variables */
}
// shouldComponentUpdate?(...data: TData): boolean;
// componentWillMount?(...data: TData): void;
// componentWillUpdate?(...data: TData): void;
// componentWillUnmount?(): void;
// componentDidUpdate?(...data: TData): void;
// componentDidMount?(...data: TData): void;
// render?(...data: TData): void;
const hooks = [
'shouldComponentUpdate',
'componentWillMount',
'componentWillUpdate',
'componentDidUpdate',
'componentDidMount',
'render'
];
const proto = Cls.prototype;
// let argsString: string = '';
let argsCount = 0;
for (let i = 0, hl = hooks.length; i < hl; i++) {
const hookName = hooks[i];
const fn = proto[hookName] as Function;
if (fn !== undefined) {
// const args = getArguments(fn);
const count = fn.length;
if (count > argsCount) {
argsCount = count;
// argsString = args;
}
}
}
// avoid name collision
const ars: string[] = [];
for (let i = 0; i < argsCount; i++) {
ars.push('_' + i);
}
const argsString = ars.join(',');
// this is for compiled code
// tslint:disable-next-line:prefer-const
let cachedArgs: any;
function compileSetCachedStrings(cacheArgsVariableString: string) {
cacheArgsVariableString = cacheArgsVariableString.replace(/[^a-zA-Z0-9_$]|\n|\s/g, '');
const ss: string[] = [];
for (let i = 0; i < argsCount; i++) {
ss.push(`(cachedArgs[${i}] !== ${'_'+i}) && (cachedArgs[${i}] = ${'_'+i})`);
}
// make sure it's an expression
if (ss.length === 0) {
return 'cachedArgs';
}
return `(cachedArgs = ${cacheArgsVariableString}.cachedArgs,${ss.join(',')})`;
}
// tslint:disable-next-line:prefer-const
let f: any;
const originalFunctionString = functionComponent.toString();
const cachedArgsVariableString = originalFunctionString.match(/MACRO_GET_VARIABLE_NAME\(([a-zA-Z0-9_$]+)\)/)![1];
const newFunctionString = originalFunctionString
.replace(/['"]MACRO_ARGS['"]/g, argsString)
.replace(/MACRO_GET_VARIABLE_NAME\(([a-zA-Z0-9_$]+)\)/, compileSetCachedStrings(cachedArgsVariableString))
.replace(new RegExp(functionComponent.name + '[^{]*{'), `${Cls.name}FunctionComponent(${argsString}){`);
// tslint:disable-next-line:no-eval
eval('f = ' + newFunctionString);
// use the compiled version is 60% faster
// and I see when use the original function, there are many "Builtins_CallFunction_ReceiverIsNotNullOrUndefined"
// and when use compiled version, they are gone
// funny v8...
// tslint:disable-next-line:no-eval
// eval('f = ' + functionComponent.toString());
return f;
// return functionComponent as any;
}
function createStackNode() {
return ({
//
});
}
const Root = toFunctionComponent(class extends Component<[Function]> {
render(child: Function) {
child();
}
})
export function getRoot<T>(rootView: T) {
const cachedContext: Context = {
// the variables shared by all function calls of a root
lastCallStack: undefined,
memoryPool: new MemoryPool(createStackNode),
isBatchedUpdate: false,
// root variables definition end
// the variables shared inside a layer of a subtree
parentView: undefined,
parentInCurrentCallStack: undefined,
preSiblingInCurrentCallStack: undefined,
lastNode: undefined,
}
function forceUpdate(node: StackNode) {
const instance = node.i!;
if (instance.__forcedUpdate === true) {
context!.lastNode = instance.__stackNode;
instance.__stackNode.f!.apply(null, instance.cachedArgs);
return false;
}
return true;
}
const cachedQueue = new Queue<StackNode>();
return ({
Root(child: Function) {
cachedContext.lastNode = cachedContext.lastCallStack;
cachedContext.parentInCurrentCallStack = undefined;
cachedContext.preSiblingInCurrentCallStack = undefined;
cachedContext.parentView = rootView;
context = cachedContext;
Root(child);
context = undefined;
},
batchedUpdates(fn: Function) {
context = cachedContext;
context.isBatchedUpdate = true;
fn();
context.isBatchedUpdate = false;
const nodesToBeTraversed = cachedQueue;
nodesToBeTraversed.reset();
context.skippedNodes = nodesToBeTraversed;
const {lastCallStack} = context;
if (lastCallStack !== undefined) {
walkModifiedCrossListNode(nodesToBeTraversed, lastCallStack, forceUpdate);
}
context.skippedNodes = undefined;
context = undefined;
}
});
}
|
86b7f8f7e9cf411652337f9eb5f39092deda4d51
|
TypeScript
|
Maks0123/factoryBusinessOptimisation
|
/pms-client/src/app/models/HR/employment-info.ts
| 2.90625
| 3
|
export class EmploymentInfo {
id: number;
employmentDate: Date;
dismissalDate: Date;
dismissReason: string;
constructor() {
this.id = -1;
}
clone(): EmploymentInfo {
const info = new EmploymentInfo();
info.id = this.id;
info.employmentDate = this.employmentDate;
info.dismissalDate = this.dismissalDate;
info.dismissReason = this.dismissReason;
return info;
}
initFrom(info: EmploymentInfo) {
this.id = info.id;
this.employmentDate = info.employmentDate;
this.dismissalDate = info.dismissalDate;
this.dismissReason = info.dismissReason;
}
}
|