Datasets:

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
d78248019b8837507a81516c850b9c8a04b46eff
TypeScript
aizigao/keepTraining
/basic_review/type-challenge/meduim/612-medium-kebabcase.ts
2.953125
3
/* 612 - KebabCase ------- by Johnson Chu (@johnsoncodehk) #medium #template-literal ### Question `FooBarBaz` -> `foo-bar-baz` > View on GitHub: https://tsch.js.org/612 */ /* _____________ Your Code Here _____________ */ // type KebabCase<S> = any; type recurse<S extends string> = S extends `${infer first}${infer rest}` ? first extends Uncapitalize<first> ? `${first}${recurse<rest>}` : `-${Uncapitalize<first>}${recurse<rest>}` : S; type KebabCase<S extends string> = recurse<Uncapitalize<S>>; /* _____________ Test Cases _____________ */ import { Equal, Expect } from "@type-challenges/utils"; type cases = [ Expect<Equal<KebabCase<"FooBarBaz">, "foo-bar-baz">>, Expect<Equal<KebabCase<"fooBarBaz">, "foo-bar-baz">>, Expect<Equal<KebabCase<"foo-bar">, "foo-bar">>, Expect<Equal<KebabCase<"foo_bar">, "foo_bar">>, Expect<Equal<KebabCase<"Foo-Bar">, "foo--bar">>, Expect<Equal<KebabCase<"ABC">, "a-b-c">>, Expect<Equal<KebabCase<"-">, "-">>, Expect<Equal<KebabCase<"">, "">>, Expect<Equal<KebabCase<"😎">, "😎">> ]; /* _____________ Further Steps _____________ */ /* > Share your solutions: https://tsch.js.org/612/answer > View solutions: https://tsch.js.org/612/solutions > More Challenges: https://tsch.js.org */
7eafa7ee578c89a9335a5a359de6eb546f763747
TypeScript
distunal/KungFuScreeps
/src/Military/Military.Intents.Helper.ts
2.78125
3
import _ from "lodash"; import { ACTION_MOVE, ERROR_ERROR, MemoryApi_Military, UserException } from "Utils/Imports/internals"; export class MilitaryIntents_Helper { /** * Get the map of the creeps based on their caravan position * @param creeps the creeps in the squad * @param instance the instance we are controlling * @returns hash map of creeps with caravan position being the key */ private static getCreepPositionMap(instance: ISquadManager): { [key: number]: Creep } { const creeps: Creep[] = MemoryApi_Military.getLivingCreepsInSquadByInstance(instance); const positionMap: { [key: number]: Creep } = {} _.forEach(creeps, (creep: Creep) => { const creepOptions: CreepOptionsMili = creep.memory.options as CreepOptionsMili; if (creepOptions.caravanPos === undefined || creepOptions.caravanPos === null) throw new UserException("Could not rotate creep, no caravan pos", "Squad - " + instance.squadUUID, ERROR_ERROR); positionMap[creepOptions.caravanPos] = creep; }); return positionMap; } /** * Get the intent mapper for ease of use in pushing intents to creeps * @returns intent mapper */ private static getIntentMap(): { [key: string]: Move_MiliIntent } { return { ["left"]: { action: ACTION_MOVE, target: LEFT, targetType: "direction" }, ["up_left"]: { action: ACTION_MOVE, target: TOP_LEFT, targetType: "direction" }, ["down_left"]: { action: ACTION_MOVE, target: BOTTOM_LEFT, targetType: "direction" }, ["up_right"]: { action: ACTION_MOVE, target: TOP_RIGHT, targetType: "direction" }, ["down_right"]: { action: ACTION_MOVE, target: BOTTOM_RIGHT, targetType: "direction" }, ["right"]: { action: ACTION_MOVE, target: RIGHT, targetType: "direction" }, ["up"]: { action: ACTION_MOVE, target: TOP, targetType: "direction" }, ["down"]: { action: ACTION_MOVE, target: BOTTOM, targetType: "direction" } }; } /** * Queue the intents to turn the squads orientation around * @param instance The current instance we are controlling * @param currentOrientation the current direction the squad is facing */ public static queueIntentsQuadSquadTurnAround(instance: ISquadManager, currentOrientation: DirectionConstant): void { const positionMap: { [key: number]: Creep } = this.getCreepPositionMap(instance); const intentMapper: { [key: string]: Move_MiliIntent } = this.getIntentMap(); switch (currentOrientation) { case TOP: if (positionMap[0] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[0].name, intentMapper["down_right"]); if (positionMap[1] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[1].name, intentMapper["down_left"]); if (positionMap[2] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[2].name, intentMapper["up_right"]); if (positionMap[3] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[3].name, intentMapper["up_left"]); break; case LEFT: if (positionMap[0] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[0].name, intentMapper["up_right"]); if (positionMap[1] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[1].name, intentMapper["down_right"]); if (positionMap[2] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[2].name, intentMapper["up_left"]); if (positionMap[3] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[3].name, intentMapper["down_left"]); break; case RIGHT: if (positionMap[0] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[0].name, intentMapper["down_left"]); if (positionMap[1] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[1].name, intentMapper["up_left"]); if (positionMap[2] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[2].name, intentMapper["down_right"]); if (positionMap[3] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[3].name, intentMapper["up_right"]); break; case BOTTOM: if (positionMap[0] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[0].name, intentMapper["up_left"]); if (positionMap[1] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[1].name, intentMapper["up_right"]); if (positionMap[2] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[2].name, intentMapper["down_left"]); if (positionMap[3] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[3].name, intentMapper["down_right"]); break; } } /** * Queue the intents to rotate the squad clockwise * @param instance The current instance we are controlling * @param currentOrientation the current direction the squad is facing */ public static queueIntentsQuadSquadRotateClockwise(instance: ISquadManager, currentOrientation: DirectionConstant): void { const positionMap: { [key: number]: Creep } = this.getCreepPositionMap(instance); const intentMapper: { [key: string]: Move_MiliIntent } = this.getIntentMap(); switch (currentOrientation) { case TOP: if (positionMap[0] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[0].name, intentMapper["right"]); if (positionMap[1] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[1].name, intentMapper["down"]); if (positionMap[2] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[2].name, intentMapper["up"]); if (positionMap[3] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[3].name, intentMapper["left"]); break; case LEFT: if (positionMap[0] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[0].name, intentMapper["up"]); if (positionMap[1] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[1].name, intentMapper["right"]); if (positionMap[2] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[2].name, intentMapper["left"]); if (positionMap[3] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[3].name, intentMapper["down"]); break; case RIGHT: if (positionMap[0] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[0].name, intentMapper["down"]); if (positionMap[1] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[1].name, intentMapper["left"]); if (positionMap[2] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[2].name, intentMapper["right"]); if (positionMap[3] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[3].name, intentMapper["up"]); break; case BOTTOM: if (positionMap[0] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[0].name, intentMapper["left"]); if (positionMap[1] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[1].name, intentMapper["up"]); if (positionMap[2] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[2].name, intentMapper["down"]); if (positionMap[3] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[3].name, intentMapper["right"]); break; } } /** * Queue the intents to rotate the squad counter clockwise * @param instance The current instance we are controlling * @param currentOrientation the current direction the squad is facing */ public static queueIntentsQuadSquadRotateCounterClockwise(instance: ISquadManager, currentOrientation: DirectionConstant): void { const positionMap: { [key: number]: Creep } = this.getCreepPositionMap(instance); const intentMapper: { [key: string]: Move_MiliIntent } = this.getIntentMap(); switch (currentOrientation) { case TOP: if (positionMap[0] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[0].name, intentMapper["down"]); if (positionMap[1] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[1].name, intentMapper["left"]); if (positionMap[2] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[2].name, intentMapper["right"]); if (positionMap[3] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[3].name, intentMapper["up"]); break; case LEFT: if (positionMap[0] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[0].name, intentMapper["right"]); if (positionMap[1] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[1].name, intentMapper["down"]); if (positionMap[2] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[2].name, intentMapper["up"]); if (positionMap[3] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[3].name, intentMapper["left"]); break; case RIGHT: if (positionMap[0] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[0].name, intentMapper["left"]); if (positionMap[1] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[1].name, intentMapper["up"]); if (positionMap[2] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[2].name, intentMapper["down"]); if (positionMap[3] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[3].name, intentMapper["right"]); break; case BOTTOM: if (positionMap[0] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[0].name, intentMapper["up"]); if (positionMap[1] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[1].name, intentMapper["right"]); if (positionMap[2] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[2].name, intentMapper["left"]); if (positionMap[3] !== undefined) MemoryApi_Military.pushIntentToCreepStack(instance, positionMap[3].name, intentMapper["down"]); break; } } /** * Update the orientation of the squad * @param currentOrientation the current orientation of the squad * @param operationApplied the operation that was applied to decide the new orientation */ public static updateSquadOrientation(currentOrientation: DirectionConstant, operationApplied: "clockwise" | "counterClockwise" | "turnAround"): DirectionConstant { interface SquadOrientationMapper { [key: string]: { [key: string]: DirectionConstant }; } const orientationMapper: SquadOrientationMapper = { [TOP]: { ["clockwise"]: RIGHT, ['counterClockwise']: LEFT, ['turnAround']: BOTTOM }, [LEFT]: { ["clockwise"]: TOP, ['counterClockwise']: BOTTOM, ['turnAround']: RIGHT }, [RIGHT]: { ["clockwise"]: BOTTOM, ['counterClockwise']: TOP, ['turnAround']: LEFT }, [BOTTOM]: { ["clockwise"]: LEFT, ['counterClockwise']: RIGHT, ['turnAround']: TOP } } return orientationMapper[currentOrientation][operationApplied]; } }
aa4c3b49ddd963e5b72e5abd2fbe2f942c4a2783
TypeScript
pisa-kun/practice_ts_oreilly
/chapter5/src/shoe.ts
3.75
4
interface Shoe { purpose :string } class BalletFlat implements Shoe{ purpose = 'Dancing' } class Boot implements Shoe{ purpose = 'woodcutting' } class Sneaker implements Shoe{ purpose = 'walking' } let Shoe = { create(type : 'balletFlat' | 'boot' | 'sneaker'): Shoe{ switch(type){ case 'balletFlat': return new BalletFlat case 'boot': return new Boot case 'sneaker': return new Sneaker } } } let b = Shoe.create('balletFlat') // Shoe console.log(b.purpose) let s = Shoe.create('sneaker') // Shoe console.log(s.purpose) // interface instance change s = b console.log(s.purpose)
7552c58d67c677f964561057d0a3fd760bde409b
TypeScript
etcdigital/atomic-css
/packages/css/src/hash/index.ts
3.140625
3
// tslint:disable: no-bitwise /* * @ see more in * https://github.com/garycourt/murmurhash-js */ const hasher = (str: string): string => { const z = 0x5bd1e995; const y = 0xe995; const x = 16; const w = 0xffff; const v = 24; const c = (s: string, i: number) => s.charCodeAt(i) & 0xff; const g = (k: any) => (k & w) * z + (((k >>> x) * y) << x); const j = (h: any) => (h & w) * z + (((h >>> x) * y) << x); let h = 0; let k; let i = 0; let len = str.length; for (; len >= 4; ++i, len -= 4) { k = c(str, i) | (c(str, ++i) << 8) | (c(str, ++i) << x) | (c(str, ++i) << v); k = g(k); k ^= k >>> v; h = g(k) ^ j(h); } switch (len) { case 3: h ^= c(str, i + 2) << x; case 2: h ^= c(str, i + 1) << 8; case 1: h ^= c(str, i); h = j(h); } h ^= h >>> 13; h = j(h); return ((h ^ (h >>> 15)) >>> 0).toString(36); }; export const hash = (str: string): string => { const h = hasher(str); // CSS class names can not start with numbers const prefix = /[0-9]/gi.test(h[0]) ? "_" : ""; const commaPrevent = prefix.replace(",", "_"); return `${commaPrevent}${h}`; }; export default hash;
2a3bd9e06a4c10e83e9a288073fd755664ba1998
TypeScript
vofus/webgl_lessons
/src/tools/m3.ts
2.671875
3
// https://webglfundamentals.org/webgl/lessons/ru/webgl-2d-matrices.html export const m3 = { translation: function (tx: number, ty: number): number[] { return [ 1, 0, 0, 0, 1, 0, tx, ty, 1, ]; }, rotation: function (angleInRadians: number): number[] { const c = Math.cos(angleInRadians); const s = Math.sin(angleInRadians); return [ c, -s, 0, s, c, 0, 0, 0, 1, ]; }, scaling: function (sx: number, sy: number): number[] { return [ sx, 0, 0, 0, sy, 0, 0, 0, 1, ]; }, };
86b33c1dfc736010f51b37130088f35ad3bbbf5a
TypeScript
Garavirod/share-letters-cli
/src/app/models/escritor-model.ts
2.859375
3
import { Historia } from "./historia-model"; export class Escritor { public id: string; public username: string; public email: string; public about: string; public imageURL: string; public numHist: number; public historias: Array<any>; constructor(){ this.id = ""; this.username = ""; this.email = ""; this.about = ""; this.imageURL = ""; this.numHist = 0; this.historias = []; } public getHistorias(): Array<any> { return this.historias; } public setHistorias(historias: Array<any>): void { this.historias = historias; } public getId(): string { return this.id; } public setId(id: string): void { this.id = id; } public getUsername(): string { return this.username; } public setUsername(username: string): void { this.username = username; } public getEmail(): string { return this.email; } public setEmail(email: string): void { this.email = email; } public getAbout(): string { return this.about; } public setAbout(about: string): void { this.about = about; } public getImageURL(): string { return this.imageURL; } public setImageURL(imageURL: string): void { this.imageURL = imageURL; } public getNumHist(): number { return this.numHist; } public setNumHist(numHist: number): void { this.numHist = numHist; } public addNewStory(historia:any){ this.historias.unshift(historia); } }
8fdcb8d41e8428035b021707e3ee0e6535cb90fc
TypeScript
KoheiNishino/js_practice
/typescript-todo-app/src/index.ts
3.34375
3
// 追加ボタンの処理 const onClickAdd = () => { const addText: HTMLInputElement = document.getElementById("add-text") as HTMLInputElement if (!addText.value || !addText.value.match(/\S/g)) { alert("Todoを入力してください。") return } createUnfinishedTodos(addText.value) addText.value = "" } const createUnfinishedTodos = (text: string) => { const unfinishedTodos: HTMLElement | null = document.getElementById("unfinished-todos") if (unfinishedTodos === null) return const maximumNumberOfTodos = 5 if (unfinishedTodos.childElementCount >= maximumNumberOfTodos) { alert(`登録できるTodoは${maximumNumberOfTodos}個までです。未完了のTodoを減らしてください。`) return } // divタグ生成 const div = document.createElement("div"); div.className = "list-row"; // liタグ生成 const li = document.createElement("li"); li.innerText = text; // buttonタグ生成 const completeButton: HTMLButtonElement = createCompleteButton() const deleteButton: HTMLButtonElement = createDeleteButton() // divタグの子要素に各要素を設定 div.appendChild(li) div.appendChild(completeButton) div.appendChild(deleteButton) // 完了リストに追加 unfinishedTodos.appendChild(div); } // 完了ボタンの設定 const createCompleteButton = (): HTMLButtonElement => { const completeButton = document.createElement("button") completeButton.innerText = "完了" completeButton.addEventListener("click", () => { if (completeButton.parentNode === null) return addToFinishedTodos(completeButton.parentNode) }) return completeButton } // 完了ボタンの処理 const addToFinishedTodos = (target: (Node & ParentNode)) => { // 押された完了ボタンの親タグ(div)を未完了リストから削除 deleteFromUnfinishiedTodos(target) // TODO内容テキストを取得 const todoFirstElementChild: HTMLElement = target.firstElementChild as HTMLElement // div以下を初期化 target.textContent = null // liタグ生成 const li = document.createElement("li") li.innerText = todoFirstElementChild.innerText // buttonタグ生成 const backButton: HTMLButtonElement = createBackButton() // divタグの子要素に各要素を設定 target.appendChild(li) target.appendChild(backButton) // 完了リストに追加 const finishedTodos: HTMLElement | null = document.getElementById("finished-todos") if (finishedTodos !== null) { finishedTodos.appendChild(target) } } // 戻すボタンの設定 const createBackButton = (): HTMLButtonElement => { const backButton = document.createElement("button") backButton.innerText = "戻す" backButton.addEventListener("click", () => { if (backButton.parentNode !== null) { backToUnfinishedTodos(backButton.parentNode) } }) return backButton } // 戻すボタンの処理 const backToUnfinishedTodos = (target: (Node & ParentNode)) => { // 押された戻すボタンの親タグ(div)を完了リストから削除 const finishedTodos: HTMLElement | null = document.getElementById("finished-todos") if (finishedTodos !== null) { finishedTodos.removeChild(target) } // 未完了リストに追加 const todoFirstElementChild: HTMLElement = target.firstElementChild as HTMLElement createUnfinishedTodos(todoFirstElementChild.innerText); } // 削除ボタンの設定 const createDeleteButton = (): HTMLButtonElement => { const deleteButton = document.createElement("button") deleteButton.innerText = "削除" deleteButton.addEventListener("click", () => { // 押された削除ボタンの親タグ(div)を未完了リストから削除 if (deleteButton.parentNode !== null) { deleteFromUnfinishiedTodos(deleteButton.parentNode) } }) return deleteButton } // 削除ボタンの処理 const deleteFromUnfinishiedTodos = (target: (Node & ParentNode)) => { const unfinishedTodos: HTMLElement | null = document.getElementById("unfinished-todos") if (unfinishedTodos !== null) { unfinishedTodos.removeChild(target) } } // 追加ボタンに処理を追加 const addButton: HTMLElement | null = document.getElementById("add-button") if (addButton !== null) { addButton.addEventListener("click", () => {onClickAdd()}) }
4e0cc7bc4a85eadf20105ea8bac99a0cf62a8531
TypeScript
bolollo/protomaps.js
/test/json_style.test.ts
2.65625
3
import { filterFn, numberOrFn, numberFn, getFont } from '../src/compat/json_style' import assert from 'assert' import baretest from 'baretest' test = baretest("Json Style") test("==",async () => { let f = filterFn(['==','building','yes']) assert(f(0,{props:{"building":"yes"}})) }) test("!=",async () => { let f = filterFn(['!=','building','yes']) assert(!f(0,{props:{"building":"yes"}})) assert(f(0,{props:{"building":"no"}})) }) test("<",async () => { let f = filterFn(['<','level',3]) assert(f(0,{props:{"level":2}})) assert(!f(0,{props:{"level":3}})) }) test("<=",async () => { let f = filterFn(['<=','level',3]) assert(f(0,{props:{"level":2}})) assert(f(0,{props:{"level":3}})) }) test(">",async () => { let f = filterFn(['>','level',3]) assert(f(0,{props:{"level":4}})) assert(!f(0,{props:{"level":3}})) }) test(">=",async () => { let f = filterFn(['>=','level',3]) assert(f(0,{props:{"level":4}})) assert(f(0,{props:{"level":3}})) }) test("in",async () => { let f = filterFn(['in','type','foo','bar']) assert(f(0,{props:{"type":"foo"}})) assert(f(0,{props:{"type":"bar"}})) assert(!f(0,{props:{"type":"baz"}})) }) test("!in",async () => { let f = filterFn(['!in','type','foo','bar']) assert(!f(0,{props:{"type":"bar"}})) assert(f(0,{props:{"type":"baz"}})) }) test("has",async () => { let f = filterFn(['has','type']) assert(f(0,{props:{"type":"foo"}})) assert(!f(0,{props:{}})) }) test("!has",async () => { let f = filterFn(['!has','type']) assert(!f(0,{props:{"type":"foo"}})) assert(f(0,{props:{}})) }) test("!",async () => { let f = filterFn(["!",['has','type']]) assert(!f(0,{props:{"type":"foo"}})) assert(f(0,{props:{}})) }) test("all",async () => { let f = filterFn(['all',["==","building","yes"],["==","type","foo"]]) assert(!f(0,{props:{"building":"yes"}})) assert(!f(0,{props:{"type":"foo"}})) assert(f(0,{props:{"building":"yes","type":"foo"}})) }) test("any",async () => { let f = filterFn(['any',["==","building","yes"],["==","type","foo"]]) assert(!f(0,{props:{}})) assert(f(0,{props:{"building":"yes"}})) assert(f(0,{props:{"type":"foo"}})) assert(f(0,{props:{"building":"yes","type":"foo"}})) }) test("numberFn constant", async () => { let n = numberOrFn(5) assert.equal(n,5) n = numberOrFn(undefined) assert.equal(n,0) }) test("numberFn function", async () => { let n = numberFn({base:1,stops:[[14,0],[16,2]]}) assert.equal(n.length,1) assert.equal(n(15),0) assert.equal(n(16),1) assert.equal(n(17),2) }) test("numberFn interpolate", async () => { let n = numberFn(["interpolate",["exponential",1],["zoom"],14,0,16,2]) assert.equal(n.length,1) assert.equal(n(15),0) assert.equal(n(16),1) assert.equal(n(17),2) }) test("numberFn properties", async () => { let n = numberFn(["step",["get","scalerank"],0,1,2,3,4]) assert.equal(n.length,2) assert.equal(n(14,{props:{scalerank:0}}),0) assert.equal(n(14,{props:{scalerank:1}}),2) assert.equal(n(14,{props:{scalerank:3}}),4) assert.equal(n(14,{props:{scalerank:4}}),4) }) test("font", async () => { let n = getFont({'text-font':['Noto'],'text-size':14},{}) assert.equal(n,'14px sans-serif') n = getFont({'text-font':['Noto'],'text-size':15},{}) assert.equal(n,'15px sans-serif') n = getFont({'text-font':['Noto'],'text-size':15},{'Noto':{face:'serif'}}) assert.equal(n,'15px serif') n = getFont({'text-font':['Boto','Noto'],'text-size':15},{'Noto':{face:'serif'},'Boto':{face:'Comic Sans'}}) assert.equal(n,'15px Comic Sans, serif') }) test("font weight and style", async () => { n = getFont({'text-font':['Noto'],'text-size':15},{'Noto':{face:'serif',weight:100}}) assert.equal(n,'100 15px serif') n = getFont({'text-font':['Noto'],'text-size':15},{'Noto':{face:'serif',style:"italic"}}) assert.equal(n,'italic 15px serif') }) test("font size fn zoom", async () => { let n = getFont({'text-font':['Noto'],'text-size':{'base':1,'stops':[[14,1],[16,3]]}},{}) assert.equal(n(15),'1px sans-serif') assert.equal(n(16),'2px sans-serif') assert.equal(n(17),'3px sans-serif') }) test("font size fn zoom props", async () => { let n = getFont({'text-font':['Noto'],'text-size':["step",["get","scalerank"],0,1,12,2,10]},{}) assert.equal(n(14,{props:{scalerank:0}}),'0px sans-serif') assert.equal(n(14,{props:{scalerank:1}}),'12px sans-serif') assert.equal(n(14,{props:{scalerank:2}}),'10px sans-serif') }) export default test
6f27c2ea34ea69a7b78d06bd6c09c5e2f39b3552
TypeScript
Kobzol/davis
/src/app/emulation/instruction/bitwise.ts
2.515625
3
import {BinaryOperation} from "./instruction"; import {CPU} from "../cpu"; export class And extends BinaryOperation { execute(cpu: CPU): number { this.target.setValue(cpu.alu.and(this.target.getValue(), this.source.getValue())); return cpu.getNextInstruction(); } } export class Or extends BinaryOperation { execute(cpu: CPU): number { this.target.setValue(cpu.alu.or(this.target.getValue(), this.source.getValue())); return cpu.getNextInstruction(); } } export class Xor extends BinaryOperation { execute(cpu: CPU): number { this.target.setValue(cpu.alu.xor(this.target.getValue(), this.source.getValue())); return cpu.getNextInstruction(); } }
8d21497a5c3cb65d45bc6586669714c586043d02
TypeScript
dhindustries/saggitarius-path
/src/driver/posix.ts
3.03125
3
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. import { PathInfo } from "../pathinfo"; export let cwd = ""; export const env: Record<string, string> = {}; export const separator = "/"; export const delimiter = ":"; function isString(value: any): value is string { return typeof(value) === "string"; } function isObject(value: any): value is Record<string, string> { return typeof(value) === "object"; } // resolves . and .. elements in a path array with directory names there // must be no slashes or device names (c:\) in the array // (so also no leading and trailing slashes - it does not distinguish // relative and absolute paths) function normalizeArray(parts: string[], allowAboveRoot: boolean): string[] { let res = []; for (let i = 0; i < parts.length; i++) { let p = parts[i]; // ignore empty parts if (!p || p === ".") { continue; } if (p === "..") { if (res.length && res[res.length - 1] !== "..") { res.pop(); } else if (allowAboveRoot) { res.push(".."); } } else { res.push(p); } } return res; } // returns an array with empty elements removed from either end of the input // array or the original array if no elements need to be removed function trimArray(arr: string[]): string[] { let lastIndex = arr.length - 1; let start = 0; for (; start <= lastIndex; start++) { if (arr[start]) { break; } } let end = lastIndex; for (; end >= 0; end--) { if (arr[end]) { break; } } if (start === 0 && end === lastIndex) { return arr; } if (start > end) { return []; } return arr.slice(start, end + 1); } // Split a filename into [root, dir, basename, ext], unix version // "root" is just a slash, or nothing. const splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; function splitPath(filename: string): string[] { return splitPathRe.exec(filename).slice(1); } // path.resolve([from ...], to) // posix version export function resolve(...paths: string[]): string { let resolvedPath = ""; let resolvedAbsolute = false; for (let i = paths.length - 1; i >= -1 && !resolvedAbsolute; i--) { let path = (i >= 0) ? paths[i] : cwd; // Skip empty and invalid entries if (!isString(path)) { throw new TypeError("Arguments to path.resolve must be strings"); } else if (!path) { continue; } resolvedPath = path + "/" + resolvedPath; resolvedAbsolute = path[0] === "/"; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeArray(resolvedPath.split("/"), !resolvedAbsolute).join("/"); return ((resolvedAbsolute ? "/" : "") + resolvedPath) || "."; } // path.normalize(path) // posix version export function normalize(path: string): string { const isAbs = isAbsolute(path); const trailingSlash = path && path[path.length - 1] === "/"; // Normalize the path path = normalizeArray(path.split("/"), !isAbs).join("/"); if (!path && !isAbs) { path = "."; } if (path && trailingSlash) { path += "/"; } return (isAbs ? "/" : "") + path; } // posix version export function isAbsolute(path: string): boolean { return path.charAt(0) === "/"; } // posix version export function join(...paths: string[]): string { let path = ""; for (let i = 0; i < paths.length; i++) { const segment = paths[i]; if (!isString(segment)) { throw new TypeError("Arguments to path.join must be strings"); } if (segment) { if (!path) { path += segment; } else { path += "/" + segment; } } } return normalize(path); } // path.relative(from, to) // posix version export function relative(from: string, to: string): string { from = resolve(from).substr(1); to = resolve(to).substr(1); const fromParts = trimArray(from.split("/")); const toParts = trimArray(to.split("/")); const length = Math.min(fromParts.length, toParts.length); let samePartsLength = length; for (let i = 0; i < length; i++) { if (fromParts[i] !== toParts[i]) { samePartsLength = i; break; } } let outputParts = []; for (let i = samePartsLength; i < fromParts.length; i++) { outputParts.push(".."); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join("/"); } export function _makeLong(path: string): string { return path; } export function dirname(path: string): string { const result = splitPath(path); const root = result[0]; let dir = result[1]; if (!root && !dir) { // No dirname whatsoever return "."; } if (dir) { // It has a dirname, strip trailing slash dir = dir.substr(0, dir.length - 1); } return root + dir; } export function basename(path: string, ext: string): string { let f = splitPath(path)[2]; if (ext && f.substr(-1 * ext.length) === ext) { f = f.substr(0, f.length - ext.length); } return f; } export function extname(path: string): string { return splitPath(path)[3]; } export function format(pathObject: PathInfo): string { if (!isObject(pathObject)) { throw new TypeError( "Parameter \"pathObject\" must be an object, not " + typeof pathObject ); } const root = pathObject.root || ""; if (!isString(root)) { throw new TypeError( "\"pathObject.root\" must be a string or undefined, not " + typeof pathObject.root ); } const dir = pathObject.dir ? pathObject.dir + separator : ""; const base = pathObject.base || ""; return dir + base; } export function parse(pathString: string): PathInfo { if (!isString(pathString)) { throw new TypeError( "Parameter \"pathString\" must be a string, not " + typeof pathString ); } const allParts = splitPath(pathString); if (!allParts || allParts.length !== 4) { throw new TypeError("Invalid path \"" + pathString + "\""); } allParts[1] = allParts[1] || ""; allParts[2] = allParts[2] || ""; allParts[3] = allParts[3] || ""; return { root: allParts[0], dir: allParts[0] + allParts[1].slice(0, -1), base: allParts[2], ext: allParts[3], name: allParts[2].slice(0, allParts[2].length - allParts[3].length) }; }
0bc5f2be7f5ec68f04302d61f3142057aba61632
TypeScript
SmileSmith/puppeteer-e2e
/tests/utils/index.ts
2.890625
3
import { DirectNavigationOptions, Target } from 'puppeteer'; /** * 为Url添加参数 * * @export * @param {string} url * @param {({ [key in string]: string | number | boolean })} params * @returns */ export function addUrlParam(url: string, params: { [key in string]: string | number | boolean }) { const urlArr = url.split('#'); const hash = urlArr[1]; url = urlArr[0]; for (const key in params) { const reg = new RegExp('([?&])' + key + '=[^&]*(&|$)', 'i'); if (reg.test(url)) { // 判断是否存在这个参数,若存在则替换 url = url.replace(reg, '$1' + key + '=' + params[key] + '$2'); } else { // 不存在则追加 url += (url.indexOf('?') > -1 ? '&' : '?') + key + '=' + params[key]; } } if (hash) { url = url + '#' + hash; } return url; } // 等待一段时间 export const wait = (timeout: number) => new Promise((resolve) => { setTimeout(resolve, timeout); }); // 打开网页 export const goto = (url: string, options?: DirectNavigationOptions) => { url = addUrlParam(url, { _test: Date.now() }); return page.goto(url, options || { waitUntil: 'networkidle0' }); }; // 固定本地时间,保持页面渲染的一致性 export const mockDate = (value: string | number) => { const listener = async (target: Target) => { browser.off('targetchanged', listener); const targetPage = await target.page(); const client = await targetPage.target().createCDPSession(); await client.send('Runtime.evaluate', { expression: ` var d = new Date(${JSON.stringify(value)}); Date = class extends Date { constructor(a) { super(a); if (!a) { return d; } } }; Date.now = function() { return d.getTime(); }; `, }); }; browser.on('targetchanged', listener); }; // 获取节点所在的位置 export const getClip = async (selector: string, index = 0) => { const result = await page.evaluate( (a, b) => { let el; if (b === 0) { el = document.querySelector(a); } else { el = document.querySelectorAll(a)[b]; } if (el) { const offset = { x: 0, y: 0, width: el.offsetWidth, height: el.offsetHeight }; while (el) { offset.y += el.offsetTop; offset.x += el.offsetLeft; el = el.offsetParent; } return JSON.stringify(offset); } return null; }, selector, index, ); if (result) { return JSON.parse(result); } return null; }; // 滚动到节点所在的位置 export const scrollTo = (selector: string | number, index = 0) => { return page.evaluate( (a, b) => { if (typeof a === 'string') { let el; if (b === 0) { el = document.querySelector(a); } else { el = document.querySelectorAll(a)[b]; } if (el) { document.documentElement.scrollTop += el.getBoundingClientRect().top; } } else { document.documentElement.scrollTop = a; } }, selector, index, ); };
85100f6ddf4167745d8e3348818a2186c6619ec4
TypeScript
Assasindie/fortniteBot
/src/core/EventCore.ts
2.71875
3
import * as Discord from "discord.js"; import * as winston from "winston"; import Logger from "log/Logger"; import NikkuCore from "core/NikkuCore"; import OnMessageState from "state/OnMessageState"; export default class EventCore { private readonly logger: winston.Logger = new Logger(this.constructor.name).getLogger(); /** * Main interface with Discord.js */ private client: Discord.Client; private core: NikkuCore; /** * @classdesc Class for handling events. * @param core - The main bot core. */ public constructor(core: NikkuCore) { this.client = core.getClient(); this.core = core; this.logger.debug("Event Core created."); } /** * Begin listening for channel messages. */ public listenMessages(): void { this.client.on("message", (message: Discord.Message) => { if (message.attachments.size >= 1) { // } else if (!message.author.bot) { this.core.getCommandManager().parseLine(message.content, message.author.id, new OnMessageState(this.core, message)); } }); } public handleGuildRegistration(): void { this.client.on("guildCreate", (guild) => { this.logger.verbose(`Joined new server "${guild.name}".`); }); this.client.on("guildDelete", (guild) => { this.logger.verbose(`Left server "${guild.name}".`); }); } }
fe9f61e75006f938288a553cfe788ad068420904
TypeScript
wlee88/iam.alexplescan.com
/src/CanvasCreator.ts
2.515625
3
export class CanvasCreator { createAndAddToDocument (): HTMLCanvasElement { const canvas = document.createElement('canvas') canvas.style.position = 'absolute' canvas.width = window.innerWidth canvas.height = window.innerHeight document.body.prepend(canvas) return canvas } }
1e08e63c68deb663ee6d4a1340762ba1c60d593c
TypeScript
justinefication/assalaam-pmis
/src/app/member.service.ts
2.609375
3
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MemberService { constructor() { } getMemberInfo(memberID: string) { /* | If the length of the entered member code is greater than | or equal to 8, try to search for the member. */ if (memberID === '123456') { console.log('Member'); } return null; } }
2cb192f7cc9bc32f1359d0a4bd8cccdb5ab282c4
TypeScript
user-hejun/up_2020
/TS/demo1.ts
2.5625
3
function terry() { let web : string = 'hello world' console.log(web); } terry()
6b5b2aa77a422caa8d691cf033c6764afb568e68
TypeScript
gj262/thewatertemp-reactified
/src/reducers/temperatureData.ts
3
3
import { Action, ActionTypes, TemperatureDataIds, Temperature, TemperatureRange, ComparisonList } from "../types"; interface SingleTemperatureState { isLoading: boolean; data?: Temperature; failure?: Error; } interface TemperatureRangeState { isLoading: boolean; data?: TemperatureRange; failure?: Error; } interface ComparisonListState { isLoading: boolean; data?: ComparisonList; failure?: Error; endReason?: string; } type PossibleStates = SingleTemperatureState | TemperatureRangeState | ComparisonListState; interface PerStationState { [dataId: string]: PossibleStates; } export interface TemperatureDataState { [stationId: string]: PerStationState; } export default function temperatureData(state: TemperatureDataState = {}, action: Action): TemperatureDataState { let stationState; let temperatureDataState; switch (action.type) { case ActionTypes.LOADING_TEMPERATURE_DATA: stationState = state[action.meta.stationId] || {}; temperatureDataState = action.meta.dataId in stationState ? { ...stationState[action.meta.dataId], isLoading: true } : { isLoading: true }; stationState = { ...stationState, [action.meta.dataId]: temperatureDataState }; return { ...state, [action.meta.stationId]: stationState }; case ActionTypes.TEMPERATURE_DATA_LOADED: stationState = state[action.meta.stationId] || {}; stationState = { ...stationState, [action.meta.dataId]: { isLoading: false, data: action.payload.data } as PossibleStates }; return { ...state, [action.meta.stationId]: stationState }; case ActionTypes.PARTIAL_COMPARISON_LIST_LOAD: stationState = state[action.meta.stationId] || {}; temperatureDataState = stationState[action.meta.dataId] || {}; let update = false; let data = (temperatureDataState.data as ComparisonList) || []; data = data.map(item => { if (item.regarding === action.payload.data.regarding) { update = true; return action.payload.data; } return item; }); if (!update) { data = [...data, action.payload.data]; } temperatureDataState = { data, isLoading: !!temperatureDataState.isLoading }; stationState = { ...stationState, [action.meta.dataId]: temperatureDataState }; return { ...state, [action.meta.stationId]: stationState }; case ActionTypes.COMPLETED_COMPARISON_LIST_LOAD: stationState = state[action.meta.stationId] || {}; temperatureDataState = stationState[action.meta.dataId] || {}; temperatureDataState = { data: temperatureDataState.data as ComparisonList, endReason: action.payload.endReason, isLoading: false }; stationState = { ...stationState, [action.meta.dataId]: temperatureDataState }; return { ...state, [action.meta.stationId]: stationState }; case ActionTypes.FAILED_TO_LOAD_TEMPERATURE_DATA: stationState = state[action.meta.stationId] || {}; temperatureDataState = stationState[action.meta.dataId] || {}; temperatureDataState = { ...temperatureDataState, isLoading: false, failure: action.error }; stationState = { ...stationState, [action.meta.dataId]: temperatureDataState }; return { ...state, [action.meta.stationId]: stationState }; default: return state; } } export function getTemperature(state: TemperatureDataState, stationId: string, dataId: TemperatureDataIds): Temperature | null { const thisState = _getTemperatureDataState(state, stationId, dataId); return thisState && thisState.data ? (thisState.data as Temperature) : null; } export function getTemperatureRange( state: TemperatureDataState, stationId: string, dataId: TemperatureDataIds ): TemperatureRange | null { const thisState = _getTemperatureDataState(state, stationId, dataId); return thisState && thisState.data ? (thisState.data as TemperatureRange) : null; } export function getComparisonList( state: TemperatureDataState, stationId: string, dataId: TemperatureDataIds ): ComparisonList | null { const thisState = _getTemperatureDataState(state, stationId, dataId); return thisState && thisState.data ? (thisState.data as ComparisonList) : null; } export function isLoading(state: TemperatureDataState, stationId: string, dataId: TemperatureDataIds): boolean { const thisState = _getTemperatureDataState(state, stationId, dataId); return !!(thisState && thisState.isLoading); } export function loadFailed(state: TemperatureDataState, stationId: string, dataId: TemperatureDataIds): boolean { const thisState = _getTemperatureDataState(state, stationId, dataId); return !!(thisState && thisState.failure); } export function getFailureMessage(state: TemperatureDataState, stationId: string, dataId: TemperatureDataIds): string | null { const thisState = _getTemperatureDataState(state, stationId, dataId); return thisState && thisState.failure ? thisState.failure.message : null; } export function getEndReason(state: TemperatureDataState, stationId: string, dataId: TemperatureDataIds): string | null { const thisState = _getTemperatureDataState(state, stationId, dataId); return thisState && "endReason" in thisState && thisState.endReason ? thisState.endReason : null; } function _getTemperatureDataState( state: TemperatureDataState, stationId: string, dataId: TemperatureDataIds ): SingleTemperatureState | TemperatureRangeState | ComparisonListState | null { if (stationId in state) { const thisStationState = state[stationId]; if (thisStationState && dataId in thisStationState) { return thisStationState[dataId] || null; } } return null; }
0cabeab2c8287de2fee044eab75ba26f0797a84c
TypeScript
restuwahyu13/express-payment-gateway
/src/utils/util.uniqueNumber.ts
2.5625
3
export const uniqueOrderNumber = (): string => { const randomOrderNumber: string = Math.random().toString().replace('0.', '') const getRandomOrderNumber: any = parseInt(4 + randomOrderNumber) const getDigitOrderNumber: RegExpExecArray = /\d{10}/.exec(getRandomOrderNumber) const mergeDigitOrderNumber: string = getDigitOrderNumber.join('') const resultDigitOrderNumber = typeof +mergeDigitOrderNumber === 'number' && +mergeDigitOrderNumber return `bfc-${resultDigitOrderNumber}` }
3a8514fd1cd8bf29a3f1a74f37a3309867db87f6
TypeScript
MySocialApp/mysocialapp-ts-client
/src/models/model.ts
2.828125
3
import * as _ from 'lodash'; import {Configuration} from "../configuration"; export interface ModelInterface { load(o: object, conf: Configuration) } export interface Serializable { toJson(): string getJsonParameters(): {} } export class Model implements ModelInterface, Serializable { protected conf: Configuration; load(o: any, conf?: Configuration) { if (conf !== undefined) { this.conf = conf; } _.forOwn(o, (value, key) => { this[key] = value }); } constructor(o?: {}, conf?: Configuration) { if (o !== undefined || conf !== undefined) { this.load(o, conf); } } toJson(): string { return JSON.stringify(this.getJsonParameters()); } getJsonParameters(): {} { return this; } }
507e42f2c3cd0083256c274107e91720f3e7f990
TypeScript
owncast/owncast
/web/components/stores/application-state.ts
2.890625
3
/* This is a finite state machine model that is used by xstate. https://xstate.js.org/ You send events to it and it changes state based on the pre-determined modeling. This allows for a clean and reliable way to model the current state of the web application, and a single place to determine the flow of states. You can paste this code into https://stately.ai/viz to see a visual state map or install the VS Code plugin: https://marketplace.visualstudio.com/items?itemName=statelyai.stately-vscode */ import { createMachine } from 'xstate'; export interface AppStateOptions { chatAvailable: boolean; chatLoading?: boolean; videoAvailable: boolean; appLoading?: boolean; } export function makeEmptyAppState(): AppStateOptions { return { chatAvailable: false, chatLoading: true, videoAvailable: false, appLoading: true, }; } const OFFLINE_STATE: AppStateOptions = { chatAvailable: false, chatLoading: false, videoAvailable: false, appLoading: false, }; const ONLINE_STATE: AppStateOptions = { chatAvailable: true, chatLoading: false, videoAvailable: true, appLoading: false, }; const LOADING_STATE: AppStateOptions = { chatAvailable: false, chatLoading: false, videoAvailable: false, appLoading: true, }; const GOODBYE_STATE: AppStateOptions = { chatAvailable: true, chatLoading: false, videoAvailable: false, appLoading: false, }; export enum AppStateEvent { Loading = 'LOADING', // Have not pulled configuration data from the server. Loaded = 'LOADED', // Configuration data has been pulled from the server. Online = 'ONLINE', // Stream is live Offline = 'OFFLINE', // Stream is not live NeedsRegister = 'NEEDS_REGISTER', // Needs to register a chat user Fail = 'FAIL', // Error ChatUserDisabled = 'CHAT_USER_DISABLED', // Chat user is disabled } const appStateModel = /** @xstate-layout N4IgpgJg5mDOIC5QEMAOqDKAXZWwDoAbAe2QgEsA7KAYgCUBRAcQEkMAVBxgEUVFWKxyWcsUp8QAD0QBGAGwz8ABgCscpUoDsAZgAcKgEwrtATgA0IAJ6zNS-CZMLtcuQBY9Jg5t0BfHxbRMHDwiUgpqGgA5BgZuDAB9RlYOLgkBIRExCWkEGRVFVXUtPUNjcytEAxNXfB0DbSNNORMG119-EEDsXAISMipaABkAeQBBbli0wWFRcSQpWQVlNQ0dfSNTC2tc+vwZVwMZWxNbA5kDAz8A9G6QvvDaADFRlkGpjNns2VcCleL1spbRDaA74FS6ORVfYHTSObRXTo3YIEABOYCg5FgeBRA3ozDYnB47xmWXmOQOKj22hUnl02iajjk2iBCCqdgO2n2VRcbQhCK6yPwaIxWLAOIiz1exMyc1A5KMVJpBjpDJczIqCG0enwXk0MiUENMjiUBjk-KRPSFYDIlnwYkIVDANGGj0egxY0WlnzJiF0TXwulU9LqWhMMl0LIM7ipmguIIObU85qClrRNrtADMMw7KE7hpF3Z75ukSbKFgg5Pp7PSQdTXBp9uVtlHtDG464E7okx0BanrRBbVBiMQIAAjSxOyRYy3IDPYgAU2g0y4AlDReyE0wP8EOR+OwF7SXLff7A8ZNCHYeGWedW3qlDIWkz61rLgjKCO4BIN70wgND2W8o3pyyjKrCdZ6q4sYqMmtyouimLYv+xbTDKXyakuyiuHI+QmCoJquCo2FyCyS52PURzqI+mgqIYpqwYKW62vajoAehsJyFS+paPhfoRhqUa6PgTIuLoRznComiEWaPYWpu-bMVmOYHihHxHuWRQ6pCJz0sqGgNMBBjCfohiEUoIJ0kyDF9umu5jhObE+rkqh2BCLS8XhYa6K4wGUuGtEviYZ5qNZ8k2o5x4IJJnGmlUOixoG5kGCy+G1JyXgHGJJhKByrihQQsBigAbmKjzIOQhAAK5ohF5YXJx+q2MYbieFB4KkW0yj6NBfr6vU3n5fglWFSiGblVVNWqaW6H5HY4bNFJbhKI4HV3k0rgnNlS6xm+1wpngtU5NeGoALQXDqbVBct+g5Qofh+EAA */ createMachine({ id: 'appState', initial: 'loading', predictableActionArguments: true, states: { loading: { meta: LOADING_STATE, on: { NEEDS_REGISTER: { target: 'loading', }, LOADED: { target: 'ready', }, FAIL: { target: 'serverFailure', }, }, }, ready: { initial: 'offline', states: { online: { meta: { ...ONLINE_STATE, }, on: { OFFLINE: { target: 'goodbye', }, CHAT_USER_DISABLED: { target: 'chatUserDisabled', }, }, }, offline: { meta: { ...OFFLINE_STATE, }, on: { ONLINE: { target: 'online', }, }, }, goodbye: { on: { ONLINE: { target: 'online', }, }, meta: { ...GOODBYE_STATE, }, after: { '300000': { target: 'offline', }, }, }, chatUserDisabled: { meta: { ...ONLINE_STATE, chatAvailable: false, }, }, }, }, serverFailure: { type: 'final', }, userfailure: { type: 'final', }, }, }); export default appStateModel;
06c87bb0bf452d911a373afedf04622a5d9af88b
TypeScript
amoungui/ecom-with-typeorm
/src/src/controllers/CheckoutController.ts
2.515625
3
import { Request, Response } from "express"; import Cart from "../entity/Cart"; import { Product } from "../entity/Product"; import session = require("express-session"); import * as Stripe from 'stripe'; class CheckoutController{ static getCheckout = async (req: Request, res: Response) => { var message = req.session.cart; if(!message){ res.status(200).json({ message: "Not product in your Cart", url: "http://localhost:3000/" }); } var cart = new Cart(message); res.status(200).json({ message: "Checkout your shopping cart", //products: cart.generateArray(), totalPrice: cart.totalPrice, buttonInfo: "Following the link to buy your commande with Stripe API", request: { type: "POST", BuyWithStripe: "http://localhost:3000/checkout/" } }); }; static checkout = async (req: Request, res: Response) =>{ var data = req.body; var message = req.session.cart; var token = null; //console.log(data); if(!message){ res.status(200).json({ message: "Not product in your Cart", url: "http://localhost:3000/" }); } var cart = new Cart(message); var stripe = require("stripe")("sk_test_ygWt2bASL7DDcGjNzcylg8Qr"); stripe.tokens.create({ card: { "number": data.number, "exp_month": data.exp_month, "exp_year": data.exp_year, "cvc": data.cvc } }, function(err, token) { res.status(201).json({ message: "Successfully bought product!", token: token }); }); // Create a new customer and then a new charge for that customer: stripe.customers .create({ email: 'foo-customer@example.com', }) .then((customer) => { return stripe.customers.createSource(customer.id, { source: 'tok_visa', }); }) .then((source) => { return stripe.charges.create({ amount: cart.totalPrice*100, currency: 'usd', customer: source.customer, }); }) .then((charge) => { // New charge created on a new customer }) .catch((err) => { // Deal with an error }); }; }; export default CheckoutController;
4085e19ff9fc287b7de4253ceb94b3cf444d4a52
TypeScript
paolotiu/crud-app-examples
/todo-graphql-typescript/backend/src/util/createVariablesString.ts
3.296875
3
export const createVariablesString = (arr: any[]) => { // Create the variables string // [1,5,3,9] => "$1,$2,$3,$4" let vars = ""; for (let i in arr) { const index = parseInt(i) + 1; if (index >= arr.length) { vars = vars + "$" + index; } else { vars = `${vars}$${index},`; } } return vars; };
1c01f99b5218acbd6f5cbb4fe16702f4c6b6a19c
TypeScript
JulienBergeon/gsb-nest
/src/doctor/doctor.controller.ts
2.96875
3
import { Controller, Get, Request, UseGuards } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; import { ApiResponse, ApiUseTags } from '@nestjs/swagger'; import { UserDtoConverter } from '../users/converter/userDto.converter'; import { UserDto } from '../users/model/user.dto'; import { User } from '../users/user.entity'; import { UsersService } from '../users/users.service'; /** * @swagger * @ApiUseTags annotation swagger pour indiquer que ces routes appartiennent au controller DoctorController * @ApiResponse annotation swagger pour indiquer la forme de la réponse */ @ApiUseTags('doctor') @Controller('doctor') export class DoctorController { /** * * @param userService service qui permet de faire toutes les opérations relatives à la table User * @param userDtoConverter service qui permet de convertir un User en UserDto (et inversement) */ constructor( private readonly userService: UsersService, private readonly userDtoConverter: UserDtoConverter ) {} /** * Méthode GET sur la route /api/doctor/patients * Cette route permet de récupérer tous les patients d'un médecin à partir de son token de connexion * * @UseGuards annotation qui permet d'ajouter un gardien à une route. * AuthGuard permet de créer un gardien d'authentification à partir d'une Strategy Nest, ici 'auth'. * (Celui définit par la stratégie jwt cf. /auth/strategy/jwt.strategy.ts) * * * @param req objet qui fait référence à la requête * On utilise cet objet parce qu'on a affecté un gardien d'authentification à cette route. * Ce gardien est un gardien issue de la stratégie JWT, il remonte dans la requête l'utilisateur correspondant au token. * Le champ req.user contient le retour de la méthode validate() définit dans /auth/strategy/jwt.strategy.ts * * @returns {UserDto[]} le tableau qui contient les patients du docteur connecté */ @UseGuards(AuthGuard('auth')) @Get('/patients') @ApiResponse({ status: 201, description: 'Doctor patients', type: UserDto, isArray: true}) @ApiResponse({ status: 401, description: 'User not authentificated'}) @ApiResponse({ status: 404, description: 'User not found'}) async addDoctor( @Request() req, ): Promise<UserDto[]> { //Récupère tous les patients d'un utilisateur à partir de son id const patients: User[] = await this.userService.getAllDoctorPatients(req.user.id); //On retourne le tableau de User convertis en tableau de UserDto return this.userDtoConverter.convertOutboundCollection(patients); } }
b78049fca7f425c1a4e3f1f3b4f21a5910f76d86
TypeScript
hrokhbakhsh/formgenerator
/src/app/form/show-form/show-form.component.ts
2.546875
3
import { Component, OnInit } from '@angular/core'; import {FormArray, FormBuilder, FormGroup} from "@angular/forms"; import {animate, state, style, transition, trigger} from "@angular/animations"; import {InputComponent} from "../input/input.component"; import {MatDialog} from "@angular/material/dialog"; export interface DialogData { animal: string; name: string; } interface JsonFormValidators { min?: number; max?: number; required?: boolean; requiredTrue?: boolean; email?: boolean; minLength?: boolean; maxLength: boolean; pattern?: string; nullValidators?: boolean; } interface JsonFormControlOptions { min?: number; max?: number; required?: boolean; step?: string; icon?: string } interface JsonFormControls { name: string; label: string; value: string; type: string; class: string; multi?: boolean data?: IList[]; options?: JsonFormControlOptions; required: boolean; validators: JsonFormValidators; } interface IList{ value: string; label: string } export interface JsonFormData { controls: JsonFormControls; } @Component({ selector: 'app-show-form', templateUrl: './show-form.component.html', styleUrls: ['./show-form.component.scss'], animations: [ trigger('fadein', [ state('in', style({ opacity: 1 })), transition('* => in', [ animate('1s') ]), ]) ] }) export class ShowFormComponent implements OnInit { form = this._fb.group({ name: [''], action: [''], controls: this._fb.array( [] ) }) openDialog(): void { const dialogRef = this.dialog.open(InputComponent, { width: '550px' }); dialogRef.afterClosed().subscribe(data => { this.addControl(data) }) } constructor(private _fb: FormBuilder , public dialog: MatDialog) { } get controls(): FormArray { return this.form.get('controls') as FormArray; } ngOnInit(): void { } submitted() { console.log(this.form.value); } newInput(data: any): FormGroup { return this._fb.group({ name: [data.name], label: [data.label], value: [data.value], type: [data.type], multi: [data.multi], class: [data.class], required: [data.required], validators: this._fb.group({ min: [data.validators.min], max: [data.validators.max], required: [data.validators.required], requiredTrue: [data.validators.requiredTrue], email: [data.validators.email], minLength: [data.validators.minLength], maxLength: [data.validators.maxLength], pattern: [data.validators.pattern], nullValidators: [data.validators.nullValidators] }) }) } addControl(data: any) { this.controls.push(this.newInput(data)); } }
220980b420e8d007fbbb6ade2944295e9129b200
TypeScript
linkinvo/nextjs-blog-main
/server/models/reviewsModel.ts
2.65625
3
import { Model, DataTypes, BuildOptions } from "sequelize"; import { IContextContainer } from "./../container"; interface IReviews extends Model { id: number; feedback: string; createdAt: BigInt; propertiId: number; userId: number; } export type ReviewsType = typeof Model & { new(values?: object, options?: BuildOptions): IReviews; initModel(): void; }; export default (ctx: IContextContainer) => { const ReviewsModel = <ReviewsType>ctx.db.define("reviews", { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: DataTypes.INTEGER }, feedback: { type: DataTypes.TEXT, allowNull: false }, userId: { type: DataTypes.INTEGER }, propertiId: { type: DataTypes.INTEGER }, createdAt: { allowNull: false, type: DataTypes.BIGINT }, updatedAt: { type: DataTypes.BIGINT, allowNull: false }, }); ReviewsModel.initModel = () => { ReviewsModel.belongsTo(ctx.PropertiModel, { foreignKey: 'propertiId', onDelete: 'CASCADE', }); ReviewsModel.belongsTo(ctx.UserModel, { foreignKey: 'userId', onDelete: 'CASCADE', }); } return ReviewsModel; };
405a9ada8d36a6c02ae23945a928c2a2e2fde185
TypeScript
Rakeshjayaraj/sample-code-house
/sample-code-house/src/app/house-list/house-list.component.ts
2.96875
3
import { Component, OnInit } from '@angular/core'; import { ApiService } from '../services/api.service'; import { House } from '../models/house'; @Component({ selector: 'app-house-list', templateUrl: './house-list.component.html', styleUrls: ['./house-list.component.css'] }) export class HouseListComponent implements OnInit { houseData: any; houseData_from_Eberswalder_stasse: Array<House>; houseData_with_more_than_five_rooms: Array<House>; houseData_without_complete_data: Array<House>; sorted_houseData_from_Eberswalder_stasse: Array<House>; sorted_houseData_with_more_than_five_rooms: Array<House>; sorted_houseData_without_complete_data: Array<House>; /** * constructor to init the varibales */ constructor( public apiService: ApiService ) { this.houseData = []; this.houseData_from_Eberswalder_stasse = []; this.houseData_with_more_than_five_rooms = []; this.houseData_without_complete_data = []; this.sorted_houseData_from_Eberswalder_stasse = []; this.sorted_houseData_with_more_than_five_rooms = []; this.sorted_houseData_without_complete_data = []; } ngOnInit() { this.getAllHouses(); } /** * This funtion get the list of houses depening upon conditions described below 1. a list of all the houses sorted according to their distance to your sisters home in Eberswalder Straße 55. Start w ith the house w ith the low est distance. 2. a list of houses w hich have more then 5 rooms. Start w ith the low est number of rooms. 3. a list of houses that you do not have all the data for. Sort them by the street-name. */ getAllHouses() { //Get saved list of houses this.apiService.getList().subscribe(response => { console.log(response); this.houseData = response; this.getAllHouses_from_Eberswalder_stasse(); this.getAllHouses_with_more_than_five_rooms(); this.sortHouseWithRooms(); this.getAllHouses_without_complete_data(); this.sortHouseWithoutData(); }) } /** * This Sorts the houses based on rooms */ private sortHouseWithRooms() { this.sorted_houseData_with_more_than_five_rooms = this.houseData_with_more_than_five_rooms.sort(function (a, b) { if (a.params.rooms < b.params.rooms) { return -1; } if (a.params.rooms > b.params.rooms) { return 1; } return 0; }); } /** * This Sorts the houses based on street Name */ private sortHouseWithoutData() { this.sorted_houseData_without_complete_data = this.houseData_without_complete_data.sort((a, b) => a.street.localeCompare(b.street)) } /** * This Sorts the houses based on distance from street Eberswalder Straße 55 */ getAllHouses_from_Eberswalder_stasse() { let { lang1, long1 } = this.get_base_langitude_and_longitude(); this.sorted_houseData_from_Eberswalder_stasse = Array<House>(this.houseData).sort(function (a, b) { let dist1: number = this.distance(lang1, long1, a.cordinate.latitude, a.cordinate.longitude); let dist2: number = this.distance(lang1, long1, b.cordinate.latitude, b.cordinate.longitude); if (dist1 < dist2) { return -1; } if (dist1 > dist2) { return 1; } return 0; }); } /** * This funtion calculates the distance between two langitudes and longitude */ private get_base_langitude_and_longitude() { let lang1: number = 0; let long1: number = 0; Array<House>(this.houseData).forEach(function (house) { let streetName: string = ""; if (house.street.toLowerCase().match("Eberswalder Straße 55")) { lang1 = house.cordinate.latitude; long1 = house.cordinate.longitude; } }); return { lang1, long1 }; } /** * This funtion calculates the distance of streets from Eberswalder Straße 55 */ getAllHouses_with_more_than_five_rooms() { //Get saved list of houses Array<House>(this.houseData).forEach(function (house) { if (house.params.rooms > 5 && house.params.value) { this.houseData_with_more_than_five_rooms.push(house); } }); } /** * This funtion checks for houses which has has missing data */ getAllHouses_without_complete_data() { //Get saved list of houses Array<House>(this.houseData).forEach(function (house) { if (!house.params.value) { this.houseData_without_complete_data.push(house); return; } if (!house.params.rooms) { this.houseData_without_complete_data.push(house); return; } if (!house.params.value) { this.houseData_without_complete_data.push(house); } }); } /** * This funtion calculates the distance between two given langitudes and longitude */ private distance(lat1: number, lon1: number, lat2: number, lon2: number) { if ((lat1 == lat2) && (lon1 == lon2)) { return 0; } else { let radlat1: any = Math.PI * lat1 / 180; var radlat2: any = Math.PI * lat2 / 180; let theta: any = lon1 - lon2; let radtheta: any = Math.PI * theta / 180; let dist: any = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta); if (dist > 1) { dist = 1; } dist = Math.acos(dist); dist = dist * 180 / Math.PI; dist = dist * 60 * 1.1515; dist = dist * 1.609344 return dist; } } }
2d078871fcf33bd42a71020f24131d88e585b0b1
TypeScript
bonejon/ngrx-sample
/src/app/store/cart/cart.spec.ts
2.546875
3
import { CartState, InitialCartState } from './cart.state'; import { CartItem } from 'src/app/common/models/cart-item'; import { AddItemToCartActionSuccess } from './cart.actions'; import { cartReducer } from './cart.reducer'; import * as cartActions from './cart.actions'; import { cold } from 'jasmine-marbles'; import { CartEffects } from './cart.effects'; import { TestColdObservable } from 'jasmine-marbles/src/test-observables'; describe('NGRX: cart state', () => { describe('actions', () => { it('should have correct type for AddItemToCartAction', () => { const action = new cartActions.AddItemToCartAction(new CartItem()); expect(action.type).toBe(cartActions.ADD_ITEM_TO_CART_ACTION); }); it('should have correct type for AddItemToCartActionSuccess', () => { const action = new cartActions.AddItemToCartActionSuccess(new CartItem()); expect(action.type).toBe(cartActions.ADD_ITEM_TO_CART_ACTION_SUCCESS); }); it('should have correct type for RemoveItemFromCartAction', () => { const action = new cartActions.RemoveItemFromCartAction(0); expect(action.type).toBe(cartActions.REMOVE_ITEM_FROM_CART_ACTION); }); it('should have correct type for RemoveItemFromCartActionSuccess', () => { const action = new cartActions.RemoveItemFromCartActionSuccess(0); expect(action.type).toBe(cartActions.REMOVE_ITEM_FROM_CART_ACTION_SUCCESS); }); it('should have correct type for ClearCartAction', () => { const action = new cartActions.ClearCartAction(); expect(action.type).toBe(cartActions.CLEAR_CART_ACTION); }); it('should have correct type for ClearCartActionSuccess', () => { const action = new cartActions.ClearCartActionSuccess(); expect(action.type).toBe(cartActions.CLEAR_CART_ACTION_SUCCESS); }); it('should have correct type for UpdateCartItemAction', () => { const action = new cartActions.UpdateCartItemAction(new cartActions.UpdateCartItemPayload(1, 2)); expect(action.type).toBe(cartActions.UPDATE_CART_ITEM_ACTION); }); it('should have correct type for UpdateCartItemActionSuccess', () => { const action = new cartActions.UpdateCartItemActionSuccess(new cartActions.UpdateCartItemPayload(1, 2)); expect(action.type).toBe(cartActions.UPDATE_CART_ITEM_ACTION_SUCCESS); }); }); describe('reducers', () => { it('Should add an item to the cart state', () => { const initialState: CartState = InitialCartState; const newItem: CartItem = new CartItem(); newItem.productId = 1; newItem.productName = 'Test'; newItem.quantity = 1; newItem.unitPrice = 2; const action = new AddItemToCartActionSuccess(newItem); const newState: CartState = cartReducer(initialState, action); expect(newState).toBeDefined(); expect(newState.items.length).toBe(1); expect(newState.items[0]).toBe(newItem); }); it('Should update the correct item in the cart state', () => { const item1: CartItem = new CartItem(); item1.productId = 1; item1.productName = 'One'; item1.quantity = 1; item1.unitPrice = 1; const item2: CartItem = new CartItem(); item2.productId = 2; item2.productName = 'Two'; item2.quantity = 2; item2.unitPrice = 2; const initialState: CartState = { items: [ item1, item2, ] }; const action = new cartActions.UpdateCartItemActionSuccess(new cartActions.UpdateCartItemPayload(item2.id, 10)); const newState: CartState = cartReducer(initialState, action); expect(newState).toBeDefined(); expect(newState).not.toBe(initialState); const updatedItem2: CartItem = newState.items.find(i => i.id === item2.id); expect(updatedItem2.quantity).toBe(10); }); it('Should remove the correct item in the cart state', () => { const item1: CartItem = new CartItem(); item1.productId = 1; item1.productName = 'One'; item1.quantity = 1; item1.unitPrice = 1; const item2: CartItem = new CartItem(); item2.productId = 2; item2.productName = 'Two'; item2.quantity = 2; item2.unitPrice = 2; const initialState: CartState = { items: [ item1, item2, ] }; const action = new cartActions.RemoveItemFromCartActionSuccess(item2.id); const newState: CartState = cartReducer(initialState, action); expect(newState).toBeDefined(); expect(newState).not.toBe(initialState); expect(newState.items.length).toBe(1); const updatedItem2: CartItem = newState.items.find(i => i.id === item2.id); expect(updatedItem2).toBeUndefined(); }); it('Should clear the cart state', () => { const item1: CartItem = new CartItem(); item1.productId = 1; item1.productName = 'One'; item1.quantity = 1; item1.unitPrice = 1; const item2: CartItem = new CartItem(); item2.productId = 2; item2.productName = 'Two'; item2.quantity = 2; item2.unitPrice = 2; const initialState: CartState = { items: [ item1, item2, ] }; const action = new cartActions.ClearCartActionSuccess(); const newState: CartState = cartReducer(initialState, action); expect(newState).toBeDefined(); expect(newState).not.toBe(initialState); expect(newState.items.length).toBe(0); }); }); describe('effects', () => { it('Should return the correct success action for AddItemToCart', () => { const payload: cartActions.AddItemToCartPayload = new cartActions.AddItemToCartPayload(1, 'Product1', 1, 2, 123); const addItemToCartAction: cartActions.AddItemToCartAction = new cartActions.AddItemToCartAction(payload); const result: CartItem = new CartItem(123); result.productId = 1; result.productName = 'Product1'; result.quantity = 1; result.unitPrice = 2; const source: TestColdObservable = cold('a', { a: addItemToCartAction }); const expected: TestColdObservable = cold('b', { b: new AddItemToCartActionSuccess(result) }); const effects: CartEffects = new CartEffects(source); expect(effects.addItemToCartAction$).toBeDefined(); expect(effects.addItemToCartAction$).toBeObservable(expected); }); it('Should return the correct success action from RemoveItemFromCart', () => { const removeItemFromCartAction: cartActions.RemoveItemFromCartAction = new cartActions.RemoveItemFromCartAction(123); const source: TestColdObservable = cold('a', { a: removeItemFromCartAction }); const expected: TestColdObservable = cold('b', { b: new cartActions.RemoveItemFromCartActionSuccess(123) }); const effects: CartEffects = new CartEffects(source); expect(effects.removeItemFromCartAction$).toBeDefined(); expect(effects.removeItemFromCartAction$).toBeObservable(expected); }); it('Should return the correct success action from ClearCart', () => { const clearCartAction: cartActions.ClearCartAction = new cartActions.ClearCartAction(); const source: TestColdObservable = cold('a', { a: clearCartAction }); const expected: TestColdObservable = cold('b', { b: new cartActions.ClearCartActionSuccess() }); const effects: CartEffects = new CartEffects(source); expect(effects.clearCartAction$).toBeDefined(); expect(effects.clearCartAction$).toBeObservable(expected); }); it('Should return the correct success action from UpdateCartItem', () => { const payload: cartActions.UpdateCartItemPayload = new cartActions.UpdateCartItemPayload(123, 45); const updateCartItemAction: cartActions.UpdateCartItemAction = new cartActions.UpdateCartItemAction(payload); const source: TestColdObservable = cold('a', { a: updateCartItemAction }); const expected: TestColdObservable = cold('b', { b: new cartActions.UpdateCartItemActionSuccess(payload) }); const effects: CartEffects = new CartEffects(source); expect(effects.updateCartItem$).toBeDefined(); expect(effects.updateCartItem$).toBeObservable(expected); }); }); });
78e691331892d72ecc4b7c9749105c096920ca85
TypeScript
SemajDraw/GradAcademy
/TypeScriptAndAngularProjects/TypeScriptProjects/TypeScriptSolutions/CleanCode/src/app/unique-words/unique-words.component.ts
3.0625
3
import {Component} from '@angular/core'; import {orderBy} from 'lodash'; import {HttpClient} from '@angular/common/http'; @Component({ selector: 'app-unique-words', templateUrl: './unique-words.component.html', styleUrls: ['./unique-words.component.css'] }) export class UniqueWordsComponent { input = ''; output = ''; constructor(private http: HttpClient) { this.initialiseSampleText(); } private initialiseSampleText() { this.http.get('assets/dickens.txt', {responseType: 'text'}) .subscribe(x => this.input = x); } // Output the unique words found in input with the number of times they occur. // Simply append to the string this.output to show the result // Lodash may be useful here - note it doesn't work with iterables execute() { const words = this.extractWords(this.input); const wordCounts = this.countWords(words); this.outputWordCounts(wordCounts); } private outputWordCounts(wordCounts: Map<string, number>) { const sortedWordCounts = orderBy([...wordCounts.entries()], ['1'], ['desc']); this.output += `Found ${sortedWordCounts.length} unique words\n`; for (const [word, count] of sortedWordCounts) { this.output += `${word} = ${count}\n`; } } private extractWords(input: string): string[] { return input.split(/[^a-zA-Z']+/) .map(x => x.toLowerCase().trim()) .filter(x => x); } private countWords(words): Map<string, number> { const map = new Map<string, number>(); words.forEach(word => this.addToWordCount(map, word)); return map; } private addToWordCount(map: Map<string, number>, word: string) { const currentcount = map.get(word) || 0; map.set(word, currentcount + 1); } }
b68a655b01574d326933dba08543f958d9c51bfc
TypeScript
johannes85/prowljs
/src/test/ts/prowl/ProwlTest.ts
2.640625
3
import * as Mocha from 'mocha'; import * as assert from 'assert'; import * as nock from 'nock'; import Prowl from '../../../main/ts/prowl/Prowl'; describe('Prowl', () => { let p: Prowl; let successAnswer: string = '<?xml version="1.0" encoding="UTF-8"?><prowl><success code="200" remaining="123" resetdate="456789"/></prowl>'; let successRetrieveTokenAnswer: string = '<?xml version="1.0" encoding="UTF-8"?><prowl><success code="200" remaining="123" resetdate="456789"/><retrieve token="TOKEN" url="URL" /></prowl>'; let successRetrieveApikeyAnswer: string = '<?xml version="1.0" encoding="UTF-8"?><prowl><success code="200" remaining="123" resetdate="456789"/><retrieve apikey="APIKEY" /></prowl>'; let invalidApikeyAnswer: string = '<?xml version="1.0" encoding="UTF-8"?><prowl><error code="401">Invalid apikey</error></prowl>'; before(() => { p = new Prowl(); }) describe('constructor', () => { it('should set the api endpoint', () => { let p = new Prowl('https://www.foo.bar'); assert.equal(p.getApiEndpoint(), 'https://www.foo.bar'); }); it('should set the default api endpoint if not set', () => { let p = new Prowl(); assert.equal(p.getApiEndpoint(), 'https://api.prowlapp.com/publicapi'); }); }); describe('verify', () => { it('should build correct get request and parse answer', async () => { nock(p.getApiEndpoint()) .get(/verify/) .reply((uri, requestBody) => { assert.equal(uri, '/publicapi/verify?apikey=valid'); return [200, successAnswer]; }); let res = await p.verify('valid'); assert.equal(res.valid, true); assert.equal(res.remainingCalls, 123); assert.equal(res.remainingCallsResetDate, 456789); }); it('should return valid=false for an invalid apikey', async () => { nock(p.getApiEndpoint()) .get(/verify/) .reply(401, invalidApikeyAnswer); let res = await p.verify('invalid'); assert.equal(res.valid, false); }); }); describe('add', () => { it('should build correct post request and parse answer', async () => { nock(p.getApiEndpoint()) .post(/add/) .reply((uri, requestBody) => { assert.equal(uri, '/publicapi/add'); assert.equal(requestBody, 'apikey=valid&application=TestApp&event=Test&description=Test%20App%20Description'); return [200, successAnswer]; }); let res = await p.add({ apiKey: 'valid', application: 'TestApp', event: 'Test', description: 'Test App Description' }); assert.equal(res.remainingCalls, 123); assert.equal(res.remainingCallsResetDate, 456789); }); }); describe('retrieveToken', () => { it('should build correct post request and parse answer', async () => { nock(p.getApiEndpoint()) .get(/retrieve\/token/) .reply((uri, requestBody) => { assert.equal(uri, '/publicapi/retrieve/token?providerkey=provider_key'); return [200, successRetrieveTokenAnswer]; }); let res = await p.retrieveToken('provider_key'); assert.equal(res.token, 'TOKEN'); assert.equal(res.url, 'URL'); assert.equal(res.remainingCalls, 123); assert.equal(res.remainingCallsResetDate, 456789); }); }); describe('retrieveApikey', () => { it('should build correct post request and parse answer', async () => { nock(p.getApiEndpoint()) .get(/retrieve\/apikey/) .reply((uri, requestBody) => { assert.equal(uri, '/publicapi/retrieve/apikey?providerkey=provider_key&token=token'); return [200, successRetrieveApikeyAnswer]; }); let res = await p.retrieveApikey('provider_key', 'token'); assert.equal(res.apikey, 'APIKEY'); assert.equal(res.remainingCalls, 123); assert.equal(res.remainingCallsResetDate, 456789); }); }); });
5a61e8d947060c95bb6210e144b2071eef4ee609
TypeScript
wthapps/portal-frontend
/src/shared/shared/pipe/phone-to-flag.pipe.ts
2.671875
3
import { Pipe, PipeTransform } from '@angular/core'; declare var _: any; @Pipe({ name: 'phoneCodeCountries' }) export class PhoneCodeCountriesPipe implements PipeTransform { transform(key: any, data: any): any { if (key) { const phoneName = key.split(' (+'); const phoneCode = _.find(data, ['name', phoneName[0]]); return ( '<div class="clearfix">' + `<img class=\"pull-left\" width='30' src='assets/images/flags/` + phoneCode.code.toLowerCase() + `.svg' alt=''>` + '<span class="pull-left">' + phoneCode.name + '</span>' + '<span class="pull-right">' + '(' + phoneCode.dial_code + ')' + '</span>' + '</div>' ); } } } /** * <img *ngIf="countriesCode" src="assets/images/flags/{{item.country_alpha_code | phoneCodeFlag:countriesCode}}.svg"> */ @Pipe({ name: 'phoneCodeFlag' }) export class PhoneCodeFlagPipe implements PipeTransform { transform(key: any, data: any): any { if (data) { if (key) { const phoneName = key.split(' (+'); const phoneCode = _.find(data, ['name', phoneName[0]]); if (phoneCode && phoneCode.code) { return phoneCode.code.toLowerCase(); } return null; } } } } @Pipe({ name: 'phoneDialCode' }) export class PhoneDialCodePipe implements PipeTransform { transform(key: any): string { if (key) { return `(+${key.split(' (+')[1]}`; } else { return ''; } } } const PHONE_CODE_REGEX = /\([^\)]*\)/; // Aghanistan (+83) => +83 @Pipe({ name: 'phoneCodeOnlyFlag' }) export class PhoneCodeOnlyFlagPipe implements PipeTransform { transform(key: any): any { if (!key) return ''; const matches = key.match(PHONE_CODE_REGEX); return matches ? matches[0] : ''; } } @Pipe({ name: 'phoneCodeToDisplayCode' }) export class PhoneCodeToDisplayCodePipe implements PipeTransform { transform(key: any, data: any): any { const phoneCode = _.find(data, ['code', key.toUpperCase()]); return ( '<div class="clearfix">' + "<img class=\"pull-left\" width='30' src='assets/images/flags/" + phoneCode.code.toLowerCase() + ".svg' alt=''>" + '<span class="pull-left">' + phoneCode.name + '</span>' + '<span class="pull-right">' + '(' + phoneCode.dial_code + ')' + '</span>' + '</div>' ); } }
e52db0baa732f60494ba224918cefb770ca92d0c
TypeScript
mihajlo202/RWAProject_Angular_NgRx
/src/app/models/JobEmployed.ts
2.703125
3
export interface IJobEmployed { id:number; jobId:number; workerId:number; } export class JobEmployed implements IJobEmployed{ id:number; jobId:number; workerId:number; constructor(jobId, workerId) { this.jobId = jobId; this.workerId = workerId; } }
00ea183af48ec8fc7662ea7b60db94fa8f18fece
TypeScript
Eoyo/read-key
/src/libs/state-machine.ts
3.359375
3
export function match(matcher: RegExp | string[] | string, key: string) { if (Array.isArray(matcher)) { return matcher.includes(key); } else if (typeof matcher === "string") { return matcher == key; } else if (matcher instanceof RegExp) { return matcher.test(key); } else { return matcher === key; } } /** * 构造一个队字符进行分词的状态机 * @param defaultInitState 默认的状态机的状态 * @param createState 状态图的构建, 以及关键运行节点的返回值 */ export function TokenStateMachine<S extends string, Tokens>( defaultInitState: S, stateSwitch: ( tokens: Tokens[] ) => { [x in S]: { lastState: S[] | RegExp; currentKey: string | RegExp; action?: (data: { currentKey: string; lastState: S }) => void | S; } } ): (code: string, initState?: S) => Tokens[] { return (code, initState = defaultInitState) => { const tokens: Tokens[] = []; const state = stateSwitch(tokens); // 解构成表格 const Values = Object.keys(state).map((stateName) => { return { state: stateName as S, value: state[stateName as S], }; }); let currentState = initState; for (const c of code) { const foundNode = Values.find(node => { return ( match(node.value.currentKey, c) && match(node.value.lastState, currentState) ); }); if (foundNode) { // 触发匹配的节点的 actions; if (foundNode.value.action) { currentState = foundNode.value.action({ currentKey: c, lastState: currentState, }) || foundNode.state; } else { currentState = foundNode.state; } } } return tokens; }; }
23e18316d7ed7afacb8b744f8e0e20f22e096330
TypeScript
thekevinscott/UpscalerJS
/test/integration/utils/catchFailures.ts
2.53125
3
export function catchFailures<T extends unknown[]>() { return ( _1: unknown, _2: string | symbol, descriptor: PropertyDescriptor ) => { const origFn = descriptor.value; descriptor.value = async function (...args: T) { try { return await origFn.apply(this, args); } catch (err) { console.error(err); process.exit(1); } }; return descriptor; }; }
4a9c0a9ec63caea6e812098d68855bfd237e777f
TypeScript
jayeshyadav89/Angular2
/demo_proj/Routing/app.department.details.component.ts
2.515625
3
import {Component, OnInit} from "@angular/core"; import {ActivatedRoute, Params, Router} from "@angular/router"; @Component({ template : `You have selected department : {{departmentId}}<br/> <a (click)="goPrevious()">Previous</a> <a (click)="goNext()">Next</a> <p> <button (click)="gotoDepartment()">Back</button> </p>` }) export class DepartmentDetailsComponent implements OnInit{ departmentId:number; constructor(private routes:ActivatedRoute, private router:Router){}; ngOnInit(){ this.routes.params.subscribe((params:Params) => { this.departmentId = parseInt(params['id']); }) } goPrevious(){ let prev_dept_id = this.departmentId - 1; this.router.navigate(['dept_list', prev_dept_id]); } goNext(){ let next_dept_id = this.departmentId + 1; this.router.navigate(['dept_list', next_dept_id]); } gotoDepartment(){ this.router.navigate(['/dept_list', {id:this.departmentId}]); } }
fea91aebcf95c6236fdb100a9bb549c0993c262b
TypeScript
tinymce/tinymce
/modules/bridge/src/main/ts/ephox/bridge/components/menu/SeparatorMenuItem.ts
2.515625
3
import { StructureSchema } from '@ephox/boulder'; import { Optional, Result } from '@ephox/katamari'; import * as ComponentSchema from '../../core/ComponentSchema'; export interface SeparatorMenuItemSpec { type?: 'separator'; text?: string; } // tslint:disable-next-line:no-empty-interface export interface SeparatorMenuItemInstanceApi { } export interface SeparatorMenuItem { type: 'separator'; text: Optional<string>; } export const separatorMenuItemSchema = StructureSchema.objOf([ ComponentSchema.type, ComponentSchema.optionalText ]); export const createSeparatorMenuItem = (spec: SeparatorMenuItemSpec): Result<SeparatorMenuItem, StructureSchema.SchemaError<any>> => StructureSchema.asRaw('separatormenuitem', separatorMenuItemSchema, spec);
f8379348df16c4195603d0db9adc7718807fc815
TypeScript
ky0yk/ohakuma-api
/test/lambda/dynamodb-bear-management-table.test.ts
2.640625
3
import * as infra from '../../src/lambda/infrastructures/dynamodb/dynamodb-bear-management-table'; import { mockClient } from 'aws-sdk-client-mock'; import * as ddbLib from '@aws-sdk/lib-dynamodb'; import { Bear } from '../../src/lambda/domains/bear-management/bear-management'; import { v4 as uuidv4 } from 'uuid'; const tableName = process.env.TABLE_NAME; const ddbMock = mockClient(infra.ddbDocClient); /** * 【担保できていること】 * ドメイン層の関数の戻り値が想定通りであること * AWS SDKに渡されるパラメータが正しいこと */ describe('インフラ', () => { beforeEach(() => { ddbMock.reset(); }); test('全クマ情報の取得ができること', async () => { const expectedItems: Bear[] = [ { id: uuidv4(), name: 'ヒグマ', info: 'ヒトはヒグマに勝てねえ' }, { id: uuidv4(), name: 'シロクマ', info: '白いクマです' }, ]; ddbMock .on(ddbLib.ScanCommand, { TableName: tableName, }) .resolves({ Items: expectedItems, }); const res: Bear[] = await infra.getAllBears(); console.log(ddbMock.calls.length); expect(res).toStrictEqual(expectedItems); }); test('IDに対応するクマ情報の取得ができること', async () => { const inputId = uuidv4(); const expectedItem: Bear = { id: inputId, name: 'ヒグマ', info: 'ヒトはヒグマに勝てねえ', }; ddbMock .on(ddbLib.GetCommand, { TableName: tableName, Key: { id: inputId }, }) .resolves({ Item: expectedItem, }); const res: Bear = await infra.getBear(inputId); console.log(res); expect(res).toStrictEqual(expectedItem); }); test('クマ情報の作成ができること', async () => { const inputItem = { id: uuidv4(), name: 'ヒグマ', info: 'ヒトはヒグマに勝てねえ', }; ddbMock .on(ddbLib.PutCommand, { TableName: tableName, Item: inputItem, }) .resolves({ Attributes: inputItem, }); const res: Bear = await infra.createBear(inputItem); console.log(res); expect(res).toStrictEqual(inputItem); }); test('IDに対応するクマ情報の更新ができること', async () => { const inputId = uuidv4(); const inputItem = { name: 'パンダ', info: '大熊猫' }; const expectedItem = { id: inputId, name: 'パンダ', info: '大熊猫' }; ddbMock .on(ddbLib.UpdateCommand, { TableName: tableName, Key: { id: inputId }, UpdateExpression: 'set #att_name =:name,#att_info =:info', ExpressionAttributeNames: { '#att_name': 'name', '#att_info': 'info' }, ExpressionAttributeValues: { ':name': 'パンダ', ':info': '大熊猫' }, ReturnValues: 'ALL_NEW', }) .resolves({ Attributes: expectedItem, }); const res: Bear = await infra.updateBear(inputId, inputItem); console.log(res); expect(res).toStrictEqual(expectedItem); }); test('IDに対応するクマ情報の削除ができること', async () => { const inputId = uuidv4(); const expectedItem = { id: inputId, name: 'グリズリー', info: '灰色熊' }; ddbMock .on(ddbLib.DeleteCommand, { TableName: tableName, Key: { id: inputId, }, ReturnValues: 'ALL_OLD', }) .resolves({ Attributes: expectedItem, }); const res: Bear = await infra.deleteBear(inputId); console.log(res); expect(res).toStrictEqual(expectedItem); }); });
faa44821e7ae069e518462f2a3bf380c4fc77707
TypeScript
Brenont/site
/src/_mocks/SelectiveProcess.mock.ts
2.578125
3
export interface ISelectiveProcessItem { title: string; description: string; } export const selectiveProcessMock: ISelectiveProcessItem[] = [ { title: "TESTE DE CLASSIFICAÇÃO", description: "Uma prova de raciocínio lógico. Simples e objetiva. Funciona como uma classificação de acordo com o número de vagas.", }, { title: "HACKATHON", description: "Como você trabalha em equipe? Além de conhecermos melhor suas habilidades, você já se prepara para as ferramentas que serão usadas ao longo do curso.", }, { title: "BATE-PAPO COM O TIME", description: "Aqui a gente se conhece melhor e seleciona os candidatos que se encaixam melhor com o nosso perfil.", }, ];
60db4b7069cdcc7f14b18d53b72b9fd9b18e7619
TypeScript
Svreber/ludos
/backend/src/modules/language/domain/language.output.ts
2.609375
3
import { Field, ID, ObjectType } from 'type-graphql'; @ObjectType() export class LanguageOutput { private _type = 'output'; @Field(type => ID) id?: number; @Field() name?: string; @Field() nameEnglish?: string; @Field() nameAlpha3?: string; }
fb165c3445255ad568ccf7f7cb959324f1ca7f83
TypeScript
Lagunskij/Lagunskij
/src/store/todolists-reducer.test.ts
2.953125
3
import { ActionType, AddTodoListAC, ChangeTodoListFilterAC, ChangeTodoListTitleAC, RemoveTodoListAC, todolistsReducer } from './todolists-reducer'; import {v1} from 'uuid'; import {FilterValuesType, TodoListType} from '../App'; let todolistID1:string; let todolistID2: string; let startState: Array<TodoListType> beforeEach(() => { todolistID1 = v1(); todolistID2 = v1(); startState = [ {id: todolistID1, title: "What to learn", filter: "all"}, {id: todolistID2, title: "What to buy", filter: "all"} ] }) test('correct todolist should be removed', () => { const endState = todolistsReducer(startState, RemoveTodoListAC(todolistID1)) expect(endState.length).toBe(1); expect(endState[0].id).toBe(todolistID2); }); test('correct todolist should be add TODOLIST', () => { let newTodo = "What to drink" const endState = todolistsReducer(startState, AddTodoListAC(newTodo)) expect(endState.length).toBe(3); expect(endState[0].title).toBe("What to drink"); }); test('correct todolist should change its name', () => { let newTodolistTitle = "New Todolist"; const action: ActionType = ChangeTodoListTitleAC(newTodolistTitle, todolistID2); const endState = todolistsReducer(startState, action); expect(endState[0].title).toBe("What to learn"); expect(endState[1].title).toBe(newTodolistTitle); }); test('correct todolist should be change filter', () => { let newFilter: FilterValuesType = "completed"; const action = ChangeTodoListFilterAC(todolistID1, newFilter) const endState = todolistsReducer(startState, action) expect(endState[0].filter).toBe("completed"); expect(endState[1].filter).toBe('all'); });
6ff0705d1209a5bfa73fe672404cdbd788dff384
TypeScript
ilomon10/solar-power-monitor
/functions/src/addData.ts
2.515625
3
import { https, Response, config } from 'firebase-functions'; import db from './db'; export interface IData { device: string; powerIn: number; powerOut: number; voltageIn: number; voltageOut: number; currentIn: number; currentOut: number; temperature: number; timestamp: number; } export const handler = (req: https.Request, res: Response) => { if (req.get('content-type') !== 'application/json') { res.status(400).send('Bad request'); return; } if (req.get('x-very-secret') !== config().very.secret) { console.log("Bad"); res.status(400).send('Bad key'); return; } const body = req.body; const data: IData = { ...body, powerIn: body.currentIn * body.voltageIn, powerOut: body.currentOut * body.voltageOut, timestamp: db.ServerValue.TIMESTAMP }; const key = db().ref('/data-lake').push(data).key; res.status(200).send(key); }
d93a00ca9d8419eb6e5e7df53b59468b1daca359
TypeScript
tom-sherman/smart-home
/services/device-registry-service/src/schema/registering.ts
2.609375
3
import { arg, inputObjectType, list, mutationField, nonNull, objectType, } from 'nexus'; import { v4 as uuid } from 'uuid'; import { NexusGenInputs } from '../generated/nexus-typegen'; import { Capability, EnumCapability, NumericCapability } from '../sourceTypes'; import { Device, Access } from './schema'; function mapInputDevice(device: NexusGenInputs['CreateDeviceInputDevice']) { const id = uuid(); return { ...device, id, description: device.description ?? null, name: device.name ?? id, powerSource: device.powerSource ?? null, exposes: { type: 'unknown', capabilities: [], }, }; } export const CreateDeviceInputDevice = inputObjectType({ name: 'CreateDeviceInputDevice', definition(t) { t.string('description'); t.string('name'); t.string('powerSource'); t.field('capabilities', { type: list(nonNull(CapabilityInputObject)), }); }, }); export const CreateDeviceInput = inputObjectType({ name: 'CreateDeviceInput', definition(t) { t.nonNull.field('device', { type: CreateDeviceInputDevice, }); t.nonNull.string('controller'); }, }); export const createDevice = mutationField('registerDevice', { type: 'Device', description: 'Register a new device or re-register (override) an existing one', args: { input: arg({ type: nonNull(CreateDeviceInput), }), }, resolve: async (_source, { input: { device, controller } }, context) => { const resolvedDevice = { ...mapInputDevice(device), controller, capabilities: [], }; await context.store.createOrUpdateDevices([ { id: resolvedDevice.id, device: resolvedDevice, }, ]); return resolvedDevice; }, }); export const CreateManyDevicesInput = inputObjectType({ name: 'CreateManyDevicesInput', definition(t) { t.nonNull.field('devices', { type: list(nonNull(CreateDeviceInputDevice)), }); t.nonNull.string('controller'); }, }); const capabilityInputObjectKeyLookup = { binary: 'BinaryCapability', numeric: 'NumericCapability', enum: 'EnumCapability', } as Record<string, Capability['__typename']>; type CapabilityInput = Exclude< NexusGenInputs['CapabilityInputObject'][keyof NexusGenInputs['CapabilityInputObject']], null | undefined >; function mapInputCapability( type: string, inputCapability: CapabilityInput ): Capability { const typeName = capabilityInputObjectKeyLookup[type]; if (!typeName) { throw new Error(`Unimplemented capability type "${type}"`); } const description = inputCapability.description ?? ''; // TODO: Casting to eg NumericCapability is technically incorrect because that casts to the resolved/stored capability // type when we are actually working on the input type here. The input type can have a slightly different shape. switch (typeName) { case 'BinaryCapability': { return { __typename: typeName, ...inputCapability, description, }; } case 'NumericCapability': { return { __typename: typeName, ...inputCapability, description, max: (inputCapability as NumericCapability).max ?? null, min: (inputCapability as NumericCapability).min ?? null, unit: (inputCapability as NumericCapability).unit ?? null, }; } case 'EnumCapability': { return { __typename: typeName, ...inputCapability, description, values: (inputCapability as EnumCapability).values ?? [], }; } } } export const registerManyDevices = mutationField('registerManyDevices', { type: list(Device), args: { input: arg({ type: nonNull(CreateManyDevicesInput), }), }, resolve: async (_source, { input: { devices, controller } }, context) => { const resolvedDevices = devices.map((device) => ({ ...mapInputDevice(device), controller, capabilities: device.capabilities?.flatMap((capability) => { const deviceCapabilities: Capability[] = []; for (const [type, inputCapability] of Object.entries(capability)) { if (!inputCapability) { continue; } deviceCapabilities.push(mapInputCapability(type, inputCapability)); } return deviceCapabilities; }) ?? [], })); await context.store.createOrUpdateDevices( resolvedDevices.map((device) => ({ id: device.id, device, })) ); return resolvedDevices; }, }); export const UnregisterDeviceInputDevice = inputObjectType({ name: 'UnregisterDeviceInputDevice', definition(t) { t.nonNull.id('id'); }, }); export const UnregisterManyDevicesInput = inputObjectType({ name: 'UnregisterManyDevicesInput', definition(t) { t.nonNull.field('devices', { type: list(nonNull(UnregisterDeviceInputDevice)), }); }, }); export const UnregisterManyDevicesResult = objectType({ name: 'UnregisterManyDevicesResult', definition(t) { t.nonNull.list.string('deletedDeviceIds'); }, }); export const unregisterManyDevices = mutationField('unregisterManyDevices', { type: UnregisterManyDevicesResult, args: { input: arg({ type: nonNull(UnregisterManyDevicesInput), }), }, resolve: async (_source, { input: { devices } }, context) => { const ids = devices.map((device) => device.id); await context.store.removeDevices(ids); return { deletedDeviceIds: ids, }; }, }); const UnregisterAllDevicesForControllerInput = inputObjectType({ name: 'UnregisterAllDevicesForControllerInput', definition(t) { t.nonNull.string('controller'); }, }); export const unregisterAllDevicesForController = mutationField( 'unregisterAllDevicesForController', { type: UnregisterManyDevicesResult, args: { input: arg({ type: nonNull(UnregisterAllDevicesForControllerInput), }), }, resolve: async (_source, { input: { controller } }, context) => { const devices = await context.store.getAllDevicesForController( controller ); const ids = devices.map((device) => device.id); await context.store.removeDevices(ids); return { deletedDeviceIds: ids, }; }, } ); // This is a workaround for graphql not having union input types. export const CapabilityInputObject = inputObjectType({ name: 'CapabilityInputObject', description: ` This is basically a workaround for GraphQL not having input unions. Ideally we would describe this type as BinaryCapabilityInput | NumericCapabilityInput, instead we define an object with an optional key for each capability type. This accomplishes the same thing as a union here because a device can have more than one capability, and more than one capability of the same type. `, definition(t) { t.field('binary', { type: BinaryCapabilityInput, }); t.field('numeric', { type: NumericCapabilityInput, }); t.field('enum', { type: EnumCapabilityInput, }); }, }); export const BinaryCapabilityInput = inputObjectType({ name: 'BinaryCapabilityInput', definition(t) { t.nonNull.string('property'); t.string('description'); t.nonNull.field('access', { type: Access, }); }, }); export const NumericCapabilityInput = inputObjectType({ name: 'NumericCapabilityInput', definition(t) { t.nonNull.string('property'); t.string('description'); t.nonNull.field('access', { type: Access, }); t.float('min'); t.float('max'); t.string('unit'); }, }); export const EnumCapabilityInput = inputObjectType({ name: 'EnumCapabilityInput', definition(t) { t.nonNull.string('property'); t.string('description'); t.nonNull.field('access', { type: Access, }); t.list.nonNull.string('values'); }, });
affc2ed40ccf47d80073bf7a87f1ca5680677fae
TypeScript
ffalt/jamserve
/src/modules/rest/builder/express-path-parameters.ts
2.8125
3
import {CustomPathParameterGroup, CustomPathParameters} from '../definitions/types'; import {MethodMetadata} from '../definitions/method-metadata'; import {InvalidParamError, MissingParamError} from './express-error'; import {getMetadataStorage} from '../metadata'; function validateCustomPathParameterValue(rElement: string | undefined, group: CustomPathParameterGroup): any { const type = group.getType(); let value: string = rElement || ''; if (group.prefix) { value = value.replace(group.prefix, '').trim(); } if (value.length === 0) { throw MissingParamError(group.name); } if (type === String) { return value; } else if (type === Boolean) { return Boolean(value); } else if (type === Number) { const number = Number(value); if (isNaN(number)) { throw InvalidParamError(group.name, 'is not a number'); } if ((group.min !== undefined && number < group.min) || (group.max !== undefined && number > group.max)) { throw InvalidParamError(group.name, 'number not in allowed range'); } return number; } else { const enumInfo = getMetadataStorage().enums.find(e => e.enumObj === type); if (enumInfo) { const enumObj: any = enumInfo.enumObj; if (!enumObj[value]) { throw InvalidParamError(group.name, `Enum value not valid`); } return value; } throw new Error('Internal: Invalid Custom Path Parameter Type ' + group.name); } } export function processCustomPathParameters(customPathParameters: CustomPathParameters, pathParameters: string, method: MethodMetadata): any { const r = customPathParameters.regex.exec(pathParameters) || []; let index = 1; const result: any = {}; const route = '/' + customPathParameters.groups.filter((g, index) => r[index + 1]).map(g => `${g.prefix || ''}{${g.name}}`).join(''); const alias = (method.aliasRoutes || []).find(a => a.route === route); for (const group of customPathParameters.groups) { if (!alias || !alias.hideParameters.includes(group.name)) { result[group.name] = validateCustomPathParameterValue(r[index], group); } index++; } return result; }
081f8dea76a4a9b2e13afa66f91a27fcedb7e55f
TypeScript
simonjamesrowe/react-ui
/src/state/socialMedia/Reducer.ts
2.59375
3
import { Reducer } from "redux"; import { ISocialMediaState} from "../Store"; import { SocialMediaActions, SocialMediaActionTypes} from "./Actions"; const initialSocialMediaState: ISocialMediaState = { loading: false, socialMedias: [] }; export const socialMediaReducer: Reducer<ISocialMediaState, SocialMediaActions> = ( state = initialSocialMediaState, action ) => { switch (action.type) { case SocialMediaActionTypes.GETALL: { return { socialMedias : action.socialMedias, loading: false }; } } return state; };
af9626175e35ab50f0f40dceab4008e03c15406d
TypeScript
woutervh-/taskdist
/src/shared/messages/master-to-worker.d.ts
2.625
3
export interface TaskMessage<Task> { type: 'task'; key: string; task: Task; } export type MasterMessage<Task> = TaskMessage<Task>;
4b96f545483cb9b03b4b8185c83aa8e96b5794db
TypeScript
uxland/uxl-test-release
/test/unit/invariant-fixture.ts
3.328125
3
import {invariant} from '../../src/invariant'; import {assert, expect} from 'chai'; import * as sinon from 'sinon'; suite('when invoking `invariant` method', () => { suite('and a value is passed as first argument', () => { test('should return undefined if first argument is truthy', () => { assert.isUndefined(invariant(true)); assert.isUndefined(invariant(1)); assert.isUndefined(invariant({})); }); test('should raise exception if first argument is falsy', () => { assert.throws(() => invariant(false)); assert.throws(() => invariant(0)); assert.throws(() => invariant('')); assert.throws(() => invariant(null)); assert.throws(() => invariant(undefined)); assert.throws(() => invariant(NaN)); }); test('should set exception message if first argument is false if second argument is supplied', () => { expect(() => invariant(false, 'condition false')).to.throw(Error).that.has.property('message').eq('condition false'); expect(() => invariant(0, 'condition 0')).to.throw(Error).that.has.property('message').eq('condition 0'); expect(() => invariant('', 'condition empty string')).to.throw(Error).that.has.property('message').eq('condition empty string'); expect(() => invariant(null, 'condition null')).to.throw(Error).that.has.property('message').eq('condition null'); expect(() => invariant(undefined, 'condition undefined')).to.throw(Error).that.has.property('message').eq('condition undefined'); expect(() => invariant(NaN, 'condition NaN')).to.throw(Error).that.has.property('message').eq('condition NaN'); }); }); suite('and a function is passed as first argument', () => { test('should invoke function', () => { let stub = sinon.stub(); try { invariant(stub); } catch (e) { } assert.isTrue(stub.calledOnceWith()); }); test('should raise error if function returns falsy', () => { let stub = sinon.stub().onFirstCall().returns(false).onSecondCall().returns(0).onThirdCall().returns('') .onCall(4).returns(null).onCall(5).returns(undefined).onCall(6).returns(NaN); assert.throws(() => invariant(stub)); assert.throws(() => invariant(stub)); assert.throws(() => invariant(stub)); assert.throws(() => invariant(stub)); assert.throws(() => invariant(stub)); assert.throws(() => invariant(stub)); assert.equal(stub.callCount, 6); }); test('should set exception message if function returns falsy and a second parameter is supplied', () => { expect(() => invariant(() => false, 'condition false')).to.throw(Error).that.has.property('message').eq('condition false'); expect(() => invariant(() => 0, 'condition 0')).to.throw(Error).that.has.property('message').eq('condition 0'); expect(() => invariant(() => '', 'condition empty string')).to.throw(Error).that.has.property('message').eq('condition empty string'); expect(() => invariant(() => null, 'condition null')).to.throw(Error).that.has.property('message').eq('condition null'); expect(() => invariant(()=> undefined, 'condition undefined')).to.throw(Error).that.has.property('message').eq('condition undefined'); expect(() => invariant(() => NaN, 'condition NaN')).to.throw(Error).that.has.property('message').eq('condition NaN'); }); test('should return undefined is function returns truthy', () => { const obj = {}; const func = function(){}; assert.isUndefined(invariant(() => true)); assert.isUndefined(invariant(() => 1)); assert.isUndefined(invariant(() => 'a')); assert.isUndefined(invariant(() => obj)); assert.isUndefined(invariant(() => [])); assert.isUndefined(invariant(() => func)); }); }); });
8b641ad706e6ebab1a181ce37d8e48ad4c41b28e
TypeScript
Skidush/webui-Talos
/e2e/utils/element.utils.ts
2.9375
3
import { browser, ElementFinder, ElementArrayFinder } from "protractor"; import { ElementCommand, ElementCommandCycle, SelectorParameter } from '../helpers/helper.exports'; export class ElementUtil { /** * Checks if the timeout for retrying has been exhausted. * Throws an error and resets the global timeout when exhausted. * * @param timeout the time window in melliseconds for the execution of the command * @param elementSelector the selector of the element * @param action the command to the element being executed. See `ElementCommand` for options * @param commandCycle the command cycle used to retrieve the element. See `ElementCommandCycle` for options * @throws An error relative to the action executed */ static checkTimeout(timeout: number, elementSelector: string, command: ElementCommand, commandCycle: ElementCommandCycle) { if (timeout < 0) { const timeinSec = browser.params.originalTime / 1000; let message = commandCycle === ElementCommandCycle.RETRY ? `After ${timeinSec} seconds of retrying` : `Timed out after ${timeinSec} seconds.`; try { switch (command) { case ElementCommand.CLICK: message = `${message}, the element ${elementSelector} was not clicked.`; break; case ElementCommand.GET_ATTRIBUTE: message = `${message}, the attribute value for the element ${elementSelector} was not extracted.`; break; case ElementCommand.GET_TEXT: message = `${message}, the text for the element ${elementSelector} was not extracted.`; break; case ElementCommand.CLEAR: message = `${message}, the element ${elementSelector} was not cleared.`; break; case ElementCommand.SEND_KEYS: message = `${message}, the keys sent to the the element ${elementSelector} were not received.`; break; case ElementCommand.CHECK_DISPLAY: message = `${message}, the element ${elementSelector} was not displayed.`; break; case ElementCommand.CHECK_PRESENCE: message = `No element found ${elementSelector}. ${message}`; break; } throw message; } finally { browser.params.originalTime = 0; } } } static buildSelector(selectorWithParam: string, newString: string) { // type with regexp is not yet implemented by typescript, so do a check for (const param in SelectorParameter) { if (selectorWithParam.includes(SelectorParameter[param])) { return selectorWithParam.replace(SelectorParameter[param], newString); } } throw `The selector: ${selectorWithParam} - does not contain any parameters`; } static selector(_el: ElementFinder | ElementArrayFinder): string { return ((_el.constructor.name === 'ElementFinder' ? _el.parentElementArrayFinder.locator_ : _el.locator_).toString()).split(',')[1].replace(/.$/, '').trim(); } }
d3e39a1b878afe958af4b689a201ae9cc2bd04be
TypeScript
aqualaguna/validator-class
/src/chain/ruleFunction/comparisonRule/afterEqualRule.ts
2.671875
3
import strtotime from '../../helper/strtotime'; import dateRule from '../typeRule/dateRule'; export default function afterEqualRule (data: any, params: any) { if (dateRule(data, params)) { let d = new Date(data); let ms = strtotime(params.value.join(','), (new Date()).getTime()); if (typeof ms == "boolean" && !ms) { // assume its a field let field = params.value.join(','); let tempdata = params.root[field]; let cd = new Date(tempdata); if (isNaN(cd.getTime())) { return false; } else { return d.getTime() >= cd.getTime(); } } return d.getTime() >= ms; } else { return false; } } afterEqualRule.getErrorMessage = function (attribute_name: string, params: any) { return `${attribute_name} must be after or equal ${params.value.join(',')}.`; }
694464a8fa8af28d458325199c29c0aa35643d29
TypeScript
moredrowsy/react-native-sudoku
/src/storage/store/slices/status.slice.ts
2.671875
3
import { createSlice, PayloadAction } from '@reduxjs/toolkit'; import { RootState, AppThunk } from '..'; import * as LocalStorage from '../../local-storage'; import { AppStatus } from '../../../types'; const sliceName = 'status'; const initialState: AppStatus = { isLoggedIn: false, loading: true, userId: null, statusBarVisible: true, }; // SLICE const status = createSlice({ name: sliceName, initialState, reducers: { setCurrentUser: (state, action: PayloadAction<string>) => { state.userId = action.payload; }, setLoadingStatus: (state, action: PayloadAction<boolean>) => { state.loading = action.payload; }, setLogInStatus: (state, action: PayloadAction<boolean>) => { state.isLoggedIn = action.payload; }, setStatus: (state, action: PayloadAction<AppStatus>) => { return action.payload; }, setStatusBarVisible: (state, action: PayloadAction<boolean>) => { state.statusBarVisible = action.payload; }, }, }); export const { setCurrentUser, setLoadingStatus, setLogInStatus, setStatus, setStatusBarVisible, } = status.actions; // SELECTOR export const selectStatus = (state: RootState) => state.status; // ASYNC ACTIONS export const setCurrentUserAsync = ( userId: string, onSuccess?: () => void, onError?: (msg: string) => void ): AppThunk => async (dispatch, getState) => { try { const status = selectStatus(getState()); LocalStorage.status.setStatus({ ...status, userId }); dispatch(setCurrentUser(userId)); if (onSuccess) onSuccess(); } catch (e: unknown) { if (onError) { if (e instanceof Error) onError(e.message); else if (typeof e === 'string') onError(e); else onError('Error'); } } }; export const setLoadingAsync = ( loading: boolean, onSuccess?: () => void, onError?: (msg: string) => void ): AppThunk => async (dispatch, getState) => { try { const status = selectStatus(getState()); LocalStorage.status.setStatus({ ...status, loading }); dispatch(setLoadingStatus(loading)); if (onSuccess) onSuccess(); } catch (e: unknown) { if (onError) { if (e instanceof Error) onError(e.message); else if (typeof e === 'string') onError(e); else onError('Error'); } } }; export const setLoginStatusAsync = ( isLoggedIn: boolean, onSuccess?: () => void, onError?: (msg: string) => void ): AppThunk => async (dispatch, getState) => { try { const status = selectStatus(getState()); LocalStorage.status.setStatus({ ...status, isLoggedIn }); dispatch(setLogInStatus(isLoggedIn)); if (onSuccess) onSuccess(); } catch (e: unknown) { if (onError) { if (e instanceof Error) onError(e.message); else if (typeof e === 'string') onError(e); else onError('Error'); } } }; export const setStatusAsync = ( status: AppStatus, onSuccess?: () => void, onError?: (msg: string) => void ): AppThunk => async (dispatch, getState) => { try { LocalStorage.status.setStatus(status); dispatch(setStatus(status)); if (onSuccess) onSuccess(); } catch (e: unknown) { if (onError) { if (e instanceof Error) onError(e.message); else if (typeof e === 'string') onError(e); else onError('Error'); } } }; export default status.reducer;
90efca8e3a2cc83a1a3cf9473caa361b9cd18914
TypeScript
lcostash/backend.terence.one
/src/strategy/local.strategy.ts
2.5625
3
import { BadRequestException, Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { Strategy } from 'passport-local'; import { registerSchema, validate } from 'class-validator'; import { AuthService } from '../service'; import { LocalValidation } from '../validation'; import { ValidationError } from 'class-validator/types/validation/ValidationError'; import { UserInterface } from '../interface'; @Injectable() export class LocalStrategy extends PassportStrategy(Strategy) { /** * @param authService */ constructor(private authService: AuthService) { super(); registerSchema(LocalValidation); } /** * @since 0.0.1 * @param username string * @param password string * @return Promise<any> */ async validate(username: string, password: string): Promise<any> { const body = { username: username, password: password }; await validate('LocalValidationSchema', body).then((errors: ValidationError[]) => { if (errors.length > 0) throw new BadRequestException(errors); }); let user: UserInterface = null; await this.authService.checkAuth(username, password) .then((foundUser: UserInterface) => user = foundUser) .catch(() => { throw new UnauthorizedException(); }); return new Promise((resolve) => resolve(user)); } }
5f2e355e543273be0add88c50040a175b34db0db
TypeScript
isaacsimmons/aoc2020
/src/day7/main.ts
3.078125
3
import { truthy } from '../utils/array'; import { readInputLines } from '../utils/file'; const inputLines = readInputLines(); interface Rule { color: string; contents: Contents[]; } interface Contents { color: string; quantity: number; } const contents = new Map<string, Map<string, number>>(); const containedIn = new Map<string, Map<string, number>>(); const leaves = new Set<string>(); const saveEntry = (map: Map<string, Map<string, number>>, key1: string, key2: string, value: number) => { let inner: Map<string, number>|undefined = map.get(key1); if (!inner) { inner = new Map<string, number>(); map.set(key1, inner); } if (inner.has(key2)) { throw new Error(`Duplicate key: ${key1} ${key2}`); } inner.set(key2, value); }; const parseContent = (s: string): Contents => { const firstSpace = s.indexOf(' '); const lastSpace = s.lastIndexOf(' '); const quantity = s.substr(0, firstSpace); const color = s.substr(firstSpace + 1, lastSpace - firstSpace - 1); const bags = s.substr(lastSpace + 1); if (bags !== 'bag' && bags !== 'bags') { throw new Error('must end with bag'); } return {quantity: Number(quantity), color}; }; const parseLine = (s: string): Rule => { const [color, right] = s.split(' bags contain '); if (right === 'no other bags.') { leaves.add(color); return { color, contents: []}; } if (right[right.length - 1] !== '.') { throw new Error('no period'); } const pieces = right.substr(0, right.length - 1).split(', '); return { color, contents: pieces.map(parseContent)}; }; inputLines.forEach(line => { const rule = parseLine(line); rule.contents.forEach(({color, quantity}) => { saveEntry(contents, rule.color, color, quantity); saveEntry(containedIn, color, rule.color, quantity); }); }); //console.log(contents); const result = new Set<string>(); const active = new Set(['shiny gold']); const check = () => { const color = active.values().next().value; active.delete(color); if (!containedIn.has(color)) { return; } const newColors = [...containedIn.get(color)!.keys()]; newColors.forEach(newColor => { if (!result.has(newColor)) { result.add(newColor); active.add(newColor); } }); }; while (active.size > 0) { check(); } // console.log(result); // console.log(result.size); // console.log(leaves); const totalBags = new Map<string, number>([...leaves].map(color => [color, 0])); // console.log(totalBags); outer: while (contents.size) { mid: for (const [color, bags] of contents.entries()) { let numWithin = 0; for (const [bagColor, bagQty] of bags) { const n = totalBags.get(bagColor); if (n === undefined) { continue mid; } numWithin += (1 + n) * bagQty; } if (color === 'shiny gold') { console.log('all done', numWithin); break outer; } totalBags.set(color, numWithin); contents.delete(color); } } //console.log(totalBags);
8b79c6f18633e968e0b6f4d2173329986319ffe1
TypeScript
PrashanthEttaboina/java-programing
/TypeScript/union.ts
3.53125
4
function display(value: number | string) { if(typeof(value)=="number") console.log("Value is number : "+value); else console.log("value is String : " +value); } display(11); display("Hello World");
438a89333761c5d67a009b7332a0ab311f6b18c8
TypeScript
nhn/tui.chart
/apps/chart/tests/store/store.spec.ts
2.8125
3
import Store from '@src/store/store'; import { BaseOptions } from '@t/options'; import { ChartOptions } from '@t/store/store'; describe('Store', () => { let store: Store<BaseOptions>; describe('Computed', () => { beforeEach(() => { store = new Store({} as any); store.setRootState({ chart: { width: 1, height: 2 }, }); }); it('should computed property correctly', () => { store.setComputed('cdata', ({ chart }) => { return chart.width + chart.height; }); expect(store.computed.cdata).toEqual(3); }); }); describe('Observe', () => { beforeEach(() => { store = new Store({} as any); store.setRootState({ chart: { width: 1, height: 2 }, }); }); it('should observe observable correctly', () => { let cdata; store.observe(({ chart }) => { cdata = chart.width + chart.height; }); store.state.chart.width = 2; expect(cdata).toEqual(4); }); it('could unobserve correctly', () => { let cdata; const unob = store.observe(({ chart }) => { cdata = chart.width + chart.height; }); unob(); store.state.chart.width = 2; expect(cdata).toEqual(3); }); }); describe('watcher', () => { beforeEach(() => { store = new Store({} as any); store.setRootState({ chart: { width: 1, height: 2 }, }); }); it('should watcher property correctly', () => { let count = 0; store.setWatch('state.chart.width', (width) => { count += width; }); store.state.chart.width = 2; store.state.chart.width = 3; expect(count).toEqual(5); }); it('could unwatch correctly', () => { let count = 0; const unwatch = store.setWatch('state.chart.width', (width) => { count += width; }); store.state.chart.width = 2; if (unwatch) { unwatch(); } store.state.chart.width = 3; expect(count).toEqual(2); }); }); describe('Module', () => { it('should set state', () => { store = new Store({ series: {}, options: {} }); store.setModule({ name: 'layout', state: { chart: { width: 1, height: 2, }, }, }); expect(store.state.chart.width).toEqual(1); }); it('should set state with state function', () => { store = new Store({ series: {}, options: { chart: { width: 10, height: 15 } } }); store.setModule({ name: 'layout', state: ({ options }) => ({ chart: options.chart as ChartOptions }), }); expect(store.state.chart.width).toEqual(10); }); it('should set a action, observe, watch, computed', () => { store = new Store({ series: {}, options: {} }); let obData = 0; const watchFunc = jest.fn(); store.setModule({ name: 'layout', state: { chart: { width: 1, }, } as any, action: { myAction: ({ state }, num) => { state.chart.width = num; }, }, observe: { myObserve: ({ chart }) => { obData = chart.width; }, }, watch: { 'state.data': watchFunc, }, computed: { dataCount: ({ chart }) => { return chart.width + 10; }, }, }); expect(obData).toEqual(1); store.dispatch('myAction', 5); store.dispatch('myAction', 2); expect(obData).toEqual(2); expect(store.computed.dataCount).toEqual(12); expect(watchFunc.call.length).toEqual(1); }); }); describe('Action', () => { beforeEach(() => { store = new Store({} as any); store.setRootState({ chart: { width: 1, height: 2 }, }); }); it('should set action and dispatch', () => { store.setAction('chageWidth', ({ state }, amount: number) => { state.chart.width = amount; }); store.dispatch('chageWidth', 5); expect(store.state.chart.width).toEqual(5); }); }); it('should make state correctly with setRootState()', () => { store = new Store({} as any); store.setRootState({ chart: { width: 1, height: 2 }, }); expect(store.state).toEqual({ chart: { width: 1, height: 2 } }); }); it('should notify observable dependencies by name path', () => { store = new Store({} as any); store.setRootState({ chart: { width: 1, height: 2 }, }); let makeMyData = 0; store.observe(({ chart }) => { makeMyData += chart.width; }); store.notifyByPath('state.chart.width'); expect(makeMyData).toEqual(2); }); it('should notify observable dependencies', () => { store = new Store({} as any); store.setRootState({ chart: { width: 1, height: 2 }, }); let makeMyData = 0; store.observe(({ chart }) => { makeMyData += chart.width; }); store.notify(store.state.chart, 'width'); expect(makeMyData).toEqual(2); }); });
ecfa51f3e7bb4e33b543abbaeea2249f8c813c27
TypeScript
TheBigMoon/SWGeek
/src/redux/reducers/planetsReducer.ts
2.828125
3
import { PlanetsStore } from '../../types/store/store'; import { PlanetsActionType } from '../../types/actions/planetsActionTypes'; import { SET_PLANET, SET_PLANETS, SORT_PLANETS_BY_A_Z, SORT_PLANETS_BY_Z_A } from '../../constants/actionTypeConstants'; import { sortHelper } from './reducerHelpers/sortHelper'; const initialState: PlanetsStore = { planets: null, planet: null, prevPage: null, nextPage: null, sortByAZ: false, sortByZA: false }; const planetsReducer = (state = initialState, action: PlanetsActionType): PlanetsStore => { switch (action.type) { case SET_PLANETS: { const planets = sortHelper(state.sortByAZ, state.sortByZA, action.planets); return { ...state, planets, prevPage: action.prevPage, nextPage: action.nextPage }; } case SET_PLANET: { return { ...state, planet: action.planet }; } case SORT_PLANETS_BY_A_Z: { const planets = state.planets || []; const sortedPlanets = sortHelper(state.sortByAZ, state.sortByZA, planets); return { ...state, planets: sortedPlanets, sortByAZ: action.sortByAZ, sortByZA: false }; } case SORT_PLANETS_BY_Z_A: { const planets = state.planets || []; const sortedPlanets = sortHelper(state.sortByAZ, state.sortByZA, planets); return { ...state, planets: sortedPlanets, sortByAZ: false, sortByZA: action.sortByZA }; } default: return state; } }; export default planetsReducer;
a964c2ef0a7f731460d10860c3a8fd3d15784d50
TypeScript
ZnoGouDj/codewars-challenges
/4kyu/4kyu-human-readable-duration-format.ts
3.5625
4
function formatDuration(seconds) { const time = { year: '', day: '', hour: '', minute: '', second: '', }; const result: string[] = []; while (seconds) { if (seconds / 60 / 60 / 24 / 365 >= 1) { time.year = String(Math.floor(seconds / 60 / 60 / 24 / 365)); seconds -= +time.year * 60 * 60 * 24 * 365; } else if (seconds / 60 / 60 / 24 >= 1) { time.day = String(Math.floor(seconds / 60 / 60 / 24)); seconds -= +time.day * 60 * 60 * 24; } else if (seconds / 60 / 60 >= 1) { time.hour = String(Math.floor(seconds / 60 / 60)); seconds -= +time.hour * 60 * 60; } else if (seconds / 60 >= 1) { time.minute = String(Math.floor(seconds / 60)); seconds -= +time.minute * 60; } else { time.second = seconds; seconds -= seconds; } } for (let key in time) { if (time[key] && time[key] > 1) { result.push(time[key] + ` ${key}s`); } else if (time[key] && time[key] === 1) { result.push(time[key] + ` ${key}`); } } return result.join('').length ? result.join(', ').replace(/,([^,]*)$/, ' and$1') : 'now'; } console.log(formatDuration(1)); // => "1 second" console.log(formatDuration(62)); // => "1 minute and 2 seconds" console.log(formatDuration(120)); // => "2 minutes" console.log(formatDuration(3600)); // => "1 hour" console.log(formatDuration(3662)); // => "1 hour, 1 minute and 2 seconds"
c5f0f0c45fed80c016152310c289c45912d03c60
TypeScript
hallieliu123/typescript-study
/basic/9generic.ts
4.3125
4
// generic泛型,泛指的类型 //1.函数中的泛型 //a/ function add<ABC>(param1: ABC, param2: ABC): ABC { return param2; } add<number>(1 ,2); //b/ function join1<T, P>(p1: T | P, p2: T | P){} join1<number, number>(1, 1); join1<string, string>('a', 'b'); join1<string, number>('a', 1); //c/. T[] function loop<T>(param: Array<T>) {} loop<string>(['a', 'b']); //2.类中的泛型 { class DataManager<T> { constructor(private list: T[]) {} getResult(index: number): T { return this.list[index]; } } const d = new DataManager<string>(['a', 'b']); } { interface Person { name: string } class DataManager<T extends Person> { constructor(private list: T[]) {} getResult(index: number): string { return this.list[index].name; } } const d = new DataManager([{name: 'Sheldon'}]); } //泛型中的 keyof 语法 { interface Person { name: string, gender: string, age: number } class Account { constructor(private user: Person) {} getInfo<T extends keyof Person>(key: T) { // <T extends keyof Person> keyof 相当于循环Person中的key return this.user[key]; } } const a = new Account({name: 'Sheldon', gender: 'male', age: 21}); const info = a.getInfo('age'); console.log(info); }
8f14e540cd0e7f6730de4019f40e11eb662d2cd2
TypeScript
VIDIUN/ngx-client-11.0.0
/package/lib/api/types/PartnerGetUsageAction.d.ts
2.59375
3
import { KalturaObjectMetadata } from '../kaltura-object-base'; import { KalturaPartnerUsage } from './KalturaPartnerUsage'; import { KalturaReportInterval } from './KalturaReportInterval'; import { KalturaRequest, KalturaRequestArgs } from '../kaltura-request'; export interface PartnerGetUsageActionArgs extends KalturaRequestArgs { year?: number; month?: number; resolution?: KalturaReportInterval; } /** * Build request payload for service 'partner' action 'getUsage'. * * Usage: Get usage statistics for a partner * Calculation is done according to partner's package * Additional data returned is a graph points of streaming usage in a timeframe * The resolution can be "days" or "months" * * Server response type: KalturaPartnerUsage * Server failure response type: KalturaAPIException */ export declare class PartnerGetUsageAction extends KalturaRequest<KalturaPartnerUsage> { year: number; month: number; resolution: KalturaReportInterval; constructor(data?: PartnerGetUsageActionArgs); protected _getMetadata(): KalturaObjectMetadata; }
02d1a0b727def46ffa25eea31df494adb9c660b4
TypeScript
kvijaygiri/ecommerce
/src/app/CustomValidation.ts
2.65625
3
import {AbstractControl,ValidatorFn} from '@angular/forms'; export function NameValidation():ValidatorFn{ return (control:AbstractControl):{[key:string]:boolean}|null =>{ if(control.value.trim()=="flipkart"){ return{'NameNotAllowed':true}; } return null; }; }
a2fa2ea43e009e72b6a1d2d2d7e1c8534b33c8b3
TypeScript
AdvaithD/hodlol
/test/scenario-test.ts
3.109375
3
import { Scenario } from "../src/models/types" import "mocha"; const sinon = require("sinon"); const assert = require("assert"); describe("logger functionality", () => { it("should given numbers for start/end a scenario should assume they are timestamps", () => { const json = { id: "foo", start: 1, end: 2 }; Scenario.createWithObject(json, true); assert(Scenario.getInstance().start === 1); assert(Scenario.getInstance().end === 2); assert(Scenario.getInstance().id === "foo"); }), it("should give strings for start/end attempt to parse the strings as dates with chrono", function(){ const json = { id: "foo", start: "december 23rd 1975 7am", end: "may 15rd 1977 9am", } Scenario.createWithObject(json, true); assert(Scenario.getInstance().start === 188568000000); assert(Scenario.getInstance().end === 232549200000); }); it ("should throw if it can't interpret what the start is", function(){ const json = { id: "foo", start: "I would very much like to partake in lunch", end: "may 15th 1977 9am" }; assert.throws(function(){ Scenario.createWithObject(json, true); }); }); it ("should throw if it can't interpret what the start is", function(){ const json = { id: "foo", start: "december 23 1975 2am", end: "two men enter, one man leaves" }; assert.throws(function(){ Scenario.createWithObject(json, true); }); }) });
f1bab51838630aecc21cbf77d20f08130e239fe6
TypeScript
devbratraghuvanshi/RegencyTours
/src/cms/model/packageImage.ts
2.53125
3
import { Document, Schema, Model, model } from 'mongoose'; // PackageImage Interface export interface IPackageImageModel extends Document { //_id packageId: Schema.Types.ObjectId; imageUrl: string; imageTag: string; attribute: string; status: Boolean; createdBy: String; createdAt: Date; modifiedAt: Date; }; //PackageImage Schema export const PackageImageSchema = new Schema({ packageId: { type: String, required: true }, imageUrl: { type: String, unique: true, required: true }, imageTag: { type: String, required: true }, attribute: { type: String, required: true, enum:["Default","VirtualTour"] }, status: { type: Boolean, default: true }, createdBy: { type: String, default: 'NA' }, createdAt: { type: Date, required: false }, modifiedAt: { type: Date, required: false } }, { collection: 'PackageImage' }); PackageImageSchema.pre('save', function (next) { if (this._doc) { let doc = <IPackageImageModel>this._doc; let now = new Date(); if (!doc.createdAt) { doc.createdAt = now; } doc.modifiedAt = now; } next(); return this; }); export const PackageImageModel = model<IPackageImageModel>('PackageImage', PackageImageSchema); // export default PackageImageModel;
516e6192b99aae68c31788ae3caa7abcfbc53964
TypeScript
kylekanouse/EventsGraph
/src/server/lib/Entity.ts
3.015625
3
import { v4 as uuidv4 } from "uuid"; import IEventData from "../domain/IEventData"; import IEventsData from "../domain/IEventsData"; import IGraphData from "../domain/IGraphData"; import IGraphEntity from "../domain/IGraphEntity"; import IGraphLink from "../domain/IGraphLink" import IGraphNode from "../domain/IGraphNode"; import { createEventData, createEventsObject, createGraphDataObject, createLink } from "./Utils" /** * Entity * * @class * @abstract * @implements {IGraphEntity} */ export default abstract class Entity implements IGraphEntity { protected _id: string protected _type: string | undefined protected _icon: string | undefined /** * constructor * * @param type {string} */ constructor(type: string, id?: string, icon?: string) { this._type = type this._id = (id) ? id : uuidv4() this._icon = icon } /** * getLabel * * @returns {string} */ public abstract getLabel(): string /** * getNode * * @abstract * @returns {IGraphNode} */ public abstract getNode(): IGraphNode /** * getType * * @returns {string} */ public getType(): string { return (this._type) ? this._type : '' } /** * getIcon * * @returns {string} */ public getIcon(): string { return (this._icon) ? this._icon : '' } /** * getID * * @returns {string} */ public getID(): string { return this._id } /** * getRootNode * * @returns {string} */ public getRootNodeID(): string { return this.getID() } /** * getLinks * * @param sourceNodeID {string} * @param label {string | undefined} * @returns {IGraphLink} */ public getLink(targetNodeID: string, label?:string, value?: number): IGraphLink { // Use current sourceNodeID unless overrided by parameter label = label ? label : this.getLabel() // Return translated EventGraph Link Object return createLink( this.getID(), targetNodeID, label, value ) } /** * getGraphData * * @param {string} targetNodeID * @returns {IGraphData} */ public getGraphData(targetNodeID?: string): IGraphData { let graphData: IGraphData = createGraphDataObject() graphData.nodes.push( this.getNode() ) if (targetNodeID) { graphData.links.push( this.getLink(targetNodeID) ) } return graphData } /** * getEventData * * @returns {IEventData} */ public getEventData(): IEventData { return createEventData() } }
e208888c524739770cff9c2b30c850e811a70b51
TypeScript
IdealCattree/MeowVideoServer
/src/entities/Movie.ts
2.90625
3
import { ArrayMinSize, IsNotEmpty, Max, Min, validate } from "class-validator"; import { Type, plainToClass } from "class-transformer"; import { BaseEntity } from "./BaseEntity"; export class Movie extends BaseEntity { @IsNotEmpty({ message: "电影名称不能为空" }) @Type(() => String) public name: string; @IsNotEmpty({ message: "电影类型不可以为空" }) @ArrayMinSize(1, { message: "电影类型至少有一个" }) @Type(() => String) public types: string[]; @IsNotEmpty({ message: "电影地区不可以为空" }) @ArrayMinSize(1, { message: "电影地区至少有一个" }) @Type(() => String) public areas: string[]; @IsNotEmpty({ message: "电影时长不能为空" }) @Min(1, { message: "电影时长最少为1分钟" }) @Max(999999, { message: "电影时长过长" }) @Type(() => Number) public time: number; @IsNotEmpty({ message: "是否热映不能为空" }) @Type(() => Boolean) public isHot: boolean; @IsNotEmpty({ message: "是否即将上映不能为空" }) @Type(() => Boolean) public isComing: boolean; @IsNotEmpty({ message: "是否为经典影片不能为空" }) @Type(() => Boolean) public isClassic: boolean; @Type(() => String) public description?: string; @Type(() => String) public poster?: string; // 类型转换 public static transform(plainObject: object): Movie { return super.baseTransform(Movie, plainObject); } }
41805255f01d4db43c711798163ad776c3e43cb5
TypeScript
Eva-AlHindy/Ang3-EvaAlHindy
/src/app/route-guard.service.ts
2.734375
3
/* Import (Router, CanActivate), and inject the router into constructor of the class. This class has a proparty (authorized) which has a boolean typescript and it refers if there is user in local storge or not. And one method (canActivate()). This method makes a checkup if the username is saved in the local storage through (this.authService.checkIfLoggedIn()) and we use the method boolean to change the typescript from string to boolean and save the result in (this.authorized). If there is no username saved in local storage so we prevint the user to enter dashbourd and sent the user to login. */ import { Router, CanActivate } from '@angular/router'; import { Injectable } from '@angular/core'; import { AuthService } from './auth.service'; @Injectable({ providedIn: 'root' }) export class RouteGuardService implements CanActivate { authorized: boolean; constructor(private authService: AuthService, public router: Router) { } canActivate(): boolean { this.authorized = Boolean(this.authService.checkIfLoggedIn()); if (!this.authorized) { // alert("Please login!") this.router.navigate(['login']); return false; } return true; this.router.navigate(['dashboard']); } }
2ac03a8ba4b736dae44d91ebcc162b5208a90cad
TypeScript
danikaze/ascii-ui
/src/widgets/Text.ts
2.9375
3
import { CharStyle, Terminal, TileSize } from '../Terminal'; import { Widget, WidgetOptions } from '../Widget'; import { WidgetContainer } from '../WidgetContainer'; import { clamp } from '../util/clamp'; import { coalesce } from '../util/coalesce'; import { deepAssign } from '../util/deepAssign'; import { noWrap, splitText, tokenizer, TokenizerFunction } from '../util/tokenizer'; export interface TextOptions extends WidgetOptions { /** Text to display */ text?: string; /** * Basic style of the text * Further styles can be applied with the `commands` option of the Terminal */ textStyle?: CharStyle; /** * How to split the text (for new lines, etc.) * If `undefined` or `null`, the text will not be splitted (no-wrap) */ tokenizer?: TokenizerFunction; /** * If `tokenizer` is `false`, the `ellipsis` text will be appended when the text is too long */ ellipsis?: string; /** * Number of characters to skip. * Useful to create a horizontal text scrolling effect */ skip?: number; /** * If `true`, it won't allow empty lines at the end of a page and the text will * end at the last line of the widget. * Set to `false` to allow empty lines (so the first line is the right next one * to the last of the previous page) */ fitPageEnd?: boolean; /** * Ms. to wait between each character when writting new text * Set to `0` (default) to disable it */ typewritterDelay?: number; /** * Set to `false` to apply the typewritter to the text again when it appears even * if it was shown already before */ persistentTypewritter?: boolean; } /** * Display formatted text in the terminal, allowing vertical scroll */ export class Text extends Widget<TextOptions> { /** Default options for widget instances */ public static defaultOptions: TextOptions; /** Text splitted into lines to fit this size */ private splittedText: string[]; /** Offset of what line to display first (for the scroll, relative to `splittedText`) */ private startLine: number = 0; /** setTimeout handler to cancel the typewritter effect when the text is scrolled */ private typewritterTimer: number; /** Line where to start applying the typewritter effect if enabled (relative to `splittedText`) */ private typewritterLine = 0; /** Column where to start applying the typewritter effect if enabled (relative to `splittedText`) */ private typewritterColumn = 0; constructor(terminal: Terminal, options: TextOptions, parent?: WidgetContainer) { super( terminal, deepAssign({}, Text.defaultOptions, options), parent, ); this.render(); } /** * Render the widget in the associated terminal */ public render(): void { if (!this.splittedText || this.startLine === undefined) { return; } if (this.options.textStyle) { this.terminal.setTextStyle(this.options.textStyle); } // render is called from outside, so we reset the status of the previous rendering operation, // in case it hasn't finished yet clearTimeout(this.typewritterTimer); const typewritterEnabled = this.options.typewritterDelay > 0; const terminalColumn = this.options.col; let terminalLine = this.options.line; let lastLine = Math.min(this.startLine + this.options.height, this.splittedText.length); const completedLines = typewritterEnabled ? Math.min(this.typewritterLine, lastLine) : lastLine; let line = this.startLine; // draw complete lines while (line < completedLines) { this.terminal.setText(this.splittedText[line], terminalColumn, terminalLine); line++; terminalLine++; } lastLine = this.options.line + this.options.height; if (terminalLine >= lastLine) { return; } // draw in progress-line completed part if (this.typewritterColumn > 0) { const text = this.splittedText[line].substring(0, this.typewritterColumn) + ' '.repeat(this.options.width - this.typewritterColumn); this.terminal.setText(text, terminalColumn, terminalLine); terminalLine++; } // draw remaining lines as blank const emptyLine = ' '.repeat(this.options.width); while (terminalLine < lastLine) { this.terminal.setText(emptyLine, terminalColumn, terminalLine); terminalLine++; } if (typewritterEnabled && this.typewritterLine - this.startLine < this.options.height) { this.typewritterTimer = setTimeout( this.renderInProgressText.bind(this), this.options.typewritterDelay, terminalColumn, this.options.line, ); } } /** * Get the size of the box if the text would be fully displayed * * @return Size of the full text */ public getTextSize(): TileSize { return { columns: this.options.tokenizer ? this.splittedText[0].length : this.options.text.length, rows: this.splittedText.length, }; } /** * Set the starting line of the text * * @param line First line to draw * @return `true` if there is more content after `line`, or `false` if it was the end */ public setScrollLine(line: number): boolean { clearTimeout(this.typewritterTimer); const currentOffset = this.startLine; const maxLine = this.options.fitPageEnd ? this.splittedText.length - this.options.height : this.splittedText.length - 1; this.startLine = clamp(line, 0, maxLine); if (currentOffset !== this.startLine) { const oldTypewritterLine = this.typewritterLine; this.typewritterLine = clamp( this.typewritterLine, this.startLine, this.options.persistentTypewritter ? this.splittedText.length : maxLine, ); if (oldTypewritterLine !== this.typewritterLine) { this.typewritterColumn = 0; } } this.render(); return this.startLine < maxLine; } /** * Move the starting line of the text * * @param lines Number of lines to scroll the text * @return `true` if there is more content after `line`, or `false` if it was the last line */ public scrollLines(lines: number): boolean { return this.setScrollLine(this.startLine + lines); } /** * Move the starting line of the text by pages * * @param pages Number of pages to scroll * @return `true` if there is more pages or `false` if it was the last one */ public scrollPages(pages: number): boolean { return this.setScrollLine(this.startLine + pages * this.options.height); } /** * `setOptions` will assign the options to `this.options`, * but any derivated calculation should be done here. * * @param changes Object with only the changed options */ protected updateOptions(changes: TextOptions): void { const dirtyText = coalesce(changes.tokenizer, changes.text, changes.width, changes.skip) !== undefined; const redraw = dirtyText || coalesce(changes.col, changes.line) !== undefined; if (changes.skip !== undefined) { this.options.skip = clamp(changes.skip, 0, this.options.text.length); } if (dirtyText) { this.splittedText = this.splitText(this.options.text); } if (redraw) { this.render(); } } /** * Renders the next character when applying the typewritter effect * It will call itself again after `this.options.typewritterDelay` ms. * to draw the next character * * @param textCol column of the current line in `this.splittedText` to draw * @param textLine line of `this.splittedText` to draw */ private renderInProgressText(textCol: number, textLine: number) { const line = this.splittedText[this.typewritterLine]; if (!line) { return; } const partialText = line[this.typewritterColumn]; const x = textCol + this.typewritterColumn; const y = textLine + this.typewritterLine - this.startLine; if (!this.isAt(x, y)) { return; } this.terminal.setText( partialText, x, y, ); this.typewritterColumn++; if (this.typewritterColumn >= this.splittedText[this.typewritterLine].trim().length) { this.typewritterColumn = 0; this.typewritterLine++; } if (this.typewritterLine - this.startLine < this.options.height && this.typewritterLine < this.splittedText.length) { this.typewritterTimer = setTimeout( this.renderInProgressText.bind(this), this.options.typewritterDelay, textCol, textLine, ); } } /** * Splits a text into different lines * * @param text Text to split * @return Splitted text for each line */ private splitText(text: string): string[] { if (!this.allocated) { return; } const txt = this.options.skip ? text.substr(this.options.skip) : text; if (!this.options.tokenizer) { const noWrappedText = noWrap(txt, this.options.width, this.options.ellipsis); return noWrappedText.map((line) => line + ' '.repeat(this.options.width - line.length)); } return splitText(txt, this.options.width, this.options.tokenizer); } } /* * Default options for new instances */ Text.defaultOptions = { tokenizer, text: '', ellipsis: '...', skip: 0, fitPageEnd: false, typewritterDelay: 0, persistentTypewritter: true, };
5b66224e968229a9ce06c66999b939b8373288b1
TypeScript
LDWDev/MEAN-stack-playground
/src/app/services/stream-handler.service.ts
2.5625
3
import { Subject, Subscription, Observable } from "rxjs"; import { takeUntil } from "rxjs/operators"; import { OnDestroy, Injectable } from "@angular/core"; @Injectable() export class StreamHandler implements OnDestroy { public subscriptions: Subscription[]; private _destroy$: Subject<boolean>; constructor() { this.subscriptions = []; this._destroy$ = new Subject(); console.log("created instance with signature", Math.random()); } public register<T>(stream: Observable<T>, callBack: (o: T) => void): void { this.subscriptions.push( stream.pipe(takeUntil(this._destroy$)).subscribe(o => callBack(o)) ); } public ngOnDestroy(): void { console.log("tore down"); this.tearDownSubscriptions(); } private tearDownSubscriptions(): void { this._destroy$.next(); this._destroy$.complete(); } }
e2b3d17937576a4c17766b0e7968bd9b0398decc
TypeScript
CatInEars/Task-Scrile
/src/modules/getFilteredUsers.ts
2.875
3
import { IUser } from "../types" export function getFilteredUsers(allUsers: IUser[], searchText: string) { return allUsers.filter((user: IUser) => { return ( user.name.toLowerCase().includes(searchText.toLowerCase()) || user.username.toLowerCase().includes(searchText.toLowerCase()) ) }) }
42eac8002d2986985d816268b1f9c6c094637da5
TypeScript
cridaflo/platzi-store
/src/app/shared/pipes/agrupar/agrupar-productos.pipe.ts
2.53125
3
import { Pipe, PipeTransform } from '@angular/core'; import { Product } from '@core/models/product.model'; import { Observable, from } from 'rxjs'; @Pipe({ name: 'agruparProductos' }) export class AgruparProductosPipe implements PipeTransform { productsCount= []; // transform(products: Product[]): any { // const newProduct: Product = { // id: '6', // title: 'stickers 2', // image: 'assets/images/stickers2.png', // price: 3000, // description: 'Stickers que borré' // }; transform(products: Product[]): any { products.forEach( product => { const index = this.productsCount.findIndex(prod => product.id === prod.prod.id); if (index < 0){ this.productsCount.push({ prod: product, count: 1 }); } else{ this.productsCount[index].count+=1; } }); return this.productsCount; } }
c994365069990fd374b2c1c5057d75fb4f227860
TypeScript
akheron/optics-ts
/src/standalone/operations.spec.ts
3.046875
3
import * as O from '.' describe('get', () => { const optic = O.prop('foo') const source = { foo: 'bar' } type Focus = string it('total', () => { const result: Focus = O.get(optic, source) expect(result).toEqual('bar') }) it('partial', () => { const result: Focus = O.get(optic)(source) expect(result).toEqual('bar') }) }) describe('preview', () => { const optic = O.at(0) const source = ['bar'] type Focus = string | undefined it('total', () => { const result: Focus = O.preview(optic, source) expect(result).toEqual('bar') }) it('partial', () => { const result: Focus = O.preview(optic)(source) expect(result).toEqual('bar') }) }) describe('collect', () => { const optic = O.elems const source = ['bar'] type Focus = string[] it('total', () => { const result: Focus = O.collect(optic, source) expect(result).toEqual(['bar']) }) it('partial', () => { const result: Focus = O.collect(optic)(source) expect(result).toEqual(['bar']) }) }) describe('modify', () => { const optic = O.prop('foo') const source = { foo: 'bar' } type Target = { foo: number } it('total', () => { const result: Target = O.modify(optic, (x) => x.length, source) expect(result).toEqual({ foo: 3 }) }) it('partial1', () => { const result: Target = O.modify(optic, (x: string) => x.length)(source) expect(result).toEqual({ foo: 3 }) }) it('partial2', () => { const result: Target = O.modify(optic)((x: string) => x.length)(source) expect(result).toEqual({ foo: 3 }) }) }) describe('set', () => { const optic = O.prop('foo') const source = { foo: 'bar' } type Target = { foo: number } it('total', () => { const result: Target = O.set(optic, 42, source) expect(result).toEqual({ foo: 42 }) }) it('partial1', () => { const result: Target = O.set(optic, 42)(source) expect(result).toEqual({ foo: 42 }) }) it('partial2', () => { const result: Target = O.set(optic)(42)(source) expect(result).toEqual({ foo: 42 }) }) }) describe('remove', () => { const optic = O.at(0) const source = [1, 2] type Target = number[] it('total', () => { const result: Target = O.remove(optic, source) expect(result).toEqual([2]) }) it('partial', () => { const result: Target = O.remove(optic)(source) expect(result).toEqual([2]) }) })
3fb30bdca1fd319996f202e64834c6759b164417
TypeScript
Seafnox/ngx-sudocu
/src/components/cell-actions/cell-actions.component.ts
2.640625
3
import { Component, EventEmitter, HostListener, Input, Output } from '@angular/core'; import { Board } from '../../interfaces/board'; import { CellPosition } from '../../interfaces/cell.position'; import { Cell } from '../../interfaces/cell'; import { boardSize } from '../../consts/config'; @Component({ selector: 'app-cell-actions', templateUrl: './cell-actions.component.html', styleUrls: ['./cell-actions.component.css'], }) export class CellActionsComponent { @Input() position: CellPosition; @Input() cell: Cell; @Input() board: Board; @Input() stopChanges: boolean; @Output() positionChange = new EventEmitter<CellPosition>(); @Output() cellValueChange = new EventEmitter<number>(); public values = new Array(boardSize).fill(0).map((a, index) => index + 1); public moveLeft(): void { if (!this.position) { return this.positionChange.emit({x: 0, y: 0}); } return this.positionChange.emit({...this.position, x: (this.position.x - 1 + boardSize) % boardSize}); } public moveRight(): void { if (!this.position) { return this.positionChange.emit({x: 0, y: 0}); } return this.positionChange.emit({...this.position, x: (this.position.x + 1) % boardSize}); } public moveUp(): void { if (!this.position) { return this.positionChange.emit({x: 0, y: 0}); } return this.positionChange.emit({...this.position, y: (this.position.y - 1 + boardSize) % boardSize}); } public moveDown(): void { if (!this.position) { return this.positionChange.emit({x: 0, y: 0}); } return this.positionChange.emit({...this.position, y: (this.position.y + 1 + boardSize) % boardSize}); } public select(value?: number): void { if (this.canSelect(value)) { this.cellValueChange.emit(value); } } public clear(): void { this.select(undefined); } @HostListener('window:keydown', ['$event']) public handleKeyDown(event: KeyboardEvent): void { if (this.stopChanges) { return; } switch (event.key) { case 'ArrowUp': return this.moveUp(); case 'ArrowDown': return this.moveDown(); case 'ArrowLeft': return this.moveLeft(); case 'ArrowRight': return this.moveRight(); case '1': return this.select(1); case '2': return this.select(2); case '3': return this.select(3); case '4': return this.select(4); case '5': return this.select(5); case '6': return this.select(6); case '7': return this.select(7); case '8': return this.select(8); case '9': return this.select(9); case 'Backspace': return this.clear(); case 'Delete': return this.clear(); } } private canSelect(value?: number): boolean { return this.position && !this.stopChanges && !!this.cell && !this.cell.isPermanent && this.cell.userValue !== value; } }
3da687ffcf1037caaf3c9609f83302e8dd45caf1
TypeScript
snakemode/massively-tetris
/src/tetris/World.ts
2.921875
3
import { Move, Mino, Cell, RotationOperation, IRotationSystem } from './Types'; import { SuperRotationSystem } from './SuperRotationSystem'; import { Tetromino } from "./Tetromino"; type Row = Cell[]; type MoveResult = { canMove: boolean, lock: boolean }; export class World { public playerId: string; public width: number; public height: number; public occupiedLocations: Mino[]; public tetromino: Tetromino; public rotationSystem: IRotationSystem; public gameOver: boolean = false; public score: number = 0; public constructor(playerId: string, width: number = 10, height: number = 22) { this.rotationSystem = new SuperRotationSystem(this); this.playerId = playerId; this.width = width; this.height = height; this.occupiedLocations = []; this.tetromino = Tetromino.Empty(); } public tick(): void { if (this.gameOver) { return; } if (this.tetromino.shape === "Empty") { this.spawnNewPiece(); this.checkForGameOver(); } this.move({ deltaX: 0, deltaY: -1, rotation: RotationOperation.None }); this.lineClear(); } public move(move: Move) { if (move.rotation != RotationOperation.None) { this.rotationSystem.rotate(move.rotation); } const moveCheck = this.canMove(move); if (moveCheck.canMove) { this.tetromino.location.x = this.tetromino.location.x + move.deltaX; this.tetromino.location.y = this.tetromino.location.y + move.deltaY; } if (moveCheck.lock) { this.lockTetromino(); this.tetromino = Tetromino.Empty(); } } private canMove(move: Move): MoveResult { for (const mino of this.tetromino.minos()) { const nextX = mino.x + move.deltaX; const nextY = mino.y + move.deltaY; if (nextY < 0) { return { canMove: false, lock: true }; } if (nextX < 0 || nextX >= this.width) { return { canMove: false, lock: false }; } const wouldCollide = this.occupiedLocations.filter(loc => loc.x == nextX && loc.y == nextY).length; if (wouldCollide && move.deltaY != 0) { return { canMove: false, lock: true }; } if (wouldCollide && move.deltaX != 0) { return { canMove: false, lock: false }; } } return { canMove: true, lock: false }; } private lockTetromino(): void { for (const mino of this.tetromino.minos()) { this.occupiedLocations.push(mino); } } private spawnNewPiece() { this.tetromino = Tetromino.random(); this.tetromino.location = { x: 3, y: this.height + 2 }; } private checkForGameOver(){ const gameOverCheck = this.canMove({ deltaX: 0, deltaY: -1, rotation: RotationOperation.None }); if (!gameOverCheck.canMove) { console.log("❌ Game over! " + this.score); this.gameOver = true; } } private lineClear() { const allRows = [...this.rows(false)]; const clearedRows: number[] = []; for (var row of allRows) { const rowY = row[0].y; if (row.every(cell => cell.occupied)) { this.occupiedLocations = this.occupiedLocations.filter(cell => cell.y != rowY); clearedRows.push(rowY); } } for (const rowNumber of clearedRows) { // Shift all rows down this.occupiedLocations = this.occupiedLocations.map(cell => { cell.y = cell.y > rowNumber ? cell.y - 1: cell.y; return cell; }); } switch (clearedRows.length) { case 1: this.score += 40; case 2: this.score += 100; case 3: this.score += 300; case 4: this.score += 1200; default: this.score += 0; } } public *cells(): IterableIterator<Cell> { for (let row of this.rows()) { for (let cell of row) { yield cell; } } } public *rows(includeActiveTetromino: boolean = true): IterableIterator<Row> { for (let yLoop = 0; yLoop < this.height; yLoop++) { const y: number = (this.height -1 ) - yLoop; const row: Row = []; for (let x = 0; x < this.width; x++) { let anyMinos: Mino[] = this.occupiedLocations.filter(l => l.x === x && l.y === y); let occupied: boolean = anyMinos.length > 0; let origin = occupied ? anyMinos[0].shape : null; if (includeActiveTetromino) { if (this.tetromino != null && this.tetromino.occupies({ x, y })) { occupied = true; origin = this.tetromino.shape; } } row.push({ x, y, occupied, origin }); } yield row; } } public toStringArray(includeActiveTetromino: boolean = false): string[] { const lines: string[] = []; for (const row of this.rows(includeActiveTetromino)) { var line = ""; for (const cell of row) { if(cell.occupied) { line += cell.origin; } else { line += " "; } } lines.push(line); } return lines; } }
fb23736682fbe1db3fc6cae11fcd8d7fc741fe30
TypeScript
psousa50/hearts-game-core
/src/Tricks/domain.ts
2.890625
3
import { score as cardScore } from "../Cards/domain" import { Card } from "../Cards/model" import { Trick } from "./model" export const createTrick = (cards: Card[] = [], firstPlayerIndex: number = 0): Trick => ({ cards, firstPlayerIndex, }) export const isEmpty = (trick: Trick) => trick.cards.length === 0 export const firstCard = (trick: Trick) => trick.cards[0] export const suit = (trick: Trick) => isEmpty(trick) ? undefined : trick.cards[0].suit export const addCard = (trick: Trick, card: Card, playerIndex: number) => ({ cards: [...trick.cards, card], firstPlayerIndex: isEmpty(trick) ? playerIndex : trick.firstPlayerIndex, }) export const score = (trick: Trick) => trick.cards.reduce((s, card) => s + cardScore(card), 0)
0b2655656dedd664b5a632372f31ad40e8e57285
TypeScript
NatanelMizrahi/kindred-marvel
/src/app/d3/models/link.ts
2.65625
3
import APP_CONFIG from '../../app.config'; import { Node } from './index'; export type LinkType = 'EVENT' | 'ALLIANCE'; export class Link implements d3.SimulationLinkDatum<Node> { static STRENGTH_FACTOR = ((APP_CONFIG.LINK_WIDTH_FACTOR) / (APP_CONFIG.MAX_VISIBLE_CHARS)); // * Math.log10(APP_CONFIG.EVENT_LIMIT) index?: number; source: Node; target: Node; type: LinkType; constructor(source, target, type: LinkType = 'EVENT') { this.type = type; this.source = source; this.target = target; this.source.links.push(this); this.target.links.push(this); } get strength() { return Link.STRENGTH_FACTOR * this.source.character.linkStrength(this.target.character) ; } get opacity() { return APP_CONFIG.BASE_OPACITY * Math.log2(this.strength) / 100; } get isDragged() { return (this.source.isDragged || this.target.isDragged); } get color() { return this.isDragged ? `rgba(200,0,50,${this.opacity})` : this.type === 'EVENT' ? `rgba(200,200,50,${this.opacity})` : `rgba(0,50,200,${2 * this.opacity})`; } get isVisible() { return this.strength > APP_CONFIG.VIEW_THRESHOLD || this.isDragged; } }
080bf5623cdc822ee3cae51714a0141a03b3eaf4
TypeScript
ClaudiaFeliciano/Arrow-6
/Scripts/objects/shoot.ts
3.03125
3
module objects { export class Shoot extends objects.AbstractGameObject { private _speed: number; private _direction: math.Vec2; private _isInPlay: boolean; private _velocity: math.Vec2; get Direction(): math.Vec2 { return this._direction; } set Direction(newDirection: math.Vec2) { this._direction = newDirection; } get IsInPlay(): boolean { return this._isInPlay; } set IsInPlay(newState: boolean) { this._isInPlay = newState; if (!this._isInPlay) { this.Reset(); } this._velocity = math.Vec2.Mulitply(this.Direction, this._speed); } // constructor constructor() { super("shot"); this.Start(); } // public methods public Reset(): void { this.x = -2000; this.y = -2000; if (managers.Game.goingDown) { this.Direction = math.Vec2.down(); } if (managers.Game.goingUp) { this.Direction = math.Vec2.up(); } if (managers.Game.goingLeft) { this.Direction = math.Vec2.left(); this.y = this.y - 40; } if (managers.Game.goingRigth) { this.Direction = math.Vec2.right(); } this._updatePosition(); // this.Direction = math.Vec2.zero(); } private _animationEnded() { this.alpha = 1; this.off("animationend", this._animationEnded.bind(this), false);//remove my event listener } public Start(): void { this._speed = 15; this.IsInPlay = false; // this.Reset(); } public Update(): void { if (this.IsInPlay) { this.Move(); this.CheckBounds(); } } public Destroy(): void { } public Move(): void { if (managers.Game.goingLeft) { this.x += this.HalfHeight; } if (managers.Game.goingRigth) { this.x -= this.HalfHeight; } if (managers.Game.goingUp) { this.y += this.HalfHeight; } if (managers.Game.goingDown) { this.y -= this.HalfHeight; } this._updatePosition(); this.Position = math.Vec2.Add(this.Position, this._velocity); this.x = this.Position.x; this.y = this.Position.y; } public CheckBounds(): void { /* if (this.x <= -this.Height) { this.Reset();*/ if (this.y <= -this.Height) { this.IsInPlay = false; this.Reset(); } if (this.x <= -this.Width) { this.IsInPlay = false; this.Reset(); } } } }
c16717d023e3c91c96a8b15e4da283bf60a5d91c
TypeScript
pwcong/okeedesign-mobile-vue
/tests/unit/toast.spec.ts
2.53125
3
import { later } from '../index'; import { Toast as NativeToast } from '@src'; const Toast = NativeToast as any; describe('Toast', () => { test('create a forbidClick toast', async () => { const toast = Toast({ forbidClick: true, type: 'success', }); await later(); expect(toast.$el.outerHTML).toMatchSnapshot(); await later(); expect(document.body.classList.contains('o-toast--unclickable')).toBeTruthy(); toast.forbidClick = false; await later(); expect(document.body.classList.contains('o-toast--unclickable')).toBeFalsy(); }); test('toast disappeared after duration', async () => { const toast = Toast({ duration: 500, }); await later(1000); expect(toast.$el.style.display).toEqual('none'); }); test('show loading toast', async () => { const toast = Toast({ message: 'loading...', type: 'loading', }); await later(); expect(toast.$el.outerHTML).toMatchSnapshot(); }); test('should trigger onClose callback after closed', () => { Toast.allowMultiple(); const onClose = jest.fn(); const toast = Toast({ message: 'toast', onClose, }); toast.clear(); expect(onClose).toHaveBeenCalledTimes(1); Toast.allowMultiple(false); }); test('trigger onOpened callback after open', async () => { const onOpened = jest.fn(); const onClose = jest.fn(); const toast = Toast({ message: 'toast', duration: 100, onOpened, onClose, }); await later(500); expect(onOpened).toHaveBeenCalledTimes(1); expect(onClose).toHaveBeenCalledTimes(1); toast; }); });
88d15d17b2875175ca86a70106deaaa1d23494b9
TypeScript
BeMoreHuman/Mahjong-like-game
/src/app/app.component.ts
2.703125
3
import { Component, OnInit } from '@angular/core'; import { GameServiceService } from './services/game-service.service'; export interface CardInterface { value: number; isEnabled: boolean; isDone: boolean; } @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent implements OnInit { title = 'Mahjong-like game'; cardArray: CardInterface[] = [ {value: 0, isEnabled: false, isDone: false}, {value: 1, isEnabled: false, isDone: false}, {value: 2, isEnabled: false, isDone: false}, {value: 1, isEnabled: false, isDone: false}, {value: 0, isEnabled: false, isDone: false}, {value: 2, isEnabled: false, isDone: false}, ]; selectedCardIndex: number = null; isWaiting = false; isReadyToPlay = false; sec = 0; min = 0; hour = 0; playerGameTime = '00:00:00'; timer: any; winScore = this.cardArray.length / 2; currentScore = 0; constructor( public gameService: GameServiceService, ) {} ngOnInit(): void {} startGame(): void { this.isReadyToPlay = true; this.timer = setInterval(() => { this.timeHandler(); }, 1000); } endGame(): void { this.timer = clearInterval(this.timer); } giveUp(): void { this.isReadyToPlay = false; this.timer = clearInterval(this.timer); this.sec = 0; this.min = 0; this.hour = 0; this.playerGameTime = '00:00:00'; this.cardArray.forEach(card => { card.isEnabled = false; card.isDone = false; }); this.selectedCardIndex = null; } timeHandler(): void { this.sec++; if (this.sec === 60) { this.sec = 0; this.min++; } if (this.min === 60) { this.min = 0; this.hour++; } this.displayTime(); } displayTime(): void { let sec_pretty: string = String(this.sec); let min_pretty: string = String(this.min); let hour_pretty: string = String(this.hour); if (this.sec < 10) { sec_pretty = '0' + this.sec; } if (this.min < 10) { min_pretty = '0' + this.min; } if (this.hour < 10) { hour_pretty = '0' + this.hour; } this.playerGameTime = hour_pretty + ':' + min_pretty + ':' + sec_pretty; } showCard(item: CardInterface, index: number): void { // Card already has pairs or double click if (item.isDone || index === this.selectedCardIndex) { return; } // First click if (!this.isWaiting && !this.selectedCardIndex) { this.isWaiting = true; item.isEnabled = true; this.selectedCardIndex = index; setTimeout(() => { this.isWaiting = false; }, 500); } // Second click if (!this.isWaiting && this.selectedCardIndex) { this.isWaiting = true; item.isEnabled = true; // Cards don't match if (item.value !== this.cardArray[this.selectedCardIndex - 1].value) { setTimeout(() => { this.cardArray[this.selectedCardIndex - 1].isEnabled = false; this.selectedCardIndex = null; item.isEnabled = false; this.isWaiting = false; }, 500); } // Cards match if (item.value === this.cardArray[this.selectedCardIndex - 1].value) { item.isDone = true; this.cardArray[this.selectedCardIndex - 1].isDone = true; // Check win score this.currentScore++; if (this.winScore === this.currentScore) { this.endGame(); } setTimeout(() => { this.selectedCardIndex = null; this.isWaiting = false; }, 500); } } } }
7dbb84cf17f3ac89b19c0d2621efffad6faae50b
TypeScript
cedelar/beartender_client
/src/app/_model/cocktail.model.ts
3.1875
3
interface CocktailJson { name: string, description: string, imageLink: string } export class Cocktail{ constructor( private _name: string, private _description: string, private _imageLink: string ){} get name(): string { return this._name; } get description(): string { return this._description; } get imageLink(): string { return this._imageLink; } static fromJSON(json: CocktailJson): Cocktail{ return new Cocktail( json.name, json.description, json.imageLink ); } }
f3282bd3b3cb61c68dc624f6285c6b0fd1620f19
TypeScript
theguvnors/CodingProblems
/ResponseChecking/Response2.ts
2.84375
3
console.clear(); type ModernResponse = { metadata: MetaData; body: unknown }; type MetaData = { apiVersion: string; callStatus: number }; type ValidationRule = { propName: string; propType: string }; class ApiModelValidator { public validate(o: ModernResponse | any): boolean { return this.isModernResponseObject(o) && this.isMetadataObject(o.metadata); } private isModernResponseObject(o: ModernResponse | unknown): o is ModernResponse { const properties: ValidationRule[] = [ { propName: 'metadata', propType: 'object' }, { propName: 'body', propType: 'object' }, ]; return hasPropertyType(o, properties); } private isMetadataObject(o: MetaData | unknown): o is MetaData { const properties: ValidationRule[] = [ { propName: 'apiVersion', propType: 'number' }, { propName: 'callStatus', propType: 'number' }, ]; return !!o && hasPropertyType(o, properties); } } function hasPropertyType<t>(o: any, props: ValidationRule[]): boolean { let returnValue = true; props.forEach((x) => { if (o[x.propName] === undefined) { console.log('Property: ' + x.propName + ' does not exist on ', o); returnValue = false; return; } else if (typeof o[x.propName] !== x.propType) { console.log( 'Property: ' + x.propName + ' was expected to be typeof: ' + x.propType + ' but was ' + typeof o[x.propName] ); returnValue = false; return; } }); return returnValue; } // tests let x = { metadata: { apiVersion: '2', callStatus: 2 }, body: {} }; let y = { metadata: { apiVersion: 2, callStatus: 2 }, body: {} }; let validator = new ApiModelValidator(); console.log(validator.validate(x)); console.log(validator.validate(y)); let test = 'www.typescriptlang.org/play?#code/webkitReques/tAnimationFrameqw.htm'; let parts = test.split('/'); let url = ''; if (parts.length > 1) { parts.slice(1, parts.length).forEach((x) => { console.log(x); url += '/' + x; }); } else { url = test; } console.log(url);
822861d63b4350f0724ef14f04ccf34578821803
TypeScript
noasand/grafana
/public/app/core/specs/emitter.test.ts
3.046875
3
import { Emitter } from '../utils/emitter'; describe('Emitter', () => { describe('given 2 subscribers', () => { it('should notfiy subscribers', () => { const events = new Emitter(); let sub1Called = false; let sub2Called = false; events.on('test', () => { sub1Called = true; }); events.on('test', () => { sub2Called = true; }); events.emit('test', null); expect(sub1Called).toBe(true); expect(sub2Called).toBe(true); }); it('when subscribing twice', () => { const events = new Emitter(); let sub1Called = 0; function handler() { sub1Called += 1; } events.on('test', handler); events.on('test', handler); events.emit('test', null); expect(sub1Called).toBe(2); }); it('should handle errors', () => { const events = new Emitter(); let sub1Called = 0; let sub2Called = 0; events.on('test', () => { sub1Called++; throw { message: 'hello' }; }); events.on('test', () => { sub2Called++; }); try { events.emit('test', null); } catch (_) {} try { events.emit('test', null); } catch (_) {} expect(sub1Called).toBe(2); expect(sub2Called).toBe(0); }); }); });
da2607fe8b3a565ae9e5fbe1b2308b6aa0bb1c1e
TypeScript
triptu/withRetry
/src/withRetry.ts
3.09375
3
import { ResourceExhaustedError } from "./ResourceExhaustedError"; import { Settings } from "./Settings"; type WithRetry = <T, Y extends unknown[]>( callback: (...args: Y) => Promise<T> ) => (...args: Y) => Promise<T>; const defaults = { maxCalls: 2, errors: [], delay: 0, }; const sleep = async (intervalMs: number): Promise<void> => await new Promise((resolve) => setTimeout(() => resolve(), intervalMs)); export default function withRetry<E extends Error>( options: Partial<Settings<E>> = {} ): WithRetry { const settings: Settings<E> = { ...defaults, ...options }; return <T, Y extends unknown[]>( callback: (...args: Y) => Promise<T> ): ((...args: Y) => Promise<T>) => { let { maxCalls } = settings; const errors: E[] = []; return async ( ...args: Parameters<typeof callback> ): ReturnType<typeof callback> => { do { try { return await callback(...args); } catch (error) { errors.push(error); if ( settings.errors.length && !settings.errors.some( (errorConstructor) => error instanceof errorConstructor ) ) { throw error; } if (maxCalls > 1 && settings.delay) { await (typeof settings.delay === "number" ? sleep(settings.delay) : sleep( settings.delay({ call: settings.maxCalls - maxCalls, errors: Array.from(errors), }) )); } } } while (--maxCalls); throw new ResourceExhaustedError(errors); }; }; }
2f1b9ebeabf1581525b2dbbb1f3f4ee6f86e2048
TypeScript
swedesjs/rus-anonym-utils
/ts/src/lib/logical/core.ts
4.09375
4
/** * @category Logical * @description Класс для работы с логическими функциями * @hideconstructor */ export class LogicalUtils { /** * Логическое И * Конъюнкция * Логическое умножение, выражение «AND». * Конъюнкция возвращает true только тогда, когда оба аргумента равны true, иначе false. * * @param {boolean} a - 1 значение * @param {boolean} b - 2 значение * @returns {boolean} - результат * @example * logical.AND(true, true) // => true * logical.AND(true, false); // => true * logical.AND(false, false); // => false * logical.AND(false, true); // => true */ public AND(a: boolean, b: boolean): boolean { return a && b; } /** * Логическое ИЛИ * Дизъюнкция * Логическое сложение, выражение «OR». Также называется «слабой дизъюнкцией». * Возвращает false только тогда, когда оба аргумента равны false, иначе true. * * @param {boolean} a - 1 значение * @param {boolean} b - 2 значение * @returns {boolean} - результат * @example * logical.OR(true, true) // => true * logical.OR(true, false); // => true * logical.OR(false, false); // => false * logical.OR(false, true); // => true */ public OR(a: boolean, b: boolean): boolean { return a || b; } /** * Логическое И-НЕ * Возвращает true только тогда, когда оба аргумента равны true, иначе false * * @param {boolean} a - 1 значение * @param {boolean} b - 2 значение * @returns {boolean} - результат * @example * logical.ANOT(true, true) // => true * logical.ANOT(true, false); // => false * logical.ANOT(false, true); // => false * logical.ANOT(false, false); // => false */ public ANOT(a: boolean, b: boolean): boolean { return a === true && b === true; } /** * Логическое ИЛИ-НЕ * Иначе стрелка Пирса, выражение «NOR». * Возвращает true только тогда, когда оба аргумента одновременно равны false. * * @param {boolean} a - 1 значение * @param {boolean} b - 2 значение * @returns {boolean} - результат * @example * logical.NOR(true, true) // => false * logical.NOR(true, false); // => false * logical.NOR(false, false); // => true * logical.NOR(false, true); // => false */ public NOR(a: boolean, b: boolean): boolean { return a === false && b === false; } /** * Логическое исключающее ИЛИ * Сильная дизъюнкция * Исключающая дизъюнкция, выражение «XOR». * Возвращает true только тогда, когда только один из них равен true, а второй равен false. * * @param {boolean} a - 1 значение * @param {boolean} b - 2 значение * @returns {boolean} - результат * @example * logical.XOR(true, true) // => false * logical.XOR(true, false); // => true * logical.XOR(false, false); // => false * logical.XOR(false, true); // => true */ public XOR(a: boolean, b: boolean): boolean { return a ? !b : b; } /** * Логическое НЕ * Отрицание * Инверсия, негация, выражение «NOT». * Возвращает противоположное значение: для false — true, для true — false. * * @param {boolean} a - 1 значение * @returns {boolean} - результат * @example * logical.NOT(true) // => false * logical.NOT(false); // => true */ public NOT(a: boolean): boolean { return !a; } /** * Логическое РАВНО * Эквивалентность * Тождество, равенство, выражение «EQ». * Возвращает true только тогда, когда оба аргумента равны одновременно false или true. * * @param {boolean} a - 1 значение * @param {boolean} b - 2 значение * @returns {boolean} - результат * @example * logical.EQ(true, true) // => false * logical.EQ(true, false); // => false * logical.EQ(false, false); // => true * logical.EQ(false, true); // => true */ public EQ(a: boolean, b: boolean): boolean { return a === b; } /** * Импликация * Выражает зависимость причины и следствия. * То есть возвращает ложь только тогда, когда первый аргумент равен true, а второй аргумент — false. * * @param {boolean} a - 1 значение * @param {boolean} b - 2 значение * @returns {boolean} - результат * @example * logical.IMP(true, true) // => true * logical.IMP(true, false); // => false * logical.IMP(false, false); // => true * logical.IMP(false, true); // => true */ public IMP(a: boolean, b: boolean): boolean { return a === true && b === false ? false : true; } } export const logical = new LogicalUtils();
968e5420dc9644d455591481bdcfa282dfec405b
TypeScript
koladev32/node-express-jwt-tutorial
/src/middleware/middleware.ts
2.5625
3
import e, { Response, Request, NextFunction } from "express"; import { IUser } from "../types/user"; const jwt = require("jsonwebtoken"); const authenticateJWT = async ( req: Request, res: Response, next: NextFunction ): Promise<e.Response<any, Record<string, any>>> => { const authHeader = req.headers.authorization; if (authHeader) { const [header, token] = authHeader.split(" "); if (!(header && token)) { return res.status(401).send("Authentication credentials are required."); } jwt.verify(token, process.env.JWT_SECRET_KEY, (err: Error, user: IUser) => { if (err) { return res.sendStatus(403); } req.user = user; next(); }); } return res.sendStatus(401); }; export default authenticateJWT;
04b7f5e26c1b56084e6066985db36dbd5408a472
TypeScript
HAFDIAHMED/IgniteTraning
/app/models/profil/profil.ts
2.59375
3
import { flow, Instance, SnapshotOut, types } from "mobx-state-tree" import { Api } from "../../services/api" /** * Model description here for TypeScript hints. */ export const ProfilModel = types .model("Profil") .props({ name : types.optional(types.string,""), job : types.optional(types.string, "j"), }) .views((self) => ({ get getJob (){ return self.job }, get getName (){ return self.name } })) // eslint-disable-line @typescript-eslint/no-unused-vars .actions((self) => ({ setJob( value : string){ self.job=value }, setName (value : string){ self.name=value } })) .actions((self)=> ({ getProfile : flow (function * (){ const api = new Api() api.setup() yield api.fetchProfils().then((response : any)=>{ self.setJob(response.job) self.setName(response.name) }) }) }) ) // eslint-disable-line @typescript-eslint/no-unused-vars type ProfilType = Instance<typeof ProfilModel> export interface Profil extends ProfilType {} type ProfilSnapshotType = SnapshotOut<typeof ProfilModel> export interface ProfilSnapshot extends ProfilSnapshotType {} export const createProfilDefaultModel = () => types.optional(ProfilModel, {})
280b1d713a3eb7457481b492dd72a5980249f1ae
TypeScript
craig0chq0/tsPlayGround
/while.ts
4.21875
4
// 安装 nodejs // 安装 nodejs 的 一个模块 typescript // 循环资料 // http://www.runoob.com/js/js-loop-for.html // http://www.runoob.com/js/js-loop-while.html // http://www.runoob.com/js/js-break.html // 实现一个函数,传入任意长度的数字数组,返回数组中所有元素相加的和 function getSum(arr: number[]) { let sum: number = 0; for (let i = 0; i < arr.length; ++i) { sum += arr[i]; } return sum; } let arr0 = [0, 1, 2, 3, 4, 5]; console.log("题目1的答案为: " + getSum(arr0)); // 实现一个函数,传入任意长度的数字数组,返回数组中除最后一个元素之外的和 function getsum1(arr: number[]) { let sum1: number = 0; for (let i = 0; i < arr.length - 1; ++i) { sum1 += arr[i]; } return sum1; } console.log("answer is " + getsum1(arr0)); // 实现一个函数,传入任意长度的数字数组,返回数组中所有第奇数位元素的和 function getsum2(arr: number[]) { let sum2: number = 0; for (let i = 1; i < arr.length; i = i + 2) { sum2 += arr[i]; } return sum2; } console.log("answer2 is " + getsum2(arr0)); // 实现一个函数,传入任意长度的数字数组,返回数组中所有偶数的和 function getsum3(arr: number[]) { let sum3: number = 0; for (let i = 0; i < arr.length; i++) { if (arr[i] % 2 == 0) { sum3 += arr[i]; } } return sum3; } console.log("answer3 is " + getsum3(arr0)); // 构造一个数组,并作为参数传入上面函数,打印返回值
378c37557fd6c6009821901b8232f17831daa83e
TypeScript
letmaik/chip8
/src/test/chip8.test.ts
2.71875
3
import { assert } from 'chai' import { wasm, unboundWasm } from './wasm' function loadProgram(program: Array<number>) { wasm.init() wasm.loadProgram(new Uint8Array(program)) return state() } function run(program: Array<number>) { loadProgram(program) return step() } function step(n = 1) { for (let i = 0; i < n; i++) { wasm.stepCPU() } return state() } function press(key: number, down: boolean) { unboundWasm.setKeyDown(key, down) return state() } function state() { return { ram: wasm.getRam().value, raster: wasm.getDisplayRaster().value, keys: unboundWasm.getKeys(), v: wasm.getVRegisters().value, i: unboundWasm.getIRegister(), dt: wasm.getDTRegister(), st: wasm.getSTRegister(), pc: unboundWasm.getPCRegister(), sp: wasm.getSPRegister(), stack: wasm.getStackRegister().value } } function bin(s: string) { return parseInt(s, 2) } // yEnd and xEnd are exclusive. function slice2D(arr: Uint8Array, height: number, width: number, yStart: number, yEnd: number, xStart: number, xEnd: number) { if (height < 0 || width < 0 || yStart < 0 || xStart < 0 || xStart > xEnd || yStart > yEnd || yEnd > height || xEnd > width) { throw new RangeError() } const newHeight = yEnd - yStart const newWidth = xEnd - xStart const out = new Uint8Array(newHeight * newWidth) for (let y = yStart; y < yEnd; y++) { const start = y * width + xStart const end = start + newWidth out.set(arr.subarray(start, end), (y - yStart) * newWidth) } return out } function sliceRaster(raster: Uint8Array, ySlice: [number, number?], xSlice: [number, number?]) { return slice2D(raster, 32, 64, ySlice[0], ySlice[1] || (ySlice[0] + 1), xSlice[0], xSlice[1] || (xSlice[0] + 1)) } // Tests from https://github.com/SnoozeTime/chip8/blob/master/test/opcode_test.cc describe('SnoozeTime instruction tests', function () { describe('LD_I_ADDR', function () { it('should store the given address in the I register', function () { // 0xA2F0 - move 2F0 in I const r = run([0xA2, 0xF0]) assert.equal(r.i, 0x2F0) assert.equal(r.pc, 0x202) }) }) describe('CALL_ADDR', function () { it('should call the given address', function () { // 0x2204 - execute subroutine at index 204. let r = run([0x22, 0x04, 0xA2, 0xF0, 0xA2, 0xFF]) // stack should be one. pc would be stored as 0x200. Current pc is 0x204. assert.equal(r.sp, 1) assert.equal(r.pc, 0x204) // FIXME should this be stack[0]? assert.equal(r.stack[1], 0x200) // to confirm execute the next cycle r = step() assert.equal(r.i, 0x2FF) }) }) describe('RET', function () { it('should return to the address at the top of the stack', function () { // 0x2204 - execute subroutine at index 204. let r = run([ 0x22, 0x04, // execute 0xA2FF subroutine 0xA2, 0xF0, 0xA2, 0xFF, // subroutine start. 0x00, 0xEE]) // stack should be one. pc would be stored as 0x200. Current pc is 0x204. assert.equal(r.sp, 1) assert.equal(r.pc, 0x204) // FIXME should this be stack[0]? assert.equal(r.stack[1], 0x200) // to confirm execute the next cycle r = step() assert.equal(r.i, 0x2FF) r = step() // return; assert.equal(r.sp, 0) assert.equal(r.pc, 0x202) r = step() assert.equal(r.i, 0x2F0) }) }) describe('LD_V_BYTE', function () { it('should store a given byte at a given V register', function () { // Assign 4 to V[1]. let r = run([0x61, 0x04]) assert.equal(r.pc, 0x202) assert.equal(r.v[1], 4) }) }) describe('ADD_V_V', function () { it('should add Vy to Vx and set VF=0 (no carry)', function () { // Assign 4 to V[1], assign 6 to v[2], add V[1] to v[2] and store in v[1] let r = run([0x61, 0x04, 0x62, 0x06, 0x81, 0x24]) assert.equal(r.v[1], 4) r = step() assert.equal(r.v[2], 6) r = step() assert.equal(r.pc, 0x206) assert.equal(r.v[1], 10) assert.equal(r.v[0xF], 0) }) it('should add Vy to Vx and set VF=1 (carry)', function () { // Assign 4 to V[1], assign 6 to v[2], add V[1] to v[2] and store in v[1] let r = run([0x61, 0xF4, 0x62, 0x10, 0x81, 0x24]) r = step() r = step() assert.equal(r.pc, 0x206) // 0xF4 + 0x10 = 260 -> should have 4 in the register + carry flag assert.equal(r.v[1], 4) assert.equal(r.v[0xF], 1) }) }) describe('SE_V_BYTE', function () { it('should skip the next instruction if Vx matches the given byte', function () { // x = 4, y = 6 let r = run([0x61, 0x04, 0x31, 0x04]) r = step() assert.equal(r.pc, 0x206) r = run([0x61, 0x04, 0x31, 0x05]) r = step() assert.equal(r.pc, 0x204) }) }) describe('SNE_V_BYTE', function () { it('should skip the next instruction if Vx does not match the given byte', function () { let r = run([0x61, 0x04, 0x41, 0x04]) r = step() assert.equal(r.pc, 0x204) r = run([0x61, 0x04, 0x41, 0x05]) r = step() assert.equal(r.pc, 0x206) }) }) describe('ADD_V_BYTE', function () { it('should add the given byte to Vx', function () { // add 4 to V[1] which is 4 let r = run([0x61, 0x04, 0x71, 0x04]) r = step() assert.equal(r.v[1], 8) }) }) describe('JP_ADDR', function () { it('should jump to the given address', function () { // 0x1204 - jump at index 204. let r = run([0x12, 0x04, 0xA2, 0xF0, 0xA2, 0xFF]) // stack should be one. pc would be stored as 0x200. Current pc is 0x204. assert.equal(r.sp, 0) assert.equal(r.pc, 0x204) // to confirm execute the next cycle r = step() assert.equal(r.i, 0x2FF) }) }) describe('LD_DT_V', function () { it('should set the delay timer to Vx', function () { let r = run([0x61, 0x04, 0xF1, 0x15]) r = step() assert.equal(r.dt, 0x04) }) }) describe('LD_ST_V', function () { it('should set the sound timer to Vx', function () { let r = run([0x61, 0x04, 0xF1, 0x18]) r = step() assert.equal(r.st, 0x04) }) }) describe('LD_V_DT', function () { it('should set Vx to the value of the delay timer', function () { let r = run([0x61, 0x04, 0xF1, 0x15, 0xFB, 0x07]) r = step() //FIXME decrease_timers() // delay timer will beb 0x03 assert.equal(r.dt, 0x03) r = step() assert.equal(r.v[0xB], 0x03) }) }) describe('SKNP_V', function () { it('should not skip the next instruction if key with the value of Vx is pressed', function () { let r = run([ 0x61, 0x04, // VX = 4 0xE1, 0xA1, // skip if 4 is not pressed 0x62, 0x01, // set v2 to 1 0x62, 0x00 // set V2 to 0 ]) press(4, true) r = step() r = step() assert.equal(r.v[0x2], 0x01) }) it('should skip the next instruction if key with the value of Vx is not pressed', function () { let r = run([ 0x61, 0x04, // VX = 4 0xE1, 0xA1, // skip if 4 is not pressed 0x62, 0x01, // set v2 to 1 0x62, 0x00 // set V2 to 0 ]) r = step() r = step() assert.equal(r.v[0x2], 0x00) }) }) describe('SKP_V', function () { it('should skip the next instruction if key with the value of Vx is pressed', function () { let r = run([ 0x61, 0x04, // VX = 4 0xE1, 0x9E, // skip if 4 is pressed 0x62, 0x01, // set v2 to 1 0x62, 0x00 // set V2 to 0 ]) r = step() r = step() assert.equal(r.v[0x2], 0x01) }) it('should not skip the next instruction if key with the value of Vx is not pressed', function () { let r = run([ 0x61, 0x04, // VX = 4 0xE1, 0x9E, // skip if 4 is pressed 0x62, 0x01, // set v2 to 1 0x62, 0x00 // set V2 to 0 ]) press(4, true) r = step() r = step() assert.equal(r.v[0x2], 0x00) }) }) describe('LD_V_K', function () { it('should wait until a key is pressed and then store the pressed key in Vx', function () { let r = run([ 0xF1, 0x0A, // wait for key and store value in V1 0x00, 0xE0 // dummy instruction ]) r = step() r = step() r = step() r = step() r = step() r = step() // key not pressed so nothing happens. assert.equal(r.pc, 0x200) r = press(5, true) assert.equal(r.pc, 0x202, 'pc') assert.equal(r.v[0x1], 0x05, 'v') }) }) describe('JP_V0_ADDR', function () { it('should jump to the given address + V0', function () { let r = run([ 0x60, 0x0A, // V0 = A 0xB2, 0x00, // set pc = 200 + v0 ]) r = step() assert.equal(r.pc, 0x20A) }) }) describe('LD_B_V', function () { it('should store the BCD representation of Vx in memory locations I, I+1, I+2', function () { // set memory(I) = 0x02 // memory(I+1) = 0x05 // memory(I+2) = 0x05 let r = run([ 0x61, 0xFF, // V0 = FF (255) 0xA2, 0x00, // I = 200 0xF1, 0x33, // set pc = 200 + v0 ]) r = step() r = step() assert.equal(r.ram[0x200], 0x02) assert.equal(r.ram[0x201], 0x05) assert.equal(r.ram[0x202], 0x05) }) }) }) // Tests from https://github.com/DavidJowett/chip8-emulator/blob/master/test/chip8_test.c describe('DavidJowett instruction tests', function () { describe('DRW_V_V', function () { it('should draw one line correctly', function () { let sprite = bin('11111111') let r = loadProgram([ 0xA0, 0x00, // I = 0 (sprite start address) 0x60, sprite, // V[0] = 0b11111111 (sprite) 0x61, 0x00, // V[1] = 0 (draw offset x) 0x62, 0x00, // V[2] = 0 (draw offset y) 0xF0, 0x55, // ram[0] = V[0] 0xD1, 0x21, // draw sprite ram[I] of length 1 at V[1],V[2] ]) r = step(6) assert.deepEqual( sliceRaster(r.raster, [0], [0, 8]), new Uint8Array([1, 1, 1, 1, 1, 1, 1, 1])) assert.equal(r.v[0xF], 0) }) it('should draw two lines correctly', function () { let sprite = bin('10101010') let r = loadProgram([ 0xA0, 0x00, // I = 0 (sprite start address) 0x60, sprite, // V[0] = 0b10101010 (sprite) 0x61, sprite, // V[1] = 0b10101010 (sprite) 0x62, 0x00, // V[2] = 0 (draw offset x) 0x63, 0x01, // V[3] = 1 (draw offset y) 0xF1, 0x55, // ram[0] = V[0], ram[1] = V[1] 0xD2, 0x32, // draw sprite ram[I] of length 2 at V[2],V[3] ]) r = step(7) assert.deepEqual( sliceRaster(r.raster, [1, 3], [0, 8]), new Uint8Array([ 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, ])) assert.equal(r.v[0xF], 0) }) it('should XOR pixels', function () { let sprite = bin('10101010') let r = loadProgram([ 0xA0, 0x00, // I = 0 (sprite start address) 0x60, sprite, // V[0] = 0b10101010 (sprite) 0x61, 0x00, // V[1] = 0 (draw offset x) 0x62, 0x00, // V[2] = 0 (draw offset y) 0xF0, 0x55, // ram[0] = V[0] 0xD1, 0x21, // draw sprite ram[I] of length 1 at V[1],V[2] 0x12, 0x00 // jump back to the start 0x200 ]) r = step(13) console.log(`instruction: ${wasm.getInstructionTypeName()} ${wasm.getInstructionParameters()}`) assert.deepEqual( sliceRaster(r.raster, [0], [0, 8]), new Uint8Array([0, 0, 0, 0, 0, 0, 0, 0])) assert.equal(r.v[0xF], 1) }) it('should draw sprites that overlap byte bounds', function () { let sprite = bin('11111111') let r = loadProgram([ 0xA0, 0x00, // I = 0 (sprite start address) 0x60, sprite, // V[0] = 0b11111111 (sprite) 0x61, sprite, // V[1] = 0b11111111 (sprite) 0x62, 0x04, // V[2] = 4 (draw offset x) 0x63, 0x04, // V[3] = 4 (draw offset y) 0xF1, 0x55, // ram[0] = V[0], ram[1] = V[1] 0xD2, 0x32, // draw sprite ram[I] of length 2 at V[2],V[3] ]) r = step(7) assert.deepEqual( sliceRaster(r.raster, [4, 6], [0, 16]), new Uint8Array([ 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, ])) assert.equal(r.v[0xF], 0) }) it('should wrap lines', function () { let sprite = bin('11111111') let r = loadProgram([ 0xA0, 0x00, // I = 0 (sprite start address) 0x60, sprite, // V[0] = 0b11111111 (sprite) 0x61, sprite, // V[1] = 0b11111111 (sprite) 0x62, 60, // V[2] = 60 (draw offset x) 0x63, 8, // V[3] = 8 (draw offset y) 0xF1, 0x55, // ram[0] = V[0], ram[1] = V[1] 0xD2, 0x32, // draw sprite ram[I] of length 2 at V[2],V[3] ]) r = step(7) assert.deepEqual( sliceRaster(r.raster, [8, 10], [56, 64]), new Uint8Array([ 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, ])) assert.deepEqual( sliceRaster(r.raster, [8, 10], [0, 8]), new Uint8Array([ 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, ])) assert.equal(r.v[0xF], 0) }) it('should wrap start offsets outside the screen', function () { let sprite = bin('11001100') let r = loadProgram([ 0xA0, 0x00, // I = 0 (sprite start address) 0x60, sprite, // V[0] = 0b11001100 (sprite) 0x61, sprite, // V[1] = 0b11001100 (sprite) 0x62, 130, // V[2] = 130 (draw offset x) 0x63, 74, // V[3] = 74 (draw offset y) 0xF1, 0x55, // ram[0] = V[0], ram[1] = V[1] 0xD2, 0x32, // draw sprite ram[I] of length 2 at V[2],V[3] ]) r = step(7) assert.deepEqual( sliceRaster(r.raster, [10, 12], [0, 16]), new Uint8Array([ 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, ])) assert.equal(r.v[0xF], 0) }) it('should wrap around rows', function () { let sprite = bin('11111111') let r = loadProgram([ 0xA0, 0x00, // I = 0 (sprite start address) 0x60, sprite, // V[0] = 0b11111111 (sprite) 0x61, sprite, // V[1] = 0b11111111 (sprite) 0x62, 7, // V[2] = 7 (draw offset x) 0x63, 31, // V[3] = 31 (draw offset y) 0xF1, 0x55, // ram[0] = V[0], ram[1] = V[1] 0xD2, 0x32, // draw sprite ram[I] of length 2 at V[2],V[3] ]) r = step(7) assert.deepEqual( sliceRaster(r.raster, [31], [0, 16]), new Uint8Array([ 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0 ])) assert.deepEqual( sliceRaster(r.raster, [0], [0, 16]), new Uint8Array([ 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0 ])) assert.equal(r.v[0xF], 0) }) }) })
a790cc56aef960837727783712e2757458ce41dd
TypeScript
alphagov/passport-verify
/lib/passport-verify-strategy.ts
2.53125
3
/** * A passport.js strategy for GOV.UK Verify */ /** */ import { Strategy } from 'passport-strategy' import * as express from 'express' import { createSamlForm } from './saml-form' import VerifyServiceProviderClient from './verify-service-provider-client' import { AuthnRequestResponse } from './verify-service-provider-api/authn-request-response' import { TranslatedMatchingResponseBody, TranslatedIdentityResponseBody, Scenario } from './verify-service-provider-api/translated-response-body' import { ResponseBody } from './verify-service-provider-api/response-body' import { ErrorMessage } from './verify-service-provider-api/error-message' /** * Configuration options and callbacks for the `PassportVerifyStrategy`. */ export interface PassportVerifyOptions { } /** * A passport.js strategy for GOV.UK Verify * * ``` * passport.use(passportVerifyStrategy) * ``` * * Users of `passport-verify` should use [[createStrategy]] to create * instances of `PassportVerifyStrategy` rather than calling the constructor directly. */ export class PassportVerifyStrategy extends Strategy { public name: string = 'verify' constructor (private client: VerifyServiceProviderClient, private createUser: (user: TranslatedMatchingResponseBody) => any, private verifyUser: (user: TranslatedMatchingResponseBody) => any, private handleIdentity: (identity: TranslatedIdentityResponseBody) => any, private saveRequestId: (requestId: string, request: express.Request) => any, private loadRequestId: (request: express.Request) => string, private serviceEntityId?: string, private samlFormTemplateName?: string, private levelOfAssurance: ('LEVEL_1' | 'LEVEL_2') = 'LEVEL_2') { super() } async authenticate (req: express.Request, options?: any) { try { await this._handleRequest(req) } catch (error) { this.error(error) } } success (user: any, info: TranslatedMatchingResponseBody | TranslatedIdentityResponseBody) { throw new Error('`success` should be overridden by passport') } fail (challenge: any, status?: number) { throw new Error('`fail` should be overridden by passport') } error (reason: Error) { throw reason } private _handleRequest (req: express.Request) { if (req.body && req.body.SAMLResponse) { return this._translateResponse(req as any) } else { return this._renderAuthnRequest(req as any) } } private async _translateResponse (req: express.Request) { const requestId = this.loadRequestId(req) const samlResponse = (req as any).body.SAMLResponse const response = await this.client.translateResponse(samlResponse, requestId, this.levelOfAssurance, this.serviceEntityId) switch (response.status) { case 200: if ((response.body as ResponseBody).scenario === Scenario.IDENTITY_VERIFIED) { await this._handleSuccessResponse(response.body as TranslatedIdentityResponseBody) } else { await this._handleSuccessMatchingResponse(response.body as TranslatedMatchingResponseBody) } break case 400: case 422: case 500: throw new Error((response.body as ErrorMessage).message) default: throw new Error(`Unexpected status ${response.status}`) } } private async _handleSuccessResponse (responseBody: TranslatedIdentityResponseBody) { switch (responseBody.scenario) { case Scenario.IDENTITY_VERIFIED: await this._handleIdentity(responseBody, this.handleIdentity) break default: this.fail(responseBody.scenario) } } private async _handleSuccessMatchingResponse (responseBody: TranslatedMatchingResponseBody) { switch (responseBody.scenario) { case Scenario.ACCOUNT_CREATION: await this._verifyUser(responseBody, this.createUser) break case Scenario.SUCCESS_MATCH: await this._verifyUser(responseBody, this.verifyUser) break default: this.fail(responseBody.scenario) } } private async _verifyUser (responseBody: TranslatedMatchingResponseBody, fetchUser: (user: TranslatedMatchingResponseBody) => any) { const user = await fetchUser(responseBody) if (user) { this.success(user, responseBody) } else { this.fail(Scenario.REQUEST_ERROR) } return Promise.resolve() } private async _handleIdentity (responseBody: TranslatedIdentityResponseBody, handleIdentity: (identity: TranslatedIdentityResponseBody) => any) { const identity = await handleIdentity(responseBody) if (identity) { this.success(identity, responseBody) } else { this.fail(Scenario.REQUEST_ERROR) } return Promise.resolve() } private async _renderAuthnRequest (request: express.Request): Promise<express.Response> { const authnRequestResponse = await this.client.generateAuthnRequest(this.levelOfAssurance, this.serviceEntityId) if (authnRequestResponse.status === 200) { const authnRequestResponseBody = authnRequestResponse.body as AuthnRequestResponse this.saveRequestId(authnRequestResponseBody.requestId, request) const response = (request as any).res if (this.samlFormTemplateName) { return response.render(this.samlFormTemplateName, { ssoLocation: authnRequestResponseBody.ssoLocation, samlRequest: authnRequestResponseBody.samlRequest }) } else { return response.send(createSamlForm(authnRequestResponseBody.ssoLocation, authnRequestResponseBody.samlRequest)) } } else { const errorBody = authnRequestResponse.body as ErrorMessage throw new Error(errorBody.message) } } } /** * Creates an instance of [[PassportVerifyStrategy]] * * This version of the function should only be used if your service uses the legacy setup. A legacy setup * involves connecting to GOV.UK Verify with a Matching Service Adapter (MSA). * * @param verifyServiceProviderHost The URL that the Verify Service Provider is running on (e.g. http://localhost:50400) * @param createUser A callback that will be invoked when a response with a new user is received. * The `user` object will contain the users' attributes (i.e. firstName, surname etc.). * Your callback should store details of the user in your datastore and return an object representing the user. * @param verifyUser A callback that will be invoked when a response with a matched user is received. * Your callback should look the user up in your datastore using their `pid` (persistent identitfier) * and return an object representing the user. * @param saveRequestId A callback that will be invoked to save the requestId that has been generated by * the verify service provider. Your callback should save the request Id in a secure manner so that it * can be matched against the corresponding SAML response. * @param loadRequestId A callback that will be invoked to load the requestId that has been securely saved * for the user's session. * @param serviceEntityId (Optional) The entityId that will be passed to the Verify Service Provider. This is * only required if the service provider is configured to be multi tenanted. * @param samlFormTemplateName (Optional) The name of a template in your service which will provide the form * used to post an authn request. If present, this will be rendered with the ssoLocation and samlRequest passed * in. Otherwise, a default form will be used. You should use this option if you wish to style the form, which * should be autoposting so only seen if the user has javascript disabled, to match the rest of your service. * @param levelOfAssurance (Optional) LEVEL_1 or LEVEL_2 - defaults to LEVEL_2. The Level of Assurance to * request from the Verify Service Provider and the minimum level to expect in the Response (e.g. if you * specify LEVEL_1 a LEVEL_2 Response would also be permissible). * @returns A strategy to be registered in passport with * ``` * passport.use(passportVerifyStrategy) * ``` */ export function createStrategy ( verifyServiceProviderHost: string, createUser: (user: TranslatedMatchingResponseBody) => object | false, verifyUser: (user: TranslatedMatchingResponseBody) => object | false, saveRequestId: (requestId: string, request: express.Request) => void, loadRequestId: (request: express.Request) => string, serviceEntityId?: string, samlFormTemplateName?: string, levelOfAssurance?: ('LEVEL_1' | 'LEVEL_2') ) { const client = new VerifyServiceProviderClient(verifyServiceProviderHost) return new PassportVerifyStrategy(client, createUser, verifyUser, () => undefined, saveRequestId, loadRequestId, serviceEntityId, samlFormTemplateName, levelOfAssurance) } /** * Creates an instance of [[PassportVerifyStrategy]] * * This version of the function should only be used if your service connects to GOV.UK Verify using the * Verify Service Provider (VSP) without a Matching Service Adapter (MSA). * * @param verifyServiceProviderHost The URL that the Verify Service Provider is running on (e.g. http://localhost:50400) * @param handleIdentity A callback that will be invoked when a response with an identity is received. * The `identity` object will contain the users' attributes (i.e. firstName, surname etc.). * Your callback should store details of the user in your datastore and return an object representing the user. * @param saveRequestId A callback that will be invoked to save the requestId that has been generated by * the verify service provider. Your callback should save the request Id in a secure manner so that it * can be matched against the corresponding SAML response. * @param loadRequestId A callback that will be invoked to load the requestId that has been securely saved * for the user's session. * @param serviceEntityId (Optional) The entityId that will be passed to the Verify Service Provider. This is * only required if the service provider is configured to be multi tenanted. * @param samlFormTemplateName (Optional) The name of a template in your service which will provide the form * used to post an authn request. If present, this will be rendered with the ssoLocation and samlRequest passed * in. Otherwise, a default form will be used. You should use this option if you wish to style the form, which * should be autoposting so only seen if the user has javascript disabled, to match the rest of your service. * @param levelOfAssurance (Optional) LEVEL_1 or LEVEL_2 - defaults to LEVEL_2. The Level of Assurance to * request from the Verify Service Provider and the minimum level to expect in the Response (e.g. if you * specify LEVEL_1 a LEVEL_2 Response would also be permissible). * @returns A strategy to be registered in passport with * ``` * passport.use(passportVerifyStrategy) * ``` */ export function createIdentityStrategy ( verifyServiceProviderHost: string, handleIdentity: (identity: TranslatedIdentityResponseBody) => object | false, saveRequestId: (requestId: string, request: express.Request) => void, loadRequestId: (request: express.Request) => string, serviceEntityId?: string, samlFormTemplateName?: string, levelOfAssurance?: ('LEVEL_1' | 'LEVEL_2') ) { const client = new VerifyServiceProviderClient(verifyServiceProviderHost) return new PassportVerifyStrategy(client, () => undefined, () => undefined, handleIdentity, saveRequestId, loadRequestId, serviceEntityId, samlFormTemplateName, levelOfAssurance) }
7f2873b828db579fe072cd515b21399080a18dac
TypeScript
vinayakvivek/raytracer
/src/utils/perlin.ts
3.03125
3
import { clamp, randomBetween } from "./utils"; import { Point3, Vec3 } from "./vec3"; const count: number = 256; const rands = new Float32Array(count); const randVecs: Vec3[] = []; const px = new Uint8Array(count); const py = new Uint8Array(count); const pz = new Uint8Array(count); const generatePerlinPerm = (p: Uint8Array) => { for (let i = 0; i < count; i++) { p[i] = i; } permute(p, count); }; const permute = (p: Uint8Array, n: number) => { for (let i = n - 1; i > 0; i--) { const target = randomBetween(0, i) ^ 0; [p[i], p[target]] = [p[target], p[i]]; // swap } }; generatePerlinPerm(px); generatePerlinPerm(py); generatePerlinPerm(pz); for (let i = 0; i < count; ++i) { rands[i] = Math.random(); randVecs.push(Vec3.random().normalize()); } const trilinearInterp = (c: Vec3[][][], u: number, v: number, w: number) => { const uu = u * u * (3 - 2 * u); const vv = v * v * (3 - 2 * v); const ww = w * w * (3 - 2 * w); let accum = 0.0; for (let i = 0; i < 2; i++) for (let j = 0; j < 2; j++) for (let k = 0; k < 2; k++) { const weightV = new Vec3(u - i, v - j, w - k); accum += (i * u + (1 - i) * (1 - u)) * (j * v + (1 - j) * (1 - v)) * (k * w + (1 - k) * (1 - w)) * c[i][j][k].dot(weightV); } return accum; }; export const perlinNoise = (p: Point3) => { let u = p.x - Math.floor(p.x); let v = p.y - Math.floor(p.y); let w = p.z - Math.floor(p.z); const i = Math.floor(p.x); const j = Math.floor(p.y); const k = Math.floor(p.z); const c: Vec3[][][] = [ [ [null, null], [null, null], ], [ [null, null], [null, null], ], ]; for (let di = 0; di < 2; di++) for (let dj = 0; dj < 2; dj++) for (let dk = 0; dk < 2; dk++) c[di][dj][dk] = randVecs[ px[(i + di) & 255] ^ py[(j + dj) & 255] ^ pz[(k + dk) & 255] ]; // console.log(c); return trilinearInterp(c, u, v, w); }; export const perlinNoiseTurb = (p: Point3, depth = 7) => { let accum = 0.0; let temp_p = p.clone(); let weight = 1.0; for (let i = 0; i < depth; i++) { accum += weight * perlinNoise(temp_p); weight *= 0.5; temp_p.multScalar(2); } return Math.abs(accum); };
faa9bcf69edb029b995f2a4fce5d2ab6a7bc1b48
TypeScript
xiong35/type-challenges-solutions
/src/0010-TupleToUnion-medium/index.ts
3.40625
3
namespace T0010 { /* 答案 */ type TupleToUnion<T extends readonly any[]> = T[number]; /* 测试 */ type Arr = ["1", "2", "3"]; type A = TupleToUnion<Arr>; // expected to be '1' | '2' | '3' }
d6ca66be5cc9f60c33f4cf19b0fcd06440487774
TypeScript
moulins/kryo
/packages/kryo/src/test/types/codepoint-string.spec.ts
2.890625
3
import chai from "chai"; import unorm from "unorm"; import { CodepointStringType } from "../../lib/codepoint-string.js"; import { runTests, TypedValue } from "../helpers/test.js"; describe("CodepointStringType", function () { describe("basic support", function () { const type: CodepointStringType = new CodepointStringType({maxCodepoints: 500, unorm}); const items: TypedValue[] = [ // Valid items {name: "\"\"", value: "", valid: true}, {name: "\"Hello World!\"", value: "Hello World!", valid: true}, {name: "Drop the bass", value: "ԂЯØǷ Łƕ੬ ɃɅϨϞ", valid: true}, // Invalid items /* tslint:disable-next-line:no-construct */ {name: "new String(\"stringObject\")", value: new String("stringObject"), valid: false}, {name: "0.5", value: 0.5, valid: false}, {name: "0.0001", value: 0.0001, valid: false}, {name: "Infinity", value: Infinity, valid: false}, {name: "-Infinity", value: -Infinity, valid: false}, {name: "NaN", value: NaN, valid: false}, {name: "undefined", value: undefined, valid: false}, {name: "null", value: null, valid: false}, {name: "true", value: true, valid: false}, {name: "false", value: false, valid: false}, {name: "[]", value: [], valid: false}, {name: "{}", value: {}, valid: false}, {name: "new Date()", value: new Date(), valid: false}, {name: "/regex/", value: /regex/, valid: false}, ]; runTests(type, items); }); describe("Ensure valid codepoints with Javascript (UCS2) strings", function () { it("should accept the empty string, when requiring length exactly 0", function () { chai.assert.isTrue(new CodepointStringType({minCodepoints: 0, maxCodepoints: 0, unorm}).test("")); }); it("should accept the string \"a\" (ASCII codepoint), when requiring length exactly 1", function () { chai.assert.isTrue(new CodepointStringType({minCodepoints: 1, maxCodepoints: 1, unorm}).test("a")); }); it("should accept the string \"∑\" (BMP codepoint), when requiring length exactly 1", function () { chai.assert.isTrue(new CodepointStringType({minCodepoints: 1, maxCodepoints: 1, unorm}).test("∑")); }); it("should reject the string \"𝄞\" (non-BMP codepoint), when requiring length exactly 2", function () { chai.assert.isFalse(new CodepointStringType({minCodepoints: 2, maxCodepoints: 2, unorm}).test("𝄞")); }); it("should accept the string \"𝄞\" (non-BMP codepoint), when requiring length exactly 1", function () { chai.assert.isTrue(new CodepointStringType({minCodepoints: 1, maxCodepoints: 1, unorm}).test("𝄞")); }); describe("should reject unmatched surrogate halves", function () { // 𝄞 corresponds to the surrogate pair (0xd834, 0xdd1e) const type: CodepointStringType = new CodepointStringType({maxCodepoints: 500, unorm}); const items: string[] = ["\ud834", "a\ud834", "\ud834b", "a\ud834b", "\udd1e", "a\udd1e", "\udd1eb", "a\udd1eb"]; for (const item of items) { it(JSON.stringify(item), function () { chai.assert.isFalse(type.test(item)); }); } }); it("should reject reversed (invalid) surrogate pairs", function () { chai.assert.isFalse(new CodepointStringType({maxCodepoints: 500, unorm}).test("\udd1e\ud834")); }); }); });
75ad76ab9a996c7e1b1e474f4a840e7b18532afd
TypeScript
darenhart/contact-list-brakets-angular4
/src/app/brackets.component.ts
2.5625
3
import {Component} from '@angular/core'; @Component({ selector: 'brackets', templateUrl: './view/brackets.component.html', styleUrls: ['./scss/brackets.component.scss'], providers: [] }) export class BracketsComponent { brackets: string = ""; isValid: boolean; constructor() { } validate(str): boolean { this.isValid = true; if (str.length <= 1) this.isValid = false; let matchingOpeningBracket, brk; let stack = []; let openingBrackets = ['[', '{', '(']; let closingBrackets = [']', '}', ')']; for (let i = 0; i < str.length; i++) { brk = str[i]; if (closingBrackets.indexOf(brk) > -1) { matchingOpeningBracket = openingBrackets[closingBrackets.indexOf(brk)]; if (stack.length == 0 || (stack.pop() != matchingOpeningBracket)) { this.isValid = false; } } else { stack.push(brk); } } this.isValid = this.isValid ? (stack.length == 0) : this.isValid; return this.isValid; } }
3d862d2ee3b5805e8749418d437d715e9ef9862b
TypeScript
gkniazkov/nest-content-roles-permission
/src/cms/comments/use-comments.decorator.ts
2.578125
3
import { ReflectMetadata, SetMetadata } from '@nestjs/common'; // // export const UseComments = (...args: string[]) => ReflectMetadata('use-comments', args); // // TODO user SetMetadata instead of target.useComment. Metadata can be reflected export const UseComments = (target) => { SetMetadata('use-comments', true); // ReflectMetadata(target, 'use-comments'); // ReflectMetadata(target, 'test'); target.useComment = true; return target; }
3cf6d73b360f66a70578ef220a76df6c5edec300
TypeScript
larilofman/react-rpg
/src/utils/collision.ts
3.046875
3
import { Rectangle } from '../types'; export function collision(rect1: Rectangle, rect2: Rectangle, gap = 0) { return (rect1.pos.x < rect2.pos.x + rect2.size.w + gap && rect1.pos.x + rect1.size.w > rect2.pos.x - gap && rect1.pos.y < rect2.pos.y + rect2.size.h + gap && rect1.pos.y + rect1.size.h > rect2.pos.y - gap); } export function collisionWithAny(rect1: Rectangle, targets: Rectangle[], gap = 0) { for (let i = 0; i < targets.length; i++) { if (collision(rect1, targets[i], gap)) { return true; } } return false; }
1c03339ba6b4722c437e8c4861951256580dfa3f
TypeScript
kinali19/TheVeggieStore
/src/app/product/product.ts
2.515625
3
export interface Product { name: string; price: number; description: string; image: string; quantity:number; inCart:boolean }
b75cbaf6946dd81241a8b6d16681648a5522d452
TypeScript
alfuveam/otwebclient
/modules/effect.ts
2.53125
3
import {Point, Timer} from "./structures"; import {Thing} from "./thing"; import {LightView} from "./lightview"; import {ThingType} from "./thingtype"; import {g_things} from "./thingtypemanager"; import {ThingCategory} from "./constants/const"; export class Effect extends Thing { public static readonly EFFECT_TICKS_PER_FRAME = 75 m_animationTimer: Timer = new Timer(); m_phaseDuration: number; m_id: number; drawEffect(dest: Point, scaleFactor, animate: boolean, offsetX: number = 0, offsetY: number = 0, lightView: LightView = null) { if (this.m_id == 0) return; let animationPhase = 0; if (animate) animationPhase = Math.min((this.m_animationTimer.ticksElapsed() / this.m_phaseDuration), this.getAnimationPhases() - 1); let xPattern = offsetX % this.getNumPatternX(); if (xPattern < 0) xPattern += this.getNumPatternX(); let yPattern = offsetY % this.getNumPatternY(); if (yPattern < 0) yPattern += this.getNumPatternY(); this.rawGetThingType().draw(dest, scaleFactor, 0, xPattern, yPattern, 0, animationPhase, lightView); } setId(id: number) { if (!g_things.isValidDatId(id, ThingCategory.ThingCategoryEffect)) id = 0; this.m_id = id; } getId(): number { return this.m_id; } asEffect(): Effect { return this; } isEffect() { return true; } getThingType(): ThingType { return g_things.getThingType(this.m_id, ThingCategory.ThingCategoryEffect); } rawGetThingType(): ThingType { return g_things.rawGetThingType(this.m_id, ThingCategory.ThingCategoryEffect); } onAppear() { this.m_animationTimer.restart(); this.m_phaseDuration = Effect.EFFECT_TICKS_PER_FRAME; // hack to fix some animation phases duration, currently there is no better solution if (this.m_id == 33) this.m_phaseDuration <<= 2; //g_dispatcher.scheduleEvent([this]() { g_map.removeThing(this); }, this.m_phaseDuration * this.getAnimationPhases()); } }
fcf26cd4ec1e6eb9a30133653709c59a19e153a1
TypeScript
tkryskiewicz/heroes-engine
/packages/heroes-core/src/objects/TradableObject.test.ts
2.734375
3
import { GameObjectData } from "../GameObject"; import { isObjectTradable, isTradableObjectData, TradableObjectData } from "./TradableObject"; describe("isTradableObjectData", () => { it("should return true when tradable object data", () => { const objectData: TradableObjectData = { id: "id", tradable: true, }; const result = isTradableObjectData(objectData); expect(result).toBe(true); }); it("should return false when not tradable object data", () => { const objectData: GameObjectData = { id: "id", }; const result = isTradableObjectData(objectData); expect(result).toBe(false); }); }); describe("isObjectTradable", () => { it("should return true when object is tradable", () => { const objectData: TradableObjectData = { id: "dataId", tradable: true, }; const result = isObjectTradable(objectData); expect(result).toBe(true); }); it("should return false when object is not tradable", () => { const objectData: TradableObjectData = { id: "dataId", tradable: false, }; const result = isObjectTradable(objectData); expect(result).toBe(false); }); });
0b86798c8cfec8468a8c36507bb37296dbecd6ac
TypeScript
MateuszSuder/REST-API-FRONTEND
/src/stores/RootStore.ts
2.640625
3
import {action, makeAutoObservable, observable} from 'mobx'; import { UserStore } from './UserStore'; import {CartStore} from "./CartStore"; export class RootStore { readonly timeout = 3500; user: UserStore; cart: CartStore; snackbarMessages: Array<{ message: string, timestamp: number }> = []; constructor() { this.user = new UserStore(); this.cart = new CartStore(this); makeAutoObservable(this); } pushMessage(msg: string) { const timestamp = Date.now(); const message = msg.substr(0, 250) + (msg.length > 247 ? '...' : ''); if (this.snackbarMessages.some((m) => m.message === message)) { return; } const i = this.snackbarMessages.push({ message, timestamp }); setTimeout(() => { this.removeMessage(i - 1); }, this.timeout + msg.length * 12.5); } removeMessage(i: number) { this.snackbarMessages.splice(i, 1) } }
097992871bd9f43902478883a988d02cf792ddb2
TypeScript
cpsubrian/react-redux-zelda
/complete/src/data/actions.ts
2.6875
3
import {Action} from 'redux'; import {ThunkAction} from 'redux-thunk'; import {ActionTypes, LayerName, TileInstance, StoreState} from '../types'; /** * Action object type definitions. */ export interface SelectTileType extends Action { type: ActionTypes.SELECT_TILE_TYPE; tileType: string; } export interface UnselectTileType extends Action { type: ActionTypes.UNSELECT_TILE_TYPE; } export interface PaintTile extends Action { type: ActionTypes.PAINT_TILE; layer: LayerName; tile: TileInstance; } export interface EraseTile extends Action { type: ActionTypes.ERASE_TILE; layer: LayerName; tile: TileInstance; } export type PaintTileThunk = ThunkAction<void, StoreState, void, PaintTile | EraseTile>; export type RepaintAdjacentTilesThunk = ThunkAction<void, StoreState, void, PaintTile>;
cef7377d7fb0af0ff882720fdf1a26665a8bdbc8
TypeScript
anoblet/my-project
/src/components/Pomodoro/Template.ts
2.609375
3
import { html } from "lit-element"; export default function() { return html` <div id="modes"> ${modes.bind(this)()} </div> <div flex-grow> <grid-component columns="2"> <span ><input name="minutes" type="text" value="${this._minutes}" /></span> <span ><input name="seconds" type="text" value="${this._seconds}" /></span> </grid-component> </div> <div flex-grow> <grid-component> <button-component @click=${this._interval ? this.stop : this.start} >${this._interval ? html` Pause ` : html` Start `}</button-component > </grid-component> </div> `; } const steps = function() { return html` <grid-component columns="8"> ${this.steps.map( (step: any, index: number) => html` <span class=${index === this._currentStep ? "active" : ""} @click=${() => this.selectStep(index)} >${step.label}</span > ` )} </grid-component> `; }; const modes = function() { return html` <grid-component columns="2"> <button-component ?active=${this._currentMode === 0} @click=${() => this.selectMode(0)} >Focus</button-component > <button-component ?active=${this._currentMode === 1} @click=${() => this.selectMode(1)} >Break</button-component > </grid-component> `; };
89564cd065a42145883c26cbbadd589354ced116
TypeScript
HongAnhDo/datn_api
/app/service/vehicle/OptionService.ts
2.671875
3
import { cx_vhc_opt as OptionVehicle } from "../../entities/vehicle/cx_vhc_opt"; import OptionRepository from "../../repository/vehicle/option/OptionRepository"; export default interface IOptionService { getAll(): Promise<Array<OptionVehicle>> getOne(id: number): Promise<OptionVehicle> create(optionVehicle: OptionVehicle):Promise<OptionVehicle> delete(id: number): Promise<OptionVehicle> update(id: number, optionVehicle: OptionVehicle): Promise<OptionVehicle> findByName(name: string): Promise<OptionVehicle> findByPriority(priority: number): Promise<any> createList(list: Array<OptionVehicle>):Promise<Array<OptionVehicle>> findIds(ids: number[]): Promise<OptionVehicle[]> } export default class OptionVehicleService implements IOptionService { private optionRepo:OptionRepository; constructor(){ this.optionRepo = new OptionRepository(); } public async getAll(): Promise<Array<OptionVehicle>> { return await this.optionRepo.getAll(); } public async getOne(id: number): Promise<OptionVehicle> { return await this.optionRepo.getOne(id); } public async create(OptionVehicle: OptionVehicle): Promise<OptionVehicle> { return await this.optionRepo.create(OptionVehicle); } public async delete(id: number): Promise<OptionVehicle> { return await this.optionRepo.delete(id); } public async update(id: number, optionVehicle: OptionVehicle): Promise<OptionVehicle> { return await this.optionRepo.update(id, optionVehicle); } public async findByName(name: string): Promise<OptionVehicle> { return await this.optionRepo.findByName(name) } public async findByPriority(priority: number): Promise<any> { return await this.optionRepo.findByPriority(priority) } public async findIds(ids: number[]): Promise<OptionVehicle[]> { return await this.optionRepo.findIds(ids) } }
ceae664ac0195bf5cafedbf8f22cf1bcc9fce93d
TypeScript
mullet1989/strava-cups
/src/entity/athlete.accesstoken.entity.ts
2.5625
3
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn } from 'typeorm'; import { Athlete } from './athlete.entity'; @Entity('athlete_access_token') export class AthleteAccessToken { @PrimaryGeneratedColumn() id: number; @Column() access_token: string; @Column() refresh_token: string; @ManyToOne(type => Athlete) @JoinColumn({ referencedColumnName: 'athlete_id', name: 'athlete_id' }) athlete: Athlete; @Column() create_datetime: Date; // access_token expires 6 hours after creation @Column() expires_datetime: Date; get isExpired() { return this.expires_datetime < new Date(); } }
6b7e0567f43c0b32f112cedc8ad2fd7a916bd800
TypeScript
ChiriVulpes/weaving-old
/src/Util.ts
3.171875
3
export function padLeft (str: string, len: number, pad: string) { while (str.length < len) str = pad + str; return str; } export function padRight (str: string, len: number, pad: string) { while (str.length < len) str += pad; return str; } export function capitalize (str: string, offset = 0) { return (offset > 0 ? str.slice(0, offset) : "") + str.charAt(offset).toUpperCase() + (offset < str.length - 1 ? str.slice(offset + 1) : ""); } export function tailsMatch (str: string, startsWith: string, endsWith: string) { return str.startsWith(startsWith) && str.endsWith(endsWith); } export function tabbify (str: string, tabs = 1) { return str.replace(/(^|\r?\n)(?!\s*\r?\n)/g, "$1" + "\t".repeat(tabs)); }
c5cd5ae54aa7bc7066296bf357a8f20ce24f1d7d
TypeScript
EnochGao/typescript-design-patterns
/src/structural-pattern/adapter/adapter.ts
3.75
4
// 将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作 /** * 目标(Target)接口:当前系统业务所期待的接口,它可以是抽象类或接口。 适配者(Adaptee)类:它是被访问和适配的现存组件库中的组件接口。 适配器(Adapter)类:它是一个转换器,通过继承或引用适配者的对象,把适配者接口转换成目标接口,让客户按目标接口的格式访问适配者。 */ export interface ITarget { request(): void; } export class Adaptee { specificRequest() { console.log('specificRequest'); }; } // 类适配器 export class ClassAdapter extends Adaptee implements ITarget { request(): void { this.specificRequest(); } } // 对象适配器 export class ObjectAdapter implements ITarget { constructor(private adaptee: Adaptee) { } request(): void { this.adaptee.specificRequest(); } }
f8e14ab07da51e91983f8a84109b20bb69f67741
TypeScript
altoplano/backchannel
/src/crypto.ts
2.75
3
import { Key, DiscoveryKey } from './types'; import { Buffer } from 'buffer'; export type EncryptedProtocolMessage = { cipher: string; nonce: string; }; export async function generateKey(): Promise<Key> { let rawKey = await window.crypto.subtle.generateKey( { name: 'AES-GCM', length: 256, }, true, ['encrypt', 'decrypt'] ); return exportKey(rawKey); } export async function exportKey(key: CryptoKey): Promise<Key> { let raw: ArrayBuffer = await window.crypto.subtle.exportKey('raw', key); return Buffer.from(raw).toString('hex'); } export function importKey(key: Key | Buffer): Promise<CryptoKey> { if (typeof key === 'string') key = Buffer.from(key, 'hex'); return window.crypto.subtle.importKey('raw', key, 'AES-GCM', true, [ 'encrypt', 'decrypt', ]); } export const symmetric = { encrypt: async function ( key: Key, msg: string ): Promise<EncryptedProtocolMessage> { let cryptoKey = await importKey(key); let enc = new TextEncoder(); let plainText = enc.encode(msg); let iv = window.crypto.getRandomValues(new Uint8Array(12)); let ciphertext = await window.crypto.subtle.encrypt( { name: 'AES-GCM', iv: iv, }, cryptoKey, plainText ); return { cipher: Buffer.from(ciphertext).toString('hex'), nonce: Buffer.from(iv).toString('hex'), }; }, decrypt: async function ( key: Key, msg: EncryptedProtocolMessage ): Promise<string> { let cryptoKey = await importKey(key); let decrypted = await window.crypto.subtle.decrypt( { name: 'AES-GCM', iv: Buffer.from(msg.nonce, 'hex'), }, cryptoKey, Buffer.from(msg.cipher, 'hex') ); let dec = new TextDecoder(); return dec.decode(decrypted); }, }; export async function computeDiscoveryKey(key: Key): Promise<DiscoveryKey> { let buf = Buffer.from(key, 'hex'); let hash = await window.crypto.subtle.digest('SHA-256', buf); let disco = Buffer.from(hash).toString('hex'); return disco; }