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
|
|---|---|---|---|---|---|---|
8c074e44a294c9c0c1a3d4db818eb741c6b8672a
|
TypeScript
|
Kjina/thejoeun_typescript_ang2
|
/Animal.ts
| 4.53125
| 5
|
interface Animal{ //? 를 붙이면 선언해도되고 안해도됨
name:string;
age:number;
height:number;
printInfo():void;
}
class Cat implements Animal{
name:string;
age:number;
height:number;
constructor(name:string, age:number){
this.name = name;
this.age = age;
}
printInfo(){
console.log("이름 : " + this.name);
console.log("나이 : " + this.age);
}
printName():void{
console.log("이름 : " + this.name);
}
}
function printSomething(a:Animal){
a.printInfo();
// a.printName(); // -> error ! -> Animal에 printName 이라는 함수가 없음
}
let cc:Cat = new Cat("종혁이",28);
cc.printInfo();
cc.printName();
printSomething(cc);
let cc2:Animal = new Cat("혀기",27);
// cc2.printName(); // -> error ! -> Animal에 printName 이라는 함수가 없음
class Bird implements Animal{
kind:string;
name:string;
age:number;
height:number;
constructor(kind:string){
this.kind = kind;
}
printInfo() :void{
console.log("이 새의 종류는? : " + this.kind);
}
}
/*class Chicken extends Bird{
constructor(kind : string){ // 나 자신은 this, 아빠는 super
super(kind);
}
printInfo() :void{
super.printInfo(); //super 만 붙여서 상위꺼..아빠꺼..가져옴
console.log("내 종류는? 당연히 닭");
console.log("test");
}
}
let c:Animal = new Chicken("닭");
c.printInfo();*/
//위 주석 친거와 동일 소스
class Chicken extends Bird{
constructor(){ // 나 자신은 this, 아빠는 super
super("닭");
}
printInfo() :void{
super.printInfo(); //super 만 붙여서 상위꺼..아빠꺼..가져옴
}
}
class Egg extends Chicken{
}
let c:Animal = new Chicken();
c.printInfo();
c = new Egg();
c.printInfo();
|
8953d73da14f097bc6d147376f44b2d249397f59
|
TypeScript
|
shwoop-ltd/adventure-app-services
|
/src/lambdas/maps/get-challenge-prizes.lambda.ts
| 2.59375
| 3
|
import controller, { ApiResponse, ApiRequest } from '../-helpers/request-handler';
import { Persistence } from '../../core/persistence';
export async function get_challenge_prizes(event: ApiRequest, model: Persistence): Promise<ApiResponse> {
// TODO: Get info about user
const { map, id } = event.path;
if (!map || !id) {
return { code: 400, body: "Need a 'map', and a correct ID for that type." };
}
let challenge_id;
try {
challenge_id = Number.parseInt(id, 10);
} catch (e) {
return { code: 400, body: 'Challenge id must be a number' };
}
const challenge = await model.challenge.get(map, challenge_id.toString());
if (!challenge) {
return { code: 404, body: 'No puzzle with that ID.' };
}
// Ensure we only pass certain information
return {
code: 200,
body: {
claimed: challenge.claimed,
prizes: challenge.prizes,
},
};
}
export const handler = controller(get_challenge_prizes);
|
d759fc31506311b5bf098a3fa1fd1f73a4c1cf69
|
TypeScript
|
Kalayagam/task_manager_web
|
/TaskManagerWeb/src/app/pipes/search-user.pipe.ts
| 2.625
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'searchUser'
})
export class SearchUserPipe implements PipeTransform {
transform(items: any[], searchText: string): any[] {
if(!items) return [];
if(!searchText) return items;
searchText = searchText.toLowerCase();
return items.filter(user => {
return user.firstName.toLowerCase().includes(searchText) || user.lastName.toLowerCase().includes(searchText);
});
}
}
|
122512c41d6be4a45c381766fe36d3c122ce6a4e
|
TypeScript
|
MilanMirkovic/CrowdFunding
|
/client/src/app/models/commentar.model.ts
| 2.640625
| 3
|
import { ProjectInterface } from './project.model';
import { UserInterface } from './user.model';
export interface CommentarInterface{
id?:number;
commentar?:string;
project?:ProjectInterface;
user?:UserInterface;
}
export class Commentar implements CommentarInterface{
id:number;
commentar:string;
project:ProjectInterface;
user:UserInterface;
constructor(c:CommentarInterface){
this.id=c.id;
this.commentar=c.commentar;
this.project=c.project;
this.user=c.user;
}
}
|
980ca69fc96cf0c5e9c689bc7aa1cb52d157a529
|
TypeScript
|
tsnobip/vscode-rescript-relay
|
/src/__tests__/graphqlUtils.test.ts
| 2.859375
| 3
|
import { buildSchema, parse, print } from "graphql";
import { addFieldAtPosition } from "../contextUtilsNoVscode";
const mockSchema = buildSchema(`
type Dog {
id: ID!
name: String!
}
type Cat {
id: ID!
name: String!
}
union Pet = Dog | Cat
"""
A user.
"""
type User {
id: ID!
"""
The age of the user.
"""
age: Int!
bestFriend: User
pets: [Pet!]
}
type Query {
me: User
}
`);
describe("addFieldAtPosition", () => {
it("adds simple fields", () => {
expect(
print(
addFieldAtPosition(
parse(`fragment SomeFragment on User {
id
}`),
"fragment",
// @ts-ignore
mockSchema.getType("User"),
"age",
"fragment"
)
).trim()
).toEqual(
`fragment SomeFragment on User {
id
age
}`
);
});
it("adds simple fields in nested position", () => {
expect(
print(
addFieldAtPosition(
parse(`fragment SomeFragment on User {
id
bestFriend {
id
}
}`),
"fragment_bestFriend",
// @ts-ignore
mockSchema.getType("User"),
"age",
"fragment"
)
).trim()
).toEqual(
`fragment SomeFragment on User {
id
bestFriend {
id
age
}
}`
);
});
it("adds complex fields", () => {
expect(
print(
addFieldAtPosition(
parse(`fragment SomeFragment on User {
id
}`),
"fragment",
// @ts-ignore
mockSchema.getType("User"),
"bestFriend",
"fragment"
)
).trim()
).toEqual(
`fragment SomeFragment on User {
id
bestFriend {
id
}
}`
);
});
it("adds complex fields in union", () => {
expect(
print(
addFieldAtPosition(
parse(`fragment SomeFragment on User {
id
pets {
... on Dog {
id
}
}
}`),
"fragment_pets_Dog",
// @ts-ignore
mockSchema.getType("Dog"),
"name",
"fragment"
)
).trim()
).toEqual(
`fragment SomeFragment on User {
id
pets {
... on Dog {
id
name
}
}
}`
);
});
});
|
3274842e841a14c7aee5935e7a165986fcf05ca7
|
TypeScript
|
DerrickDaKing/gowon
|
/src/commands/Lastfm/Stats/Scrobbles.ts
| 2.6875
| 3
|
import { Message } from "discord.js";
import { Arguments } from "../../../lib/arguments/arguments";
import {
timeRangeParser,
humanizedTimeRangeParser,
parseDate,
} from "../../../helpers/date";
import { dateDisplay, numberDisplay } from "../../../helpers";
import { LastFMBaseCommand } from "../LastFMBaseCommand";
import { standardMentions } from "../../../lib/arguments/mentions/mentions";
import { GowonService } from "../../../services/GowonService";
const args = {
inputs: {
timeRange: { custom: timeRangeParser(), index: -1 },
humanizedTimeRange: { custom: humanizedTimeRangeParser(), index: -1 },
date: {
custom: (string: string) =>
parseDate(
string.trim(),
...GowonService.getInstance().constants.dateParsers
),
index: -1,
},
},
mentions: standardMentions,
} as const;
export default class Scrobbles extends LastFMBaseCommand<typeof args> {
idSeed = "wooah songyee";
aliases = ["s"];
description =
"Shows you how many scrobbles you have over a given time period";
subcategory = "library stats";
usage = ["time period @user"];
arguments: Arguments = args;
async run(message: Message) {
if (message.content.trim() === `${this.prefix}s n s d`) {
await this.send("Gee gee gee gee baby baby baby");
return;
}
let timeRange = this.parsedArguments.timeRange!,
humanTimeRange = this.parsedArguments.humanizedTimeRange!,
date = this.parsedArguments.date;
let { username, perspective } = await this.parseMentions();
let scrobbles = await this.lastFMService.getNumberScrobbles(
username,
date || timeRange.from,
date ? new Date() : timeRange.to
);
let sentMessage = await this.traditionalReply(
`${perspective.plusToHave} ${numberDisplay(
scrobbles,
"scrobble"
).strong()} ${date ? `since ${dateDisplay(date)}` : humanTimeRange}`
);
if (
humanTimeRange === "overall" &&
scrobbles % 25000 === 0 &&
scrobbles > 0
) {
await sentMessage.react("🥳");
}
}
}
|
a0f92216045d15690e27c5adacd6e966a1f7139f
|
TypeScript
|
TautvydasDerzinskas/make-youtube-great-again
|
/src/services/common/drag.service.ts
| 3.015625
| 3
|
class DragService {
public makeElementDraggable(element: HTMLElement, onDragCallback?: (x: string, y: string) => void) {
let initX = 0;
let initY = 0;
let firstX = 0;
let firstY = 0;
element.addEventListener('mousedown', function (e: MouseEvent) {
e.preventDefault();
initX = this.offsetLeft;
initY = this.offsetTop;
firstX = e.pageX;
firstY = e.pageY;
this.addEventListener('mousemove', dragIt, false);
window.addEventListener('mouseup', () => {
element.removeEventListener('mousemove', dragIt, false);
if (typeof onDragCallback !== 'undefined') {
onDragCallback(
(this as HTMLElement).style.left,
(this as HTMLElement).style.top,
);
}
}, false);
}, false);
element.addEventListener('touchstart', function (e: TouchEvent) {
e.preventDefault();
initX = this.offsetLeft;
initY = this.offsetTop;
const touch = e.touches;
firstX = touch[0].pageX;
firstY = touch[0].pageY;
this.addEventListener('touchmove', swipeIt, false);
window.addEventListener('touchend', (event: TouchEvent) => {
event.preventDefault();
element.removeEventListener('touchmove', swipeIt, false);
if (typeof onDragCallback !== 'undefined') {
onDragCallback(
(this as HTMLElement).style.left,
(this as HTMLElement).style.top,
);
}
}, false);
}, false);
function dragIt(e: MouseEvent) {
this.style.left = initX + e.pageX - firstX + 'px';
this.style.top = initY + e.pageY - firstY + 'px';
}
function swipeIt(e: TouchEvent) {
const contact = e.touches;
this.style.left = initX + contact[0].pageX - firstX + 'px';
this.style.top = initY + contact[0].pageY - firstY + 'px';
}
}
}
export default new DragService();
|
0c67880f609fe3f0d8ca592137006b0f59b59c9c
|
TypeScript
|
kamilpraczyk/Crush
|
/src/lessons/tense/beGoingTo/beGoingToOneToThree.ts
| 2.6875
| 3
|
import { RawData } from '../../../types';
import { space, TypeId, id, capital, getNameFemale, getNameMale, getCountry, getPossessiveNameMale, getCity } from '../../helper/constants';
import explenation = require('./explenation');
import _ = require('underscore');
const separator = " ";
const postfix = ".";
const common = [TypeId.oneTwoThree];
const title = "Be going to";
const info = 'Build the correct sentence using "be going to" form.';
const lessons: RawData[] = [
{
id: id(common), title, explenation, info, postfix,
name: separator,
correct: ["I'm", "going to", "take a few exams", "at the end", "of the month"],
}, {
id: id(common), title, explenation, info, postfix: "",
name: separator,
correct: ["Are", "you", "going to", "meet " + getNameFemale(), "tonight?"],
}, {
id: id(common), title, explenation, info, postfix,
name: separator,
correct: ["Get back! The bomb", "is going", "to explode"],
}, {
id: id(common), title, explenation, info, postfix,
name: separator,
correct: ["I am", "going to", getCountry(), "next month"],
}, {
id: id(common), title, explenation, info, postfix,
name: separator,
correct: ["She is", "going to", "be a professional", "dancer", "when she grows up"],
}, {
id: id(common), title, explenation, info, postfix: "",
name: separator,
correct: ["Who are", "you going to", "invite", "to the party?"],
}, {
id: id(common), title, explenation, info, postfix,
name: separator,
correct: ["She", "is", "going to", "spend her vacation in", getCountry()],
}, {
id: id(common), title, explenation, info, postfix,
name: separator,
correct: ["He is", "going to", "spend his holidays in", getCountry()],
}, {
id: id(common), title, explenation, info, postfix: "",
name: separator,
correct: ["Who", "is going", "to make", getPossessiveNameMale(), "birthday cake?"],
}, {
id: id(common), title, explenation, info, postfix,
name: separator,
correct: ["We are", "going to", "take a bottle of orange juice", "to the party"],
}, {
id: id(common), title, explenation, info, postfix,
name: separator,
correct: ["We talked about it", "yesterday", "and I'm", "going to", "quit my job tomorrow"],
}, {
id: id(common), title, explenation, info, postfix,
name: separator,
correct: ["I was", "going to", "call you", "but I lost", "your phone number"],
}, {
id: id(common), title, explenation, info, postfix: "",
name: separator,
correct: ["They we", "going to", "take a bottle of orange juice", "to the party?"],
}, {
id: id(common), title, explenation, info, postfix,
name: separator,
correct: ["We are", "going to", "drive", "all the way", "to " + getCity()],
}, {
id: id(common), title, explenation, info, postfix,
name: separator,
correct: [getNameMale(), "is going to", "meet" + getNameFemale(), "tonight"],
}, {
id: id(common), title, explenation, info, postfix: "",
name: separator,
correct: ["Is", getNameFemale(), "going to", "meet" + getNameMale(), "tomorrow?"],
}, {
id: id(common), title, explenation, info, postfix: "",
name: separator,
correct: ["When", "are we", "going to meet", "each other", "tonight?"],
}, {
id: id(common), title, explenation, info, postfix,
name: separator,
correct: [getNameFemale(), "is", "going to", "begin business school", "next year"],
}, {
id: id(common), title, explenation, info, postfix: "",
name: separator,
correct: ["They", "are", "going to", "meet at " + _.sample([4, 5, 6, 7, 8, 9]) + " p.m."],
}, {
id: id(common), title, explenation, info, postfix,
name: separator,
correct: ["It's so cold! I think", "it is", "going to", "snow"],
}
]
export {
title,
lessons,
}
|
f776f008a9ac3603b6e49e70ddf5ae6dc7114f0c
|
TypeScript
|
Mygi/OnlineStore
|
/src/app/global/contracts/services/storage.provider.ts
| 2.921875
| 3
|
import { JsonConvert, OperationMode, ValueCheckingMode } from 'json2typescript';
import { Type } from '@angular/core';
export interface ISerialisable {
deserialiseJson(json: string, objectType: any);
serialiseJson(data: any);
}
/**
* A (nearly) purely abstract class becuase interfaces are somewaht useless
* in Angular's Dependency Injection strategy. Annoying because I
* can see a great candidate for making a storageProivder implement
* an Observable Interface for allowing subscription based models
* I would want to inject an Observable variant of my storage Accessor
* But I can't - meaning I now need to create some class just for
* Obeservables and build a class Heirarchy around it.
* @export
* @abstract
* @class StorageProvider
*/
export abstract class StorageProvider implements ISerialisable {
jsonConvert: JsonConvert;
constructor() {
this.jsonConvert = new JsonConvert();
}
/**
* Set a key/string value pair
* @param {string} keyName
* @param {string} keyValue
* @returns {boolean}
* @memberof StorageProvider
*/
abstract setKeyValue(keyName: string, keyValue: string): boolean;
/**
* The Object value wrapper for setting client storage dara
*
* @private
* @param {string} keyName
* @param {*} keyValue
* @returns boolean - true if stored otherwise false
* @memberof ClientStorageService
*/
abstract setObjectValue(keyName: string, keyValue: any);
/**
* Gets the client stored key valye
*
* @private
* @param {string} keyName
* @returns {string} Empty string if not found
* @memberof ClientStorageService
*/
abstract getKeyValue(keyName: string): string;
/**
* Returns the JSON parsed object
* May be worth consiudering localised deserialisers
* for each model
* @private
* @param {string} keyName
* @returns {*} null object if not found
* @memberof ClientStorageService
*/
abstract getKeyObjectValue(keyName: string);
/**
* Deletes a key
* @private
* @param {string} keyName
* @returns
* @memberof ClientStorageService
*/
abstract deleteKey(keyName: string);
abstract clearData();
public deserialiseJson(json: string, objectType: any) {
return this.jsonConvert.deserialize(json, objectType);
}
public serialiseJson(data: any) {
this.jsonConvert.serialize(data);
}
public abstract hasKey(keyName: string);
public abstract setDomain(domain: string);
}
|
0cdfd72df7b5bc7ae0c910ef39e3637cd34513b8
|
TypeScript
|
skychx/Toy-Data-Structures
|
/02-LinkedList/ToyLinkedList.ts
| 3.71875
| 4
|
/*
* @Author: skychx
* @Date: 2021-02-03 22:10:00
* @LastEditors: skychx
* @LastEditTime: 2021-06-16 22:56:09
* @FilePath: /Toy-Data-Structures/02-LinkedList/ToyLinkedList.ts
*/
import isEqual from 'lodash/isEqual';
// 这里把 null 也看成树节点
export type Node<T> = LinkedNode<T> | null;
export type E<T> = T | null;
// 链表单节点
export class LinkedNode<T> {
e: E<T>;
next: Node<T>;
constructor(e?: T, next?: Node<T>) {
this.e = e ?? null;
this.next = next ?? null;
}
toString(): string {
return String(this.e);
}
}
export class ToyLinkedList<T> {
private dummyHead: Node<T>;
private size: number;
constructor() {
// dummyHead:虚拟头节点、表头
this.dummyHead = new LinkedNode();
this.size = 0;
}
getSize(): number {
return this.size;
}
isEmpty(): boolean {
return this.size === 0;
}
/** 增 **/
// 在链表的index(0-based)位置添加新的元素 e
// 在链表中不是一个常用的操作
add(index: number, e: T): void {
if(index < 0 || index > this.size) {
throw new Error('Add failed. Illegal index.');
}
let prev = this.dummyHead;
for (let i = 0; i < index; i++) {
prev = prev!.next;
}
let node = new LinkedNode(e);
node.next = prev!.next;
prev!.next = node;
// prev!.next = new LinkedNode(e, prev!.next);
this.size++;
}
addFirst(e: T): void {
this.add(0, e);
}
addLast(e: T): void {
this.add(this.size, e);
}
/** 删 **/
remove(index: number): E<T> {
if (index < 0 || index >= this.size) {
throw new Error('Remove failed. Illegal index.');
}
// 找到待删除节点 retNode 之前的一个节点
let prev = this.dummyHead;
for (let i = 0; i < index; i++) {
prev = prev!.next;
}
let retNode = prev!.next;
prev!.next = retNode!.next;
retNode!.next = null;
this.size--;
return retNode!.e;
}
removeFirst(): E<T> {
return this.remove(0);
}
removeLast(): E<T> {
return this.remove(this.size - 1);
}
removeElement(e: T): void {
let prev = this.dummyHead;
while (prev!.next !== null) {
if (isEqual(prev!.next.e, e)) {
break;
}
prev = prev!.next;
}
if(prev!.next !== null) {
let delNode = prev!.next;
prev!.next = delNode.next;
delNode.next = null;
this.size--;
}
}
/** 查 **/
get(index: number): E<T> {
if (index < 0 || index >= this.size) {
throw new Error('Get failed. Illegal index.');
}
// 注意这里是从索引 0 开始遍历的
let cur = this.dummyHead!.next;
for (let i = 0; i < index; i++) {
cur = cur!.next;
}
return cur!.e;
}
getFirst(): E<T> {
return this.get(0);
}
getLast(): E<T> {
return this.get(this.size - 1);
}
contains(e: T): boolean {
// 从第一个元素开始遍历
let cur = this.dummyHead!.next;
while (cur !== null) {
if (isEqual(cur.e, e)) {
return true;
}
cur = cur.next;
}
return false;
}
/** 改 **/
// 这个操作在链表里并不常见
set(index: number, e: T): void {
if (index < 0 || index >= this.size) {
throw new Error('Set failed. Illegal index.');
}
// 注意这里是从索引 0 开始遍历的
let cur = this.dummyHead!.next;
for (let i = 0; i < index; i++) {
cur = cur!.next;
}
cur!.e = e;
}
/** 格式化 **/
toString(): string {
let res = '\n';
let cur = this.dummyHead!.next;
while (cur !== null) {
res += `${cur} -> `;
cur = cur.next;
}
res += 'NULL';
return res;
}
}
|
9012d40470228745503b831eddbd95708bee5714
|
TypeScript
|
stormhouse/FP-Glossary
|
/src/app/glossary/monad.component.ts
| 3.40625
| 3
|
import { Component } from '@angular/core';
@Component({
selector: 'app-monad',
template: `
<h1>Monad</h1>
<p>A monad is an object with of and chain functions. chain is like map except it un-nests the resulting nested object.</p>
<pre><code class="language-javascript">{{code_one}}</code></pre>
<p>of is also known as return in other functional languages. chain is also known as flatmap and bind in other languages.</p>
`
})
export class MonadComponent {
public code_one: string = [
"// Implementation",
"Array.prototype.chain = function (f) {",
" return this.reduce((acc, it) => acc.concat(f(it)), [])",
"}",
"",
"// Usage",
"Array.of('cat,dog', 'fish,bird').chain((a) => a.split(',')) // ['cat', 'dog', 'fish', 'bird']",
"",
"// Contrast to map",
"Array.of('cat,dog', 'fish,bird').map((a) => a.split(',')) // [['cat', 'dog'], ['fish', 'bird']]"].join('\n');
}
|
4bcb54ed33c89a74a62f9f6266e82274cdaf367e
|
TypeScript
|
SimonNadeau/projet2
|
/Cadriciel/client/src/app/race/event-handler/view-handler.ts
| 2.78125
| 3
|
import { TypingHandler } from "./typing-handler";
import { CameraState } from "../class/camera/cameraState";
const ZOOM_IN_KEYCODE: number = 187; // +
const ZOOM_OUT_KEYCODE: number = 189; // -
const CAMERA_CYCLE_KEYCODE: number = 67; // C
export const VIEWCODES: number[] = [ZOOM_IN_KEYCODE, ZOOM_OUT_KEYCODE, CAMERA_CYCLE_KEYCODE];
export class ViewHandler implements TypingHandler {
public constructor(private _cameras: CameraState) {}
public handleKeyDown(eventCode: number): void {
switch (eventCode) {
case ZOOM_IN_KEYCODE:
this._cameras.zoomIn();
break;
case ZOOM_OUT_KEYCODE:
this._cameras.zoomOut();
break;
case CAMERA_CYCLE_KEYCODE:
this._cameras.nextCamera();
break;
default:
break;
}
}
public handleKeyUp(eventCode: number): void {}
}
|
f87ded937ff55fa294c2a33564aaa68055ac27ad
|
TypeScript
|
adamko034/adona
|
/src/app/core/store/reducers/auth/auth.reducer.spec.ts
| 2.53125
| 3
|
import { authActions } from 'src/app/core/store/actions/auth.actions';
import { userActions } from 'src/app/core/store/actions/user.actions';
import { TeamNameUpdateRequestBuilder } from 'src/app/core/team/model/requests/update-name/team-name-update-request.build';
import { UserTeamBuilder } from 'src/app/core/user/model/user-team/user-team.builder';
import { User } from 'src/app/core/user/model/user/user.model';
import { UserTestBuilder } from 'src/app/utils/testUtils/builders/user-test-builder';
import * as fromReducer from './auth.reducer';
describe('Auth Reducer', () => {
let user: User;
const { reducer, authInitialState } = fromReducer;
beforeAll(() => {
user = UserTestBuilder.withDefaultData().build();
});
describe('an incorrect action', () => {
it('should return the previous state for unknown action when user is not logged in', () => {
// given
const action = {} as any;
// when
const result = reducer(authInitialState, action);
// then
expect(result).toBe(authInitialState);
});
it('should return the previous state for unknown action when user is logged in', () => {
// given
const action = {} as any;
const previousState = { loggedIn: true, user, loginFailed: false };
// when
const result = reducer(previousState, action);
// then
expect(result).toBe(previousState);
});
it('should return default state for undefined action', () => {
// given
const action = {} as any;
// when
const result = reducer(undefined, action);
// then
expect(result).toBe(authInitialState);
});
});
describe('On Login Success', () => {
it('should set user and login failed to null', () => {
const result = reducer({ user: null, loginFailed: true }, authActions.loginSuccess({ user }));
expect({ ...result }).toEqual({ user, loginFailed: null });
});
});
describe('On Logout Success', () => {
it('should set user to null and login failed to null', () => {
const result = reducer({ user, loginFailed: true }, authActions.logoutSuccess());
expect({ ...result }).toEqual({ user: null, loginFailed: null });
});
});
describe('On Load User Success', () => {
it('should set user', () => {
const result = reducer({ user: null, loginFailed: false }, userActions.loadUserSuccess({ user }));
expect({ ...result }).toEqual({ user, loginFailed: false });
});
});
describe('On Login Failed', () => {
it('should set user to null and login failed to true', () => {
const result = reducer({ user, loginFailed: false }, authActions.loginFailed());
expect({ ...result }).toEqual({ user: null, loginFailed: true });
});
});
describe('On Login Clear Error', () => {
it('should set user and login failed to null', () => {
const result = reducer({ user, loginFailed: true }, authActions.loginClearError());
expect({ ...result }).toEqual({ user: null, loginFailed: null });
});
});
describe('On Team Added', () => {
it('should add team to user when user does not have team assigned', () => {
const newTeam = UserTeamBuilder.from('123', 'test team').build();
const userWithoutTeams = { ...user, teams: [] };
const result = reducer({ user: userWithoutTeams, loginFailed: false }, userActions.teamAdded({ team: newTeam }));
expect({ ...result }).toEqual({
loginFailed: false,
user: {
...userWithoutTeams,
teams: [newTeam]
}
});
});
it('should add team to user when user has teams', () => {
const userToChange = UserTestBuilder.withDefaultData()
.withUserTeam(UserTeamBuilder.from('321', 'team').build())
.build();
const newTeam = UserTeamBuilder.from('123', 'test team').build();
const result = reducer({ user: userToChange, loginFailed: false }, userActions.teamAdded({ team: newTeam }));
expect({ ...result }).toEqual({
loginFailed: false,
user: {
...userToChange,
teams: [...userToChange.teams, newTeam]
}
});
});
});
describe('On Update Name Success', () => {
it('should change user name', () => {
const currentState: fromReducer.AuthState = {
loginFailed: false,
user: UserTestBuilder.withDefaultData().build()
};
const result = reducer(currentState, userActions.updateNameSuccess({ newName: 'exampleUser' }));
expect(result).toEqual({ ...currentState, user: { ...currentState.user, name: 'exampleUser' } });
});
});
describe('On Handle Invitation Success', () => {
it('should add User Team and unset Invitation Id', () => {
const action = userActions.handleInvitationSuccess({ teamId: '1', teamName: 'team 1' });
const currentState: fromReducer.AuthState = {
loginFailed: false,
user: UserTestBuilder.withDefaultData().withInvitationId('123').build()
};
const result = reducer(currentState, action);
const expected: fromReducer.AuthState = {
loginFailed: false,
user: UserTestBuilder.withDefaultData().withInvitationId(null).build()
};
expect(result).toEqual(expected);
});
});
describe('On Handle Invitation Reject', () => {
it('should unset user Invitation Id', () => {
const currentState: fromReducer.AuthState = {
loginFailed: false,
user: UserTestBuilder.withDefaultData().withInvitationId('123').build()
};
const action = userActions.handleInvitationReject();
const result = reducer(currentState, action);
const expectedState: fromReducer.AuthState = {
loginFailed: false,
user: UserTestBuilder.withDefaultData().withInvitationId(null).build()
};
expect(result).toEqual(expectedState);
});
});
describe('On Team Name Changed', () => {
it('should update team name', () => {
const userWithTeams = UserTestBuilder.withDefaultData().withDefaultUserTeams(5).build();
const team = userWithTeams.teams[2];
const request = TeamNameUpdateRequestBuilder.from(team.id, 'new great team').build();
const result = reducer({ user: userWithTeams, loginFailed: false }, userActions.teamNameChanged({ request }));
const expectedTeams = [...userWithTeams.teams];
expectedTeams[2].name = 'new great team';
expect({ ...result }).toEqual({
loginFailed: false,
user: {
...userWithTeams,
teams: expectedTeams
}
});
});
});
describe('On Team Deleted', () => {
it('should remove team from user teams array', () => {
const userToChange = UserTestBuilder.withDefaultData().withDefaultUserTeams(5).build();
const currentState: fromReducer.AuthState = {
loginFailed: false,
user: userToChange
};
const teamIdToRemove = userToChange.teams[3].id;
const expectedState: fromReducer.AuthState = {
loginFailed: false,
user: { ...userToChange, teams: [...userToChange.teams].filter((x) => x.id !== teamIdToRemove) }
};
expect(fromReducer.reducer(currentState, userActions.teamDeleted({ id: teamIdToRemove }))).toEqual(expectedState);
});
});
});
|
3f33b17431b61cb91fe791dbbd5e48912ce5912c
|
TypeScript
|
pmh-only/githubStarCalculator
|
/src/utils/ghapi.ts
| 2.578125
| 3
|
import { Config } from '../type/types.ts'
import { ACCEPT, OAUTH_BASEURL, API_BASEURL, USER_AGENT } from '../constant/const.ts'
async function _fetch (url: string, token: string) {
return await fetch (API_BASEURL + url, {
method: 'GET',
headers: new Headers({
Accept: ACCEPT,
'User-Agent': USER_AGENT,
Authorization: 'token ' + token
})
}).then((res) => res.json())
}
export async function getToken (code: string, config: Config): Promise<string | undefined> {
const url = new URL(OAUTH_BASEURL + '/access_token')
url.searchParams.append('code', code)
url.searchParams.append('client_id', config.client_id)
url.searchParams.append('redirect_uri', config.redirect_uri)
url.searchParams.append('client_secret', config.client_secret)
const response = await fetch(url.toString(), {
method: 'POST',
headers: new Headers({ 'Accept': ACCEPT, 'User-Agent': USER_AGENT })
}).then((res) => res.json())
return response.access_token
}
export const getUser = async (token: string) => await _fetch('/user', token)
export async function getRepoList (token: string, orgName?: string) {
const url = new URL(API_BASEURL + (orgName ? '/orgs/' + orgName + '/repos' : '/user/repos'))
url.searchParams.append('type', 'all')
url.searchParams.append('per_page', '100')
const repos = []
let finished = false, page = 1
while (!finished) {
url.searchParams.set('page', String(page))
const res = await _fetch(url.pathname + url.search, token)
if (res.length < 1) finished = true
repos.push(...res)
page++
}
return repos
}
export async function getOrgList (token: string, username?: string) {
const url = new URL(API_BASEURL + (username ? '/users/' + username + '/orgs' : '/user/orgs'))
url.searchParams.append('per_page', '100')
const orgs = []
let finished = false, page = 1
while (!finished) {
url.searchParams.set('page', String(page))
const res = await _fetch(url.pathname + url.search, token)
if (res.length < 1) finished = true
orgs.push(...res)
page++
}
return orgs
}
export async function isCollaborator (repofullname: string, username: string, token: string) {
const url = new URL(API_BASEURL + '/repos/' + repofullname + '/collaborators/' + username)
try {
await _fetch(url.pathname, token)
return true
} catch (_) {
return false
}
}
|
0f3ec398cb2db55a0288c171c5492bbcff40b4f2
|
TypeScript
|
wavesplatform/node-api-js
|
/src/api-node/leasing/index.ts
| 2.671875
| 3
|
import {TLong} from '../../interface';
import request from '../../tools/request';
/**
* GET /leasing/active/{address}
* Get all active leases for an address
*/
export function fetchActive(base: string, address: string, options: RequestInit = Object.create(null)): Promise<Array<ILeaseInfo>> {
return request({base, url: `/leasing/active/${address}`, options});
}
/**
* GET /leasing/info/
* Get lease transactions info.
*/
export function fetchLeasingInfo(base: string, ids: string[], options: RequestInit = Object.create(null)): Promise<Array<ILeaseInfo>> {
const searchParams = `{\"ids\":[${ids.map(id => `\"${id}\"`).join(',')}]}`;
return request({
base, url: `/leasing/info/`, options: {
...options,
body: searchParams,
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}
});
}
export interface ILeaseInfo {
id: string,
originTransactionId: string,
sender: string,
recipient: string,
amount: TLong,
height: number,
status: string,
cancelHeight: number | null,
cancelTransactionId: string | null
}
|
d3e9a5498d3d545b81803342aa487919cf314551
|
TypeScript
|
highhi/react-graphql-firebase
|
/functions/src/app.ts
| 2.515625
| 3
|
import express from 'express'
import helmet from 'helmet'
import logger from 'morgan'
import router from './routes'
import { HttpError } from 'http-errors'
const port = 3001
const app = express()
app.use(helmet())
app.use(logger('combined'))
app.use(express.json())
router(app)
function onError(error: HttpError) {
if (error.syscall !== 'listen') throw error
const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
if (process.env.NODE_ENV === 'development') {
const http = require('http')
const server = http.createServer(app)
server.listen(port, 'localhost');
server.on('error', onError);
server.on('listening', () => {
const addr = server.address()
const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${port}`;
console.log(`Listening on ${bind}`);
})
}
export default app
|
31d26920caa92046eb568a0c00e77a7def16cc33
|
TypeScript
|
Nicolas-Baudvin/memento-front-reworked
|
/src/Components/Signup/utils/index.ts
| 2.625
| 3
|
import { InputName } from "../../Login/Form/types";
const inputs: Array<InputArrayProps> = [
{
type: "email",
label: "Email",
placeholder: "exemple@gmail.com",
tooltip: "L'email doit être valide",
htmlFor: "email",
},
{
type: "password",
label: "Mot de passe",
placeholder: "••••••••",
tooltip: "Le mot de passe doit contenir 8 caractères minimum, 1 minuscule, 1 majuscule, 1 chiffre",
htmlFor: "password",
},
{
type: "password",
label: "Confirmez le mot de passe",
placeholder: "••••••••",
tooltip: "Les mots de passe doivent être identiques",
htmlFor: "confPass",
},
{
type: "username",
label: "Pseudonyme",
placeholder: "PetitHeron85",
tooltip: "Le pseudonyme doit faire 20 caractères maximum.",
htmlFor: "username"
}
];
export interface InputArrayProps {
type: string;
label: string;
placeholder: string;
tooltip: string;
htmlFor: InputName;
}
export default inputs
|
f66a0dc6026978fff48f31d0cb91ff095a4afaad
|
TypeScript
|
rodrigooler/monetify-imagini
|
/src/index.ts
| 2.59375
| 3
|
import { Background } from "./core/constructor/Background";
import { IBackground } from "./core/interface/IBackground";
import { GroupComponent } from "./core/component/GroupComponent";
import { Gender } from "./core/enum/Gender";
import { IUser } from "./core/interface/IUser";
const backgroundExemple: IBackground = {
image: 'resources/tests/applications/01/background.png'
}
const backgroundGroupComponent = new GroupComponent<IBackground>([backgroundExemple]);
const userExemple: IUser = {
name: 'Fabricio',
picture: 'resources/fabricio.jpg',
birthday: new Date('1995-03-30 GMT-0300'),
gender: Gender.Male
};
const background = new Background(undefined, userExemple, backgroundGroupComponent);
console.log(background.user.name)
|
8ff08e81fd16c6682a49205ac81499bf65f01f82
|
TypeScript
|
KovalovIE/cleanArch
|
/modules/splashView/factory/splashScreenFactory.ts
| 2.59375
| 3
|
import { IRepository } from "../../common/stores/defaultRepository/IRepository";
import { MobXRepository } from "../../common/stores/defaultRepository/MobXRepository";
import { ISplashScreenPresenter, SplashScreenPresenter } from "../presenter/splashScreenPresenter";
import { ISplashScreenUseCase, splashScreenUseCase } from "../useCases/splashScreenUseCases";
export interface ISplashScreenFactory {
splashScreenPresenter: ISplashScreenPresenter;
};
export class SplashScreenFactory implements ISplashScreenFactory {
private static instance: SplashScreenFactory;
private isSplashScreenLoaded: IRepository<boolean> = new MobXRepository<boolean>();
private splashScreenUseCases: ISplashScreenUseCase = new splashScreenUseCase(
// set data for process some event on Splash screen
this.isSplashScreenLoaded
);
readonly splashScreenPresenter: ISplashScreenPresenter = new SplashScreenPresenter(
this.isSplashScreenLoaded,
this.splashScreenUseCases,
);
constructor() {
if (SplashScreenFactory.instance) {
return SplashScreenFactory.instance;
}
SplashScreenFactory.instance = this;
};
};
|
cfa330a06f2ee1283fafb1bce5811299492fbbd9
|
TypeScript
|
tomsTestAccount/angular_wp
|
/src/app/_services/rt-form-validators.service.ts
| 2.59375
| 3
|
import { Injectable } from '@angular/core';
import {FormControl, Validators, AbstractControl,FormGroup} from '@angular/forms';
const dbgPrint_Validation = false;
@Injectable()
export class rtFormValidators {
constructor() { }
validateArray(c: FormControl) {
let retValue = null; //= {notValid: true};
if (c != null) {
retValue = (c.value.length == 0) ? {notValid: true} : null;
//console.log("In validateArray, c=",c, ', c.value.length=', c.value.length);
}
if (dbgPrint_Validation) console.log("Idsafsd c=",c, ', c.value.length=', c.value.length);
return retValue
}
validateFileUpload(c: FormControl) {
let retValue = null; // {notValid: true};
//TODO: just a workaround here -> we have to wait for Max Jakob to implement setting of 'null'-value to file-entries to plone-serialization
if (c.value != null) {
if ((c.value.size !== 'undefined') && (c.value.size <= 10))
{
retValue = {notValid: {File: 'was not added'}};
//console.log("In validateFileUpload c=",c, ', c.value=', c.value);
}
//if (dbgPrint_Validation) console.log("In validateArray, c=",c, ',c.value[0].filename =', c.value.filename);
}
//if (dbgPrint_Validation) console.log("In validateFileUpload c=",c, ', c.value=', c.value);
return retValue
}
validateCourseList(c: FormControl) {
let retValue = null; //{notValid: true};
if ( (!c.value) || (!c.value['table']) || (c.value['table'].length == 0))
{
retValue = {notValid:{Course: 'was not added'}};
}
else if ( (c.value['average'] != null) && (c.value['table'].length != 0) ) {
let numValue = parseFloat(c.value['average']);
//retValue = (isNaN(numValue) || (numValue<=0)) ? {notValid: true} : null;
if (isNaN(numValue)) retValue = {notValid:{input: 'is not a number'}};
else if (numValue<=0) retValue = {notValid:{input: 'is less than/equals zero '}};
else retValue = null;
//console.log("In validateCourseList, c=",c, ', retValue=', retValue);
}
if (dbgPrint_Validation) console.log("In validateCourseList, c=",c, ', retValue=', retValue);
return retValue
}
validateEmail(c: FormControl) {
let retValue = null;
let required = c.parent; //validator;
if ( (c.value != null) && (c.value != '') ) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
//console.log(" re.test(c.value)=", re.test(c.value));
retValue = re.test(c.value) ? null : {notValid:{email: ' wrong email address notation'}} ;
}
if (dbgPrint_Validation) console.log("In validateEmail, c=",c, ', retValue=', retValue, required);
return retValue
}
validateNumberNotZero(c: FormControl) {
let retValue = null; //= {notValid: true};
if ( (c.value != null) ) {
let numValue = parseFloat(c.value);
if (isNaN(numValue)) retValue = {notValid:{input: 'is not a number'}};
else if (numValue<=0) retValue = {notValid:{input: 'is less than/equals zero '}};
else retValue = null;
//console.log("In validateCourseList, c=",c, ', retValue=', retValue);
}
if (dbgPrint_Validation) console.log("In validateNumberNotZero, c=",c, ', retValue=', retValue);
return retValue
}
validatePasswordConfirm(cConfirm: FormControl) {
let retValue = {equal: false};
if (cConfirm != null) {
//console.log("c=",c);
let cPwd = cConfirm.root.get('password');
if (cPwd != null)
{
//retValue = (cPwd.value === cCPwd.value) ? null : {equal: false} ;
if (cPwd.value === cConfirm.value)
{
console.log("cPwd=",cPwd.value);
console.log("cCPwd=",cConfirm.value);
retValue = null;
}
}
}
return retValue;
}
validateGroup_CheckboxEnabled(group: FormGroup) {
/*
const range = group.controls[0].find(r => r.id === Number(group.value.range));
if(range && (group.value.specificValue < range.min || group.value.specificValue > range.max)) {
return {
outsideRange: true
};
}
*/
};
/*
private userDataUrl = 'app/userData';
constructor(private http: Http) { }
getUserModels(): Promise<UserModel[]> {
//return Promise.resolve(HEROES);
return this.http.get(this.userDataUrl)
.toPromise()
.then(response => response.json().data as UserModel[])
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
//slow connection mock
getUserModelSlowly(): Promise<UserModel[]> {
return new Promise<UserModel>(resolve =>
setTimeout(resolve, 2000)) // delay 2 seconds
.then(() => this.getUserModels());
}
getUserModel(uid : number): Promise<UserModel> {
return this.getUserModels().then(models => models.find(model => model.uid === uid));
}
private headers = new Headers({'Content-Type': 'application/json'});
update(model: UserModel): Promise<UserModel> {
const url = `${this.userDataUrl}/${model.uid}`;
return this.http.put(url, JSON.stringify(model), {headers: this.headers})
.toPromise()
.then(() => model)
.catch(this.handleError);
}
/*
create(name: string, power:string,state: string): Promise<UserModel> {
return this.http
.post(this.heroesUrl, JSON.stringify({name: name, power: power, state: state}), {headers: this.headers})
.toPromise()
.then(res => res.json().data)
.catch(this.handleError);
}
*/
/*
delete(uid: number): Promise<void> {
const url = `${this.userDataUrl}/${uid}`;
return this.http.delete(url, {headers: this.headers})
.toPromise()
.then(() => null)
.catch(this.handleError);
}
*/
}
|
679eb5107a6ad957a391fdcfa86cd08e37a2e0fc
|
TypeScript
|
claranceliberi/ts-hub
|
/01. basics/03. non-exception-failures/legitimate-bugs/logicErrors.ts
| 3.296875
| 3
|
const value = Math.random() < 0.5 ? "a" : "b";
if (value !== "a") {
// ...
} else if (value === "b") {
// This condition will always return 'false' since the types '"a"' and '"b"' have no overlap.
// Oops, unreachable
}
|
95deb8f3100cb9fc0171445f12dc02eed0de7f99
|
TypeScript
|
uStudioTeam/ts4ocds
|
/packages/utils/src/initializable/initializer.d.ts
| 2.890625
| 3
|
/**
* @packageDocumentation
* @module Utilities.Initializable
*/
/**
* A type that picks all properties from an object that are not methods.
*/
export type Initializer<T> = Pick<
T,
NonNullable<{ [K in keyof T]: T[K] extends (...args: any[]) => any ? never : K }[keyof T]>
>;
|
cf5f3f734538f012e1d43984f73183615788ebee
|
TypeScript
|
singtolee/CONSOLE
|
/src/app/editable-number/editable-number.component.ts
| 2.71875
| 3
|
import { Component, Input, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'
const VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(()=>EditableNumberComponent),
multi: true
}
@Component({
selector: 'app-editable-number',
templateUrl: './editable-number.component.html',
providers: [VALUE_ACCESSOR],
styleUrls: ['./editable-number.component.css']
})
export class EditableNumberComponent implements ControlValueAccessor {
@Input() label : string = "Enter value here"
@Input() required: boolean = true
private _value : string = ""
private preValue : string = ""
public editing : boolean = false
public onChange : any = Function.prototype
public onTouched: any = Function.prototype
get value():any {
return this._value
}
set value(v: any){
if(v !== this._value){
this._value = v
this.onChange(v)
}
}
writeValue(value: any){
this._value = value
}
public registerOnChange(fn: (_: any)=>{}):void {
this.onChange = fn
}
public registerOnTouched(fn: ()=>{}):void {
this.onTouched = fn
}
onBlur($event: Event){
this.editing = false
if(this._value ==""){
this._value = "NO VALUE AVAILABLE"
}
}
beginEdit(value){
this.preValue = value
this.editing = true
}
}
|
a65febd2dc9c22aaf2d71f847aba901b5a5b5a75
|
TypeScript
|
softmarshmallow/uguu-api
|
/example/index.ts
| 2.875
| 3
|
import { upload } from "../lib"
import * as fs from "fs"
const TEST_TXT_FILE_CONTENT = `# Read Me !!`
const TEST_TXT_FILE_NAME = `file.txt`
async function example() {
try {
// const file = Buffer.from(TEST_TXT_FILE_CONTENT)
const file = fs.createReadStream('./example/file.txt')
// const blob = await fetch(TEST_TXT_FILE_CONTENT).then(res => res.blob());
// const file = new Blob([TEST_TXT_FILE_CONTENT], { type: "text/plain" })
const res = upload(TEST_TXT_FILE_NAME, file)
res.then((d) => {
console.log(d)
})
} catch (e) {
console.error(e)
}
}
example()
|
f1fd952c72e1cef9b0bab0d315b83c213dc996a0
|
TypeScript
|
raffecat/manglr-v0
|
/src/ast.ts
| 2.875
| 3
|
'use strict';
// abstract types.
export type AttrMap = Map<string, string>;
export interface Node {
tag: string;
}
export interface Element extends Node {
attribs: AttrMap;
children: Node[];
}
// concrete HTML types.
export class Fragment implements Element {
readonly tag: string = '#document';
attribs: AttrMap = new Map();
children: Node[] = [];
hasDocType: boolean = false;
}
export class Tag implements Element {
children: Node[] = [];
sheet: StyleSheet|null = null; // optional style-sheet to inline.
elide: boolean = false;
constructor(public tag:string, public attribs:AttrMap=new Map()) {}
}
export class Text implements Node {
readonly tag = '#text';
constructor(public text:string, public where:string, public markup:boolean=false) {}
}
// concrete template types.
export type TextTPlNode = Text | Expression;
export type BindingNode = Text | Expression | TextTemplate;
export type BindingMap = Map<string, BindingNode>;
export type TplNode = Text | Expression | TplTag | CustomTag | TplCond | TplRepeat;
export type DefnMap = Map<string, TagDefn>;
export class Expression {
path: string[];
constructor(public source:string, public where:string) {
this.path = source.split('.');
}
}
export class TextTemplate {
constructor(public nodes:TextTPlNode[], public where:string) {}
}
export interface Loader {
filename: string;
usedFrom: string[];
}
export class StyleSheet implements Loader {
fromComponent: boolean = false;
usedFrom: string[] = [];
ast: CSSTree.Node|null = null; // parsed csstree AST.
sheetsImported: StyleSheet[] = [];
constructor(public filename:string, usedIn:string) {
this.usedFrom.push(usedIn);
}
}
export class Template implements Loader {
// contains multiple TagDefn parsed from a single template (file)
isMain: boolean = false;
usedFrom: string[] = [];
tags: DefnMap = new Map();
tplsImported: Template[] = [];
sheetsImported: StyleSheet[] = [];
inlineFontFace: Tag|null = null; // first style tag encountered with inline-fonts.
componentStyles: Tag|null = null; // first style tag encountered with component-styles.
testDataUrl: string = '';
constructor(public filename:string, usedIn:string='') {
if (usedIn) this.usedFrom.push(usedIn);
}
}
export class TagDefn {
// a custom tag definition within a Template.
nodes: TplNode[] = [];
outTag: string = '';
params: AttrMap = new Map();
tplsImported: Template[] = []; // templates imported inside this component.
componentsUsed: TagDefn[] = []; // components used in this component (NB. cannot be conditional!)
metaTags: Tag[] = []; // <meta> within the component.
linkTags: Tag[] = []; // <link> within the component.
styleTags: Tag[] = []; // <style> within the component.
headScripts: Tag[] = []; // <script move-to-head> within the component.
footScripts: Tag[] = []; // <script move-to-body> within the component.
constructor(public tpl:Template, public tagName:string, public rootNodes:Node[]=[], public anyAttrib:boolean=false) {
}
}
export class TplTag {
// a standard DOM node within a TagDefn.
constructor(
readonly tag:string,
readonly binds:BindingMap,
readonly children:TplNode[]) {}
}
export class CustomTag {
// an instance of a TagDefn for a custom tag.
constructor(
readonly defn: TagDefn,
readonly binds: BindingMap,
readonly capture: TplNode[]) {}
}
export class TplCond {
// a conditional group of nodes.
constructor(
readonly condExpr: Expression,
readonly children: TplNode[]) {}
}
export class TplRepeat {
// a repeating group of nodes.
constructor(
readonly bindName: string,
readonly eachExpr: Expression,
readonly children: TplNode[]) {}
}
|
92bc62d3ab157fd9c9ffb8ec17c2989b9f346819
|
TypeScript
|
scaleapi/scaleapi-node
|
/src/core/schemas/builders/object/property.ts
| 2.828125
| 3
|
import { Schema } from "../../Schema";
export function property<RawKey extends string, RawValue, ParsedValue>(
rawKey: RawKey,
valueSchema: Schema<RawValue, ParsedValue>
): Property<RawKey, RawValue, ParsedValue> {
return {
rawKey,
valueSchema,
isProperty: true,
};
}
export interface Property<RawKey extends string, RawValue, ParsedValue> {
rawKey: RawKey;
valueSchema: Schema<RawValue, ParsedValue>;
isProperty: true;
}
export function isProperty<O extends Property<any, any, any>>(maybeProperty: unknown): maybeProperty is O {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
return (maybeProperty as O).isProperty;
}
|
e5167081af02ecd11efaa80422b7309018e6a39d
|
TypeScript
|
agilearchitects/intra
|
/src/shared/dto/update-time.dto.ts
| 2.84375
| 3
|
import { jsonType } from "@agilearchitects/server";
// DTO's
import { IDictionaryDTO } from "./dictionary.dto";
export interface IUpdateTimeDTO {
id: number;
taskId: number;
from: string;
to?: string;
comment: string;
userId: number;
tags?: (string | number)[];
rate?: number;
}
export class UpdateTimeDTO implements IUpdateTimeDTO {
public static parseFromRequest(object: IDictionaryDTO<jsonType>): UpdateTimeDTO {
if (typeof object.id !== "number" ||
typeof object.taskId !== "number" ||
typeof object.from !== "string" ||
(typeof object.to !== "string" || object.to !== undefined) ||
typeof object.comment !== "string" ||
typeof object.userId !== "number" ||
(object.tags !== undefined && !(object.tags instanceof Array)) ||
(object.rate !== undefined && typeof object.rate !== "number")
) {
throw new Error("Unable to parse");
}
return new UpdateTimeDTO(
object.id,
object.taskId,
object.from,
object.to !== undefined ? object.to : undefined,
object.comment,
object.userId,
object.tags !== undefined ? object.tags.map((tag: jsonType) => {
if (typeof tag !== "string" && typeof tag !== "number") {
throw new Error("Unable to parse");
}
return tag;
}) : undefined,
object.rate,
);
}
public static parse(object: IUpdateTimeDTO): UpdateTimeDTO {
return new UpdateTimeDTO(
object.id,
object.taskId,
object.from,
object.to !== undefined ? object.to : undefined,
object.comment,
object.userId,
object.tags,
object.rate,
);
}
public constructor(
public readonly id: number,
public readonly taskId: number,
public readonly from: string,
public readonly to: string | undefined,
public readonly comment: string,
public readonly userId: number,
public readonly tags?: (string | number)[],
public readonly rate?: number,
) { }
public serialize(): IUpdateTimeDTO {
return {
id: this.id,
taskId: this.taskId,
from: this.from,
...(this.to !== undefined ? { to: this.to } : undefined),
comment: this.comment,
userId: this.userId,
...(this.tags !== undefined ? { tags: this.tags } : undefined),
...(this.rate !== undefined ? { rate: this.rate } : undefined),
};
}
}
|
7a2c7ae699468554d0e3d4f12373112442a336df
|
TypeScript
|
emberjs/ember.js
|
/packages/@ember/-internals/glimmer/lib/helpers/helper.ts
| 3.15625
| 3
|
/**
@module ember
*/
/**
Use the `{{helper}}` helper to create contextual helper so
that it can be passed around as first-class values in templates.
```handlebars
{{#let (helper "join-words" "foo" "bar" separator=" ") as |foo-bar|}}
{{!-- this is equivalent to invoking `{{join-words "foo" "bar" separator=" "}}` --}}
{{foo-bar}}
{{!-- this will pass the helper itself into the component, instead of invoking it now --}}
<MyComponent @helper={{helper foo-bar "baz"}} />
{{!-- this will yield the helper itself ("contextual helper"), instead of invoking it now --}}
{{yield foo-bar}}
{{/let}}
```
### Arguments
The `{{helper}}` helper works similarly to the [`{{component}}`](./component?anchor=component) and
[`{{modifier}}`](./modifier?anchor=modifier) helper:
* When passed a string (e.g. `(helper "foo")`) as the first argument,
it will produce an opaque, internal "helper definition" object
that can be passed around and invoked elsewhere.
* Any additional positional and/or named arguments (a.k.a. params and hash)
will be stored ("curried") inside the definition object, such that, when invoked,
these arguments will be passed along to the referenced helper.
@method helper
@for Ember.Templates.helpers
@public
@since 3.27.0
*/
|
106c56ecf1c3dd45f17c25d57d2a2ff060eda66b
|
TypeScript
|
porizi/mini-cms
|
/src/lib/cms/models.ts
| 2.890625
| 3
|
export interface ICmsDataDbModel {
_id : string
error?: string // Useful for checking if the mongodb operation caused an error
}
export class IRequestResponseStatus {
static OK :string = 'OK';
static ERROR:string = 'ERROR';
}
export interface IRequestResponse {
data? : any // Data to be sent back to the client (if any)
error?: string // Error explanation (if any)
status: string // Statuses defined in 'IRequestResponseStatus'
}
export interface ICmsContext {
cmsData: ICmsDataDbModel // CMS data
onCmsDataUpdate: (data: any, path: string[]) => void // Callback to execute when a particular CMS
// data needs to be updated
}
|
809936cb4ce02332ee6d55b1fb9a5a11df56b2d1
|
TypeScript
|
Mercerenies/calculator-ts
|
/src/Numerical/Complex.ts
| 3.578125
| 4
|
import NumberLike from './NumberLike'
import Floating from './Floating'
export default class Complex implements NumberLike<Complex> {
readonly real: number;
readonly imag: number;
constructor(real: number, imag: number) {
this.real = real;
this.imag = imag;
}
add(that: Complex): Complex {
return new Complex(this.real + that.real, this.imag + that.imag);
}
negate(): Complex {
return new Complex(- this.real, - this.imag);
}
sub(that: Complex): Complex {
return this.add(that.negate());
}
mul(that: Complex): Complex {
return new Complex(this.real * that.real - this.imag * that.imag,
this.real * that.imag + this.imag * that.real);
}
conj(): Complex {
return new Complex(this.real, - this.imag);
}
div(that: Complex): Complex {
let num = this.mul(that.conj());
let den = that.real * that.real + that.imag * that.imag;
return new Complex(num.real / den, num.imag / den);
}
recip(): Complex {
return new Complex(1, 0).div(this);
}
abs(): Floating {
return new Floating(Math.sqrt(this.real * this.real + this.imag * this.imag));
}
exp(): Complex {
const c = Math.exp(this.real);
const re = Math.cos(this.imag);
const im = Math.sin(this.imag);
return new Complex(re * c, im * c);
}
ln(): Complex {
const re = Math.log(this.abs().value);
const im = Math.atan2(this.imag, this.real);
return new Complex(re, im);
}
pow(that: Complex): Complex {
return (that.mul(this.ln())).exp();
}
get rectangular(): [number, number] {
return [this.real, this.imag];
}
eq(that: Complex): boolean {
return (
(new Floating(this.real).eq(new Floating(that.real))) &&
(new Floating(this.imag).eq(new Floating(that.imag)))
);
}
toString(): string {
return "(" + this.real.toString() + "," + this.imag.toString() + ")";
}
static zero(): Complex {
return new Complex(0, 0);
}
}
export function complex(real: number, imag: number): Complex {
return new Complex(real, imag);
}
|
9fd62e0b7cd2e4f77da3a57d541971b3bf46641c
|
TypeScript
|
poop9/poop-server
|
/src/models/User.ts
| 2.59375
| 3
|
import { Column, Entity, PrimaryGeneratedColumn, Unique } from 'typeorm';
import { Base } from './Base';
@Entity()
@Unique(['uuid'])
export class User extends Base {
@PrimaryGeneratedColumn()
id!: number;
@Column({ length: 50 })
nickname!: string;
@Column()
uuid!: string;
}
|
89cc80e79d482c682b7abc3d009e0487b03ca501
|
TypeScript
|
kipprice/toolkip.ts
|
/src/typescript/html/_interfaces.ts
| 3.296875
| 3
|
namespace KIP {
//..........................................
//#region INTERFACES AND TYPES
export type IAttribute = IKeyValPair<string> | string | number;
export interface IAttributes {
[key: string]: IAttribute;
}
export type IChild = StandardElement | IElemDefinition | Drawable;
export type IChildren = IChild[];
export interface IClasses {
[key: string]: IClassDefinition | IKeyValPair<string>[];
}
export interface IClassDefinition {
[key: string]: string;
}
export type IKeyedElems = IDictionary<StandardElement | Drawable>;
/**
* IElemDefinition
* ----------------------------------------------------------------------------
* Interface for how elements are created
* @version 1.3.0
*/
export interface IElemDefinition<T extends IKeyedElems = IKeyedElems> {
/** unique key for this element; used to return an element */
key?: keyof T;
/** Id to use for the element */
id?: string;
/** CSS class to use for the element */
cls?: string | IClasses;
/** the type of HTML element we are creating */
type?: "div" | "span" | "input" | "select" | "option" | "textarea" | "li" | "ul" | "p" | "br" | string;
/** content that should be added to the element */
content?: string;
/** content that should specifically be added before the children of this element */
before_content?: string;
/** content that should specifically be added after the children of this element */
after_content?: string;
/** any additional attributes that should be applied to this element */
attr?: IAttributes;
/** any specific styles to apply to this element */
style?: Styles.TypedClassDefinition;
/** any children that should be added for this element */
children?: IChildren;
/** the parent element that this should be added to */
parent?: StandardElement;
/** allow callers to add event listeners while creating elements */
eventListeners?: IEventListeners;
/** if we're creating a namespaced element, allow for specifying it */
namespace?: string;
/** determine whether this element should be able to receive focus */
focusable?: boolean;
/** allow HTML contents to be bound dynamically */
boundContent?: BoundEvalFunction<string>;
/** builds a custom tooltip in lieu of the standard title */
tooltip?: string;
/** allow the function to spin up a drawable instead of an element (will still apply classes & the like) */
drawable?: IConstructor<Drawable>;
}
/**
* keep track of event listeners of a particular type
*/
export type IEventListeners = {
[key in keyof WindowEventMap]?: EventListener;
}
}
|
86ab090e645caef39f92338737be559fe53843d9
|
TypeScript
|
juanpms2/test-integracion-continua-ejemplo
|
/src/pages/members/list/selectors.spec.ts
| 2.578125
| 3
|
import {
getMembersState,
getMembersList,
getMembersListVM,
getServerError,
} from './selectors';
import { State } from '../../reducers';
import * as mappers from './mappers';
import { Member } from './viewModel';
describe('Members selectors', () => {
describe('getMebersState', () => {
it('should return mebersState from state', () => {
// Arrange
const state: State = {
membersState: {
members: [],
serverError: null,
},
};
// Act
const result = getMembersState(state);
// Assert
expect(result).toBe(state.membersState);
});
});
describe('getMembersList', () => {
it('should return the expected members list from mebersState', () => {
// Arrange
const state: State = {
membersState: {
members: [],
serverError: null,
},
};
// Act
const result = getMembersList(state);
// Assert
expect(result).toBe(state.membersState.members);
});
});
describe('getMembersListVM', () => {
it('should return the expected members list from mebersState', () => {
// Arrange
const state: State = {
membersState: {
members: [
{ id: 1, login: 'member 1', avatar_url: 'avatar 1' },
{ id: 1, login: 'member 2', avatar_url: 'avatar 2' },
],
serverError: null,
},
};
const membersVM: Member[] = [
{ id: 1, name: 'member 1', avatarUrl: 'avatar 1' },
{ id: 1, name: 'member 2', avatarUrl: 'avatar 2' },
];
const mapMemberListModelToVM = jest
.spyOn(mappers, 'mapMemberListModelToVM')
.mockReturnValue(membersVM);
// Act
const result = getMembersListVM(state);
// Assert
expect(result).toBe(membersVM);
expect(mapMemberListModelToVM).toHaveBeenCalled();
});
it('should return the same members when called multiple times', () => {
// Arrange
const state: State = {
membersState: {
members: [
{ id: 1, login: 'member 1', avatar_url: 'avatar 1' },
{ id: 1, login: 'member 2', avatar_url: 'avatar 2' },
],
serverError: null,
},
};
const membersVM: Member[] = [
{ id: 1, name: 'member 1', avatarUrl: 'avatar 1' },
{ id: 1, name: 'member 2', avatarUrl: 'avatar 2' },
];
const mapMemberListModelToVM = jest
.spyOn(mappers, 'mapMemberListModelToVM')
.mockReturnValue(membersVM);
// Act
const result1 = getMembersListVM(state);
const result2 = getMembersListVM(state);
const result3 = getMembersListVM(state);
const result4 = getMembersListVM(state);
// Assert
expect(result1).toBe(membersVM);
expect(mapMemberListModelToVM).toHaveBeenCalledTimes(1);
});
});
describe('getServerError', () => {
it('should return serverError from memberState', () => {
// Arrange
const state: State = {
membersState: {
members: [],
serverError: null,
},
};
// Act
const result = getServerError(state);
// Assert
expect(result).toBe(state.membersState.serverError);
});
});
});
|
5f5d057945168a1473f92d920d173711d95dfd00
|
TypeScript
|
evollu/typesafe-actions
|
/src/create-action.ts
| 3.21875
| 3
|
import { StringType, ActionCreator } from './types';
import { action } from './action';
/**
* @description typesafe action-creator factory
*/
export function createAction<
T extends StringType,
AC extends ActionCreator<T> = () => { type: T }
>(
type: T,
creatorHandler?: (
action: <P = void, M = void>(
payload?: P,
meta?: M
) => P extends void
? { type: T }
: M extends void
? { type: T; payload: P }
: { type: T; payload: P; meta: M }
) => AC
): AC {
const actionCreator: AC =
creatorHandler == null
? ((() => action(type)) as AC)
: creatorHandler(action.bind(null, type));
return Object.assign(actionCreator, { getType: () => type });
}
|
4e0abfef64543e343aacc4c5b0a138b20fff3aef
|
TypeScript
|
kennylerma/assemblyscript
|
/src/compiler.ts
| 2.59375
| 3
|
import {
compileCall as compileBuiltinCall,
compileGetConstant as compileBuiltinGetConstant
} from "./builtins";
import {
PATH_DELIMITER
} from "./constants";
import {
DiagnosticCode,
DiagnosticEmitter
} from "./diagnostics";
import {
Module,
MemorySegment,
ExpressionRef,
UnaryOp,
BinaryOp,
NativeType,
FunctionTypeRef,
FunctionRef,
ExpressionId
} from "./module";
import {
Program,
ClassPrototype,
Class,
Element,
ElementKind,
Enum,
FieldPrototype,
Field,
FunctionPrototype,
Function,
Global,
Local,
Namespace,
Parameter,
EnumValue,
Property,
VariableLikeElement
} from "./program";
import {
Token
} from "./tokenizer";
import {
Node,
NodeKind,
TypeNode,
Source,
Statement,
BlockStatement,
BreakStatement,
ClassDeclaration,
ContinueStatement,
DeclarationStatement,
DoStatement,
EmptyStatement,
EnumDeclaration,
EnumValueDeclaration,
ExportMember,
ExportStatement,
ExpressionStatement,
FunctionDeclaration,
ForStatement,
IfStatement,
ImportStatement,
InterfaceDeclaration,
ModifierKind,
NamespaceDeclaration,
ReturnStatement,
SwitchCase,
SwitchStatement,
ThrowStatement,
TryStatement,
VariableLikeDeclarationStatement,
VariableDeclaration,
VariableStatement,
WhileStatement,
Expression,
AssertionExpression,
BinaryExpression,
CallExpression,
ElementAccessExpression,
FloatLiteralExpression,
IdentifierExpression,
IntegerLiteralExpression,
LiteralExpression,
LiteralKind,
NewExpression,
ParenthesizedExpression,
PropertyAccessExpression,
TernaryExpression,
StringLiteralExpression,
UnaryPostfixExpression,
UnaryPrefixExpression,
hasModifier
} from "./ast";
import {
Type,
TypeKind,
typesToNativeTypes
} from "./types";
import {
I64,
U64
} from "./util/i64";
import {
sb
} from "./util/sb";
/** Compilation target. */
export enum Target {
/** WebAssembly with 32-bit pointers. */
WASM32,
/** WebAssembly with 64-bit pointers. Experimental and not supported by any runtime yet. */
WASM64
}
/** Compiler options. */
export class Options {
/** WebAssembly target. Defaults to {@link Target.WASM32}. */
target: Target = Target.WASM32;
/** If true, performs compilation as usual but doesn't produce any output (all calls to module become nops). */
noEmit: bool = false;
/** If true, compiles everything instead of just reachable code. */
noTreeShaking: bool = false;
/** If true, replaces assertions with nops. */
noAssert: bool = false;
/** If true, does not set up a memory. */
noMemory: bool = false;
}
/** Indicates the desired kind of a conversion. */
export const enum ConversionKind {
/** No conversion. */
NONE,
/** Implicit conversion. */
IMPLICIT,
/** Explicit conversion. */
EXPLICIT
}
/** Compiler interface. */
export class Compiler extends DiagnosticEmitter {
/** Program reference. */
program: Program;
/** Provided options. */
options: Options;
/** Module instance being compiled. */
module: Module;
/** Start function being compiled. */
startFunction: Function;
/** Start function expressions. */
startFunctionBody: ExpressionRef[] = new Array();
/** Current type in compilation. */
currentType: Type = Type.void;
/** Current function in compilation. */
currentFunction: Function;
/** Marker indicating whether continue statements are allowed in the current break context. */
disallowContinue: bool = true;
/** Marker indicating that a new variable, if present, is always a local. Used to distinguish locals from globals in the start function. */
variableIsLocal: bool = false;
/** Counting memory offset. */
memoryOffset: U64 = new U64(8, 0); // leave space for (any size of) NULL
/** Memory segments being compiled. */
memorySegments: MemorySegment[] = new Array();
/** Already processed file names. */
files: Set<string> = new Set();
/** Compiles a {@link Program} to a {@link Module} using the specified options. */
static compile(program: Program, options: Options | null = null): Module {
return new Compiler(program, options).compile();
}
/** Constructs a new compiler for a {@link Program} using the specified options. */
constructor(program: Program, options: Options | null = null) {
super(program.diagnostics);
this.program = program;
this.options = options ? options : new Options();
this.memoryOffset = new U64(this.options.target == Target.WASM64 ? 8 : 4, 0); // leave space for `null`
this.module = this.options.noEmit ? Module.createStub() : Module.create();
// set up start function
var startFunctionTemplate = new FunctionPrototype(program, "start", "start", null);
var startFunctionInstance = new Function(startFunctionTemplate, startFunctionTemplate.internalName, [], [], Type.void, null);
this.currentFunction = this.startFunction = startFunctionInstance;
}
/** Performs compilation of the underlying {@link Program} to a {@link Module}. */
compile(): Module {
// initialize lookup maps, built-ins, imports, exports, etc.
this.program.initialize(this.options.target);
// compile entry file (exactly one, usually)
var sources = this.program.sources;
for (var i = 0, k = sources.length; i < k; ++i)
if (sources[i].isEntry)
this.compileSource(sources[i]);
// make start function if not empty
if (this.startFunctionBody.length) {
var typeRef = this.module.getFunctionTypeBySignature(NativeType.None, []);
if (!typeRef)
typeRef = this.module.addFunctionType("v", NativeType.None, []);
this.module.setStart(
this.module.addFunction(this.startFunction.prototype.internalName, typeRef, typesToNativeTypes(this.startFunction.additionalLocals),
this.module.createBlock(null, this.startFunctionBody)
)
);
}
// set up memory
if (!this.options.noMemory) {
var initial = this.memoryOffset.clone();
if (this.options.target == Target.WASM64)
this.module.addGlobal("HEAP_BASE", NativeType.I64, false, this.module.createI64(initial.lo, initial.hi));
else
this.module.addGlobal("HEAP_BASE", NativeType.I32, false, this.module.createI32(initial.lo));
// determine initial page size
var initialOverlaps = initial.clone();
initialOverlaps.and32(0xffff);
if (!initialOverlaps.isZero) {
initial.or32(0xffff);
initial.add32(1);
}
initial.shru32(16); // now is initial size in 64k pages
this.module.setMemory(initial.toI32(), Module.MAX_MEMORY_WASM32 /* TODO: not WASM64 compatible yet */, this.memorySegments, this.options.target, "memory");
}
return this.module;
}
// sources
compileSourceByPath(normalizedPath: string, reportNode: Node): void {
for (var i = 0, k = this.program.sources.length; i < k; ++i) {
var importedSource = this.program.sources[i];
if (importedSource.normalizedPath == normalizedPath) {
this.compileSource(importedSource);
return;
}
}
this.error(DiagnosticCode.File_0_not_found, reportNode.range, normalizedPath);
}
compileSource(source: Source): void {
if (this.files.has(source.normalizedPath))
return;
this.files.add(source.normalizedPath);
var noTreeShaking = this.options.noTreeShaking;
for (var i = 0, k = source.statements.length; i < k; ++i) {
var statement = source.statements[i];
switch (statement.kind) {
case NodeKind.CLASS:
if ((noTreeShaking || source.isEntry && hasModifier(ModifierKind.EXPORT, (<ClassDeclaration>statement).modifiers)) && !(<ClassDeclaration>statement).typeParameters.length)
this.compileClassDeclaration(<ClassDeclaration>statement, []);
break;
case NodeKind.ENUM:
if (noTreeShaking || source.isEntry && hasModifier(ModifierKind.EXPORT, (<EnumDeclaration>statement).modifiers))
this.compileEnumDeclaration(<EnumDeclaration>statement);
break;
case NodeKind.FUNCTION:
if ((noTreeShaking || source.isEntry && hasModifier(ModifierKind.EXPORT, (<FunctionDeclaration>statement).modifiers)) && !(<FunctionDeclaration>statement).typeParameters.length)
this.compileFunctionDeclaration(<FunctionDeclaration>statement, []);
break;
case NodeKind.IMPORT:
this.compileSourceByPath((<ImportStatement>statement).normalizedPath, (<ImportStatement>statement).path);
break;
case NodeKind.NAMESPACE:
if (noTreeShaking || source.isEntry && hasModifier(ModifierKind.EXPORT, (<NamespaceDeclaration>statement).modifiers))
this.compileNamespaceDeclaration(<NamespaceDeclaration>statement);
break;
case NodeKind.VARIABLE:
if (noTreeShaking || source.isEntry && hasModifier(ModifierKind.EXPORT, (<VariableStatement>statement).modifiers))
this.compileVariableStatement(<VariableStatement>statement);
break;
case NodeKind.EXPORT:
if ((<ExportStatement>statement).normalizedPath != null)
this.compileSourceByPath(<string>(<ExportStatement>statement).normalizedPath, <StringLiteralExpression>(<ExportStatement>statement).path);
if (noTreeShaking || source.isEntry)
this.compileExportStatement(<ExportStatement>statement);
break;
// otherwise a top-level statement that is part of the start function's body
default:
var previousFunction = this.currentFunction;
this.currentFunction = this.startFunction;
var expr = this.compileStatement(statement);
if (!this.module.noEmit)
this.startFunctionBody.push(expr);
this.currentFunction = previousFunction;
break;
}
}
}
// globals
compileGlobalDeclaration(declaration: VariableDeclaration, isConst: bool): Global | null {
var element = this.program.elements.get(declaration.internalName);
if (!element || element.kind != ElementKind.GLOBAL)
throw new Error("global expected");
if (!this.compileGlobal(<Global>element)) // reports
return null;
if (isModuleExport(element, declaration)) {
if ((<Global>element).hasConstantValue)
this.module.addGlobalExport(element.internalName, declaration.name.name);
else
this.warning(DiagnosticCode.Cannot_export_a_mutable_global, declaration.range);
}
return <Global>element;
}
compileGlobal(global: Global): bool {
if (global.isCompiled || (global.isBuiltIn && compileBuiltinGetConstant(this, global)))
return true;
var declaration = global.declaration;
var initExpr: ExpressionRef = 0;
if (!global.type) { // infer type
if (declaration) {
if (declaration.type) {
global.type = this.program.resolveType(declaration.type); // reports
if (!global.type)
return false;
} else if (declaration.initializer) {
initExpr = this.compileExpression(declaration.initializer, Type.void, ConversionKind.NONE); // reports and returns unreachable
if (this.currentType == Type.void)
return false;
global.type = this.currentType;
} else {
this.error(DiagnosticCode.Type_expected, declaration.name.range.atEnd);
return false;
}
} else
throw new Error("declaration expected");
}
var nativeType = global.type.toNativeType();
if (global.isDeclared) {
if (global.isConstant) {
this.module.addGlobalImport(global.internalName, global.namespace ? global.namespace.simpleName : "env", global.simpleName, nativeType);
global.isCompiled = true;
return true;
} else if (declaration) {
this.error(DiagnosticCode.Operation_not_supported, declaration.range);
}
return false;
}
var initializeInStart = false;
if (global.hasConstantValue) {
initExpr = makeInlineConstant(global, this.module);
} else if (declaration) {
if (declaration.initializer) {
if (!initExpr)
initExpr = this.compileExpression(declaration.initializer, global.type);
if (!this.module.noEmit && _BinaryenExpressionGetId(initExpr) != ExpressionId.Const) {
if (!global.isMutable) {
initExpr = this.precomputeExpressionRef(initExpr);
if (_BinaryenExpressionGetId(initExpr) != ExpressionId.Const) {
this.warning(DiagnosticCode.Compiling_constant_with_non_constant_initializer_as_mutable, declaration.range);
initializeInStart = true;
}
} else
initializeInStart = true;
}
} else
initExpr = global.type.toNativeZero(this.module);
} else
throw new Error("declaration expected");
var internalName = global.internalName;
if (initializeInStart) {
this.module.addGlobal(internalName, nativeType, true, global.type.toNativeZero(this.module));
var setExpr = this.module.createSetGlobal(internalName, initExpr);
if (!this.module.noEmit)
this.startFunctionBody.push(setExpr);
} else {
this.module.addGlobal(internalName, nativeType, global.isMutable, initExpr);
if (!global.isMutable && !this.module.noEmit) {
var exprType = _BinaryenExpressionGetType(initExpr);
switch (exprType) {
case NativeType.I32:
global.constantIntegerValue = new I64(_BinaryenConstGetValueI32(initExpr), 0);
break;
case NativeType.I64:
global.constantIntegerValue = new I64(_BinaryenConstGetValueI64Low(initExpr), _BinaryenConstGetValueI64High(initExpr));
break;
case NativeType.F32:
global.constantFloatValue = _BinaryenConstGetValueF32(initExpr);
break;
case NativeType.F64:
global.constantFloatValue = _BinaryenConstGetValueF64(initExpr);
break;
default:
throw new Error("concrete type expected");
}
global.hasConstantValue = true;
}
}
global.isCompiled = true;
return true;
}
// enums
compileEnumDeclaration(declaration: EnumDeclaration): void {
var element = this.program.elements.get(declaration.internalName);
if (!element || element.kind != ElementKind.ENUM)
throw new Error("enum expected");
this.compileEnum(<Enum>element);
}
compileEnum(element: Enum): void {
if (element.isCompiled)
return;
var previousValue: EnumValue | null = null;
if (element.members)
for (var member of element.members.values()) {
if (member.kind != ElementKind.ENUMVALUE)
continue;
var val = <EnumValue>member;
if (val.hasConstantValue) {
this.module.addGlobal(val.internalName, NativeType.I32, false, this.module.createI32(val.constantValue));
} else if (val.declaration) {
var declaration = val.declaration;
var initExpr: ExpressionRef;
var initInStart = false;
if (declaration.value) {
initExpr = this.compileExpression(<Expression>declaration.value, Type.i32);
if (!this.module.noEmit && _BinaryenExpressionGetId(initExpr) != ExpressionId.Const) {
initExpr = this.precomputeExpressionRef(initExpr);
if (_BinaryenExpressionGetId(initExpr) != ExpressionId.Const) {
if (element.isConstant)
this.warning(DiagnosticCode.Compiling_constant_with_non_constant_initializer_as_mutable, declaration.range);
initInStart = true;
}
}
} else if (previousValue == null) {
initExpr = this.module.createI32(0);
} else if (previousValue.hasConstantValue) {
initExpr = this.module.createI32(previousValue.constantValue + 1);
} else {
// in TypeScript this errors with TS1061, but actually we can do:
initExpr = this.module.createBinary(BinaryOp.AddI32,
this.module.createGetGlobal(previousValue.internalName, NativeType.I32),
this.module.createI32(1)
);
if (element.isConstant)
this.warning(DiagnosticCode.Compiling_constant_with_non_constant_initializer_as_mutable, declaration.range);
initInStart = true;
}
if (initInStart) {
this.module.addGlobal(val.internalName, NativeType.I32, true, this.module.createI32(0));
var setExpr = this.module.createSetGlobal(val.internalName, initExpr);
if (!this.module.noEmit)
this.startFunctionBody.push(setExpr);
} else {
this.module.addGlobal(val.internalName, NativeType.I32, false, initExpr);
if (!this.module.noEmit) {
if (_BinaryenExpressionGetType(initExpr) == NativeType.I32) {
val.constantValue = _BinaryenConstGetValueI32(initExpr);
val.hasConstantValue = true;
} else
throw new Error("i32 expected");
}
}
} else
throw new Error("declaration expected");
previousValue = <EnumValue>val;
}
element.isCompiled = true;
}
// functions
compileFunctionDeclaration(declaration: FunctionDeclaration, typeArguments: TypeNode[], contextualTypeArguments: Map<string,Type> | null = null, alternativeReportNode: Node | null = null): void {
var internalName = declaration.internalName;
var element = this.program.elements.get(internalName);
if (!element || element.kind != ElementKind.FUNCTION_PROTOTYPE)
throw new Error("function expected");
var instance = this.compileFunctionUsingTypeArguments(<FunctionPrototype>element, typeArguments, contextualTypeArguments, alternativeReportNode); // reports
if (!instance)
return;
if (isModuleExport(instance, declaration))
this.module.addFunctionExport(instance.internalName, declaration.name.name);
}
compileFunctionUsingTypeArguments(prototype: FunctionPrototype, typeArguments: TypeNode[], contextualTypeArguments: Map<string,Type> | null = null, alternativeReportNode: Node | null = null): Function | null {
var instance = prototype.resolveInclTypeArguments(typeArguments, contextualTypeArguments, alternativeReportNode); // reports
if (!instance)
return null;
return this.compileFunction(instance) ? instance : null;
}
compileFunction(instance: Function): bool {
if (instance.isCompiled)
return true;
var declaration = instance.prototype.declaration;
if (!declaration)
throw new Error("declaration expected"); // built-ins are not compiled here
if (instance.isDeclared) {
if (declaration.statements) {
this.error(DiagnosticCode.An_implementation_cannot_be_declared_in_ambient_contexts, declaration.name.range);
return false;
}
} else {
if (!declaration.statements) {
this.error(DiagnosticCode.Function_implementation_is_missing_or_not_immediately_following_the_declaration, declaration.name.range);
return false;
}
}
instance.isCompiled = true;
// compile statements
var stmts: ExpressionRef[] | null = null;
if (!instance.isDeclared) {
var previousFunction = this.currentFunction;
this.currentFunction = instance;
stmts = this.compileStatements(<Statement[]>declaration.statements);
this.currentFunction = previousFunction;
}
// create the function type
var numParameters = instance.parameters.length;
var numParametersInclThis = instance.instanceMethodOf ? numParameters + 1 : numParameters;
var paramIndex = 0;
var nativeResultType = instance.returnType.toNativeType();
var nativeParamTypes = new Array<NativeType>(numParametersInclThis);
var signatureNameParts = new Array<string>(numParametersInclThis + 1);
if (instance.instanceMethodOf) {
nativeParamTypes[paramIndex] = select<NativeType>(NativeType.I64, NativeType.I32, this.options.target == Target.WASM64);
signatureNameParts[paramIndex++] = instance.instanceMethodOf.type.toSignatureString();
}
for (var i = 0; i < numParameters; ++i) {
nativeParamTypes[paramIndex] = instance.parameters[i].type.toNativeType();
signatureNameParts[paramIndex++] = instance.parameters[i].type.toSignatureString();
}
signatureNameParts[paramIndex] = instance.returnType.toSignatureString();
var typeRef = this.module.getFunctionTypeBySignature(nativeResultType, nativeParamTypes);
if (!typeRef)
typeRef = this.module.addFunctionType(signatureNameParts.join(""), nativeResultType, nativeParamTypes);
// create the function
if (instance.isDeclared) {
this.module.addFunctionImport(instance.internalName, instance.prototype.namespace ? instance.prototype.namespace.simpleName : "env", declaration.name.name, typeRef);
} else {
this.module.addFunction(instance.internalName, typeRef, typesToNativeTypes(instance.additionalLocals), this.module.createBlock(null, <ExpressionRef[]>stmts, NativeType.None));
}
instance.finalize();
return true;
}
// namespaces
compileNamespaceDeclaration(declaration: NamespaceDeclaration): void {
var members = declaration.members;
var noTreeShaking = this.options.noTreeShaking;
for (var i = 0, k = members.length; i < k; ++i) {
var member = members[i];
switch (member.kind) {
case NodeKind.CLASS:
if ((noTreeShaking || hasModifier(ModifierKind.EXPORT, (<ClassDeclaration>member).modifiers)) && !(<ClassDeclaration>member).typeParameters.length)
this.compileClassDeclaration(<ClassDeclaration>member, []);
break;
case NodeKind.INTERFACE:
if ((noTreeShaking || hasModifier(ModifierKind.EXPORT, (<InterfaceDeclaration>member).modifiers)) && !(<InterfaceDeclaration>member).typeParameters.length)
this.compileInterfaceDeclaration(<InterfaceDeclaration>member, []);
break;
case NodeKind.ENUM:
if (noTreeShaking || hasModifier(ModifierKind.EXPORT, (<EnumDeclaration>member).modifiers))
this.compileEnumDeclaration(<EnumDeclaration>member);
break;
case NodeKind.FUNCTION:
if ((noTreeShaking || hasModifier(ModifierKind.EXPORT, (<FunctionDeclaration>member).modifiers)) && !(<FunctionDeclaration>member).typeParameters.length)
this.compileFunctionDeclaration(<FunctionDeclaration>member, []);
break;
case NodeKind.NAMESPACE:
if (noTreeShaking || hasModifier(ModifierKind.EXPORT, (<NamespaceDeclaration>member).modifiers))
this.compileNamespaceDeclaration(<NamespaceDeclaration>member);
break;
case NodeKind.VARIABLE:
if (noTreeShaking || hasModifier(ModifierKind.EXPORT, (<VariableStatement>member).modifiers))
this.compileVariableStatement(<VariableStatement>member);
break;
default:
throw new Error("namespace member expected");
}
}
}
compileNamespace(ns: Namespace): void {
if (!ns.members)
return;
var noTreeShaking = this.options.noTreeShaking;
for (var element of ns.members.values()) {
switch (element.kind) {
case ElementKind.CLASS_PROTOTYPE:
if ((noTreeShaking || (<ClassPrototype>element).isExported) && !(<ClassPrototype>element).isGeneric)
this.compileClassUsingTypeArguments(<ClassPrototype>element, []);
break;
case ElementKind.ENUM:
this.compileEnum(<Enum>element);
break;
case ElementKind.FUNCTION_PROTOTYPE:
if ((noTreeShaking || (<FunctionPrototype>element).isExported) && !(<FunctionPrototype>element).isGeneric)
this.compileFunctionUsingTypeArguments(<FunctionPrototype>element, []);
break;
case ElementKind.GLOBAL:
this.compileGlobal(<Global>element);
break;
case ElementKind.NAMESPACE:
this.compileNamespace(<Namespace>element);
break;
}
}
}
// exports
compileExportStatement(statement: ExportStatement): void {
var members = statement.members;
for (var i = 0, k = members.length; i < k; ++i) {
var member = members[i];
var internalExportName = statement.range.source.internalPath + PATH_DELIMITER + member.externalIdentifier.name;
var element = this.program.exports.get(internalExportName);
if (!element) // reported in Program#initialize
continue;
switch (element.kind) {
case ElementKind.CLASS_PROTOTYPE:
if (!(<ClassPrototype>element).isGeneric)
this.compileClassUsingTypeArguments(<ClassPrototype>element, []);
break;
case ElementKind.ENUM:
this.compileEnum(<Enum>element);
break;
case ElementKind.FUNCTION_PROTOTYPE:
if (!(<FunctionPrototype>element).isGeneric) {
var functionInstance = this.compileFunctionUsingTypeArguments(<FunctionPrototype>element, []);
if (functionInstance && statement.range.source.isEntry)
this.module.addFunctionExport(functionInstance.internalName, member.externalIdentifier.name);
}
break;
case ElementKind.GLOBAL:
if (this.compileGlobal(<Global>element) && statement.range.source.isEntry) {
if ((<Global>element).hasConstantValue)
this.module.addGlobalExport(element.internalName, member.externalIdentifier.name);
else
this.warning(DiagnosticCode.Cannot_export_a_mutable_global, member.range);
}
break;
case ElementKind.NAMESPACE:
this.compileNamespace(<Namespace>element);
break;
}
}
}
// classes
compileClassDeclaration(declaration: ClassDeclaration, typeArguments: TypeNode[], contextualTypeArguments: Map<string,Type> | null = null, alternativeReportNode: Node | null = null): void {
var internalName = declaration.internalName;
var element = this.program.elements.get(internalName);
if (!element || element.kind != ElementKind.CLASS_PROTOTYPE)
throw new Error("class expected");
this.compileClassUsingTypeArguments(<ClassPrototype>element, typeArguments, contextualTypeArguments, alternativeReportNode);
}
compileClassUsingTypeArguments(prototype: ClassPrototype, typeArguments: TypeNode[], contextualTypeArguments: Map<string,Type> | null = null, alternativeReportNode: Node | null = null): void {
var instance = prototype.resolveInclTypeArguments(typeArguments, contextualTypeArguments, alternativeReportNode);
if (!instance)
return;
this.compileClass(instance);
}
compileClass(instance: Class): bool {
if (instance.isCompiled)
return true;
return instance.isCompiled = true;
}
compileInterfaceDeclaration(declaration: InterfaceDeclaration, typeArguments: TypeNode[], contextualTypeArguments: Map<string,Type> | null = null, alternativeReportNode: Node | null = null): void {
throw new Error("not implemented");
}
// memory
/** Adds a static memory segment with the specified data. */
addMemorySegment(buffer: Uint8Array): MemorySegment {
if (this.memoryOffset.lo & 7) { // align to 8 bytes so any native data type is aligned here
this.memoryOffset.or32(7);
this.memoryOffset.add32(1);
}
var segment = MemorySegment.create(buffer, this.memoryOffset.clone());
this.memorySegments.push(segment);
this.memoryOffset.add32(buffer.length);
return segment;
}
// statements
compileStatement(statement: Statement): ExpressionRef {
switch (statement.kind) {
case NodeKind.BLOCK:
return this.compileBlockStatement(<BlockStatement>statement);
case NodeKind.BREAK:
return this.compileBreakStatement(<BreakStatement>statement);
case NodeKind.CONTINUE:
return this.compileContinueStatement(<ContinueStatement>statement);
case NodeKind.DO:
return this.compileDoStatement(<DoStatement>statement);
case NodeKind.EMPTY:
return this.compileEmptyStatement(<EmptyStatement>statement);
case NodeKind.EXPRESSION:
return this.compileExpressionStatement(<ExpressionStatement>statement);
case NodeKind.FOR:
return this.compileForStatement(<ForStatement>statement);
case NodeKind.IF:
return this.compileIfStatement(<IfStatement>statement);
case NodeKind.RETURN:
return this.compileReturnStatement(<ReturnStatement>statement);
case NodeKind.SWITCH:
return this.compileSwitchStatement(<SwitchStatement>statement);
case NodeKind.THROW:
return this.compileThrowStatement(<ThrowStatement>statement);
case NodeKind.TRY:
return this.compileTryStatement(<TryStatement>statement);
case NodeKind.VARIABLE:
return this.compileVariableStatement(<VariableStatement>statement);
case NodeKind.WHILE:
return this.compileWhileStatement(<WhileStatement>statement);
case NodeKind.TYPEDECLARATION:
if (this.currentFunction == this.startFunction)
return this.module.createNop();
// fall-through: must be top-level; function bodies are not guaranteed to be evaluated
default:
throw new Error("statement expected");
}
}
compileStatements(statements: Statement[]): ExpressionRef[] {
var k = statements.length;
var stmts = new Array<ExpressionRef>(k);
for (var i = 0; i < k; ++i)
stmts[i] = this.compileStatement(statements[i]);
return stmts; // array of 0-es in noEmit-mode
}
compileBlockStatement(statement: BlockStatement): ExpressionRef {
var statements = statement.statements;
if (statements.length == 0)
return this.module.createNop();
if (statements.length == 1)
return this.compileStatement(statements[0]);
return this.module.createBlock(null, this.compileStatements(statements), NativeType.None);
}
compileBreakStatement(statement: BreakStatement): ExpressionRef {
if (statement.label) {
this.error(DiagnosticCode.Operation_not_supported, statement.label.range);
return this.module.createUnreachable();
}
var context = this.currentFunction.breakContext;
if (context != null)
return this.module.createBreak("break|" + context);
this.error(DiagnosticCode.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement, statement.range);
return this.module.createUnreachable();
}
compileContinueStatement(statement: ContinueStatement): ExpressionRef {
if (statement.label) {
this.error(DiagnosticCode.Operation_not_supported, statement.label.range);
return this.module.createUnreachable();
}
var context = this.currentFunction.breakContext;
if (context && !this.disallowContinue)
return this.module.createBreak("continue|" + context);
this.error(DiagnosticCode.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement, statement.range);
return this.module.createUnreachable();
}
compileDoStatement(statement: DoStatement): ExpressionRef {
var label = this.currentFunction.enterBreakContext();
var body = this.compileStatement(statement.statement);
var condition = this.compileExpression(statement.condition, Type.i32);
this.currentFunction.leaveBreakContext();
var breakLabel = "break|" + label;
var continueLabel = "continue|" + label;
return this.module.createBlock(breakLabel, [
this.module.createLoop(continueLabel,
this.module.createBlock(null, [
body,
this.module.createBreak(continueLabel, condition)
], NativeType.None))
], NativeType.None);
}
compileEmptyStatement(statement: EmptyStatement): ExpressionRef {
return this.module.createNop();
}
compileExpressionStatement(statement: ExpressionStatement): ExpressionRef {
var expr = this.compileExpression(statement.expression, Type.void, ConversionKind.NONE);
if (this.currentType != Type.void) {
expr = this.module.createDrop(expr);
this.currentType = Type.void;
}
return expr;
}
compileForStatement(statement: ForStatement): ExpressionRef {
var context = this.currentFunction.enterBreakContext();
var variableWasLocal = this.variableIsLocal;
if (this.currentFunction == this.startFunction)
this.variableIsLocal = true;
var initializer = statement.initializer ? this.compileStatement(<Statement>statement.initializer) : this.module.createNop();
this.variableIsLocal = variableWasLocal;
var condition = statement.condition ? this.compileExpression(<Expression>statement.condition, Type.i32) : this.module.createI32(1);
var incrementor = statement.incrementor ? this.compileExpression(<Expression>statement.incrementor, Type.void) : this.module.createNop();
var body = this.compileStatement(statement.statement);
this.currentFunction.leaveBreakContext();
var continueLabel = "continue|" + context;
var breakLabel = "break|" + context;
return this.module.createBlock(breakLabel, [
initializer,
this.module.createLoop(continueLabel, this.module.createBlock(null, [
this.module.createIf(condition, this.module.createBlock(null, [
body,
incrementor,
this.module.createBreak(continueLabel)
], NativeType.None))
], NativeType.None))
], NativeType.None);
}
compileIfStatement(statement: IfStatement): ExpressionRef {
var condition = this.compileExpression(statement.condition, Type.i32);
var ifTrue = this.compileStatement(statement.ifTrue);
var ifFalse = statement.ifFalse ? this.compileStatement(<Statement>statement.ifFalse) : <ExpressionRef>0;
return this.module.createIf(condition, ifTrue, ifFalse);
}
compileReturnStatement(statement: ReturnStatement): ExpressionRef {
if (this.currentFunction) {
var expression = statement.value ? this.compileExpression(<Expression>statement.value, this.currentFunction.returnType) : <ExpressionRef>0;
return this.module.createReturn(expression);
}
return this.module.createUnreachable();
}
compileSwitchStatement(statement: SwitchStatement): ExpressionRef {
var context = this.currentFunction.enterBreakContext();
var previousDisallowContinue = this.disallowContinue;
this.disallowContinue = true;
// introduce a local for evaluating the condition (exactly once)
var tempLocal = this.currentFunction.getTempLocal(Type.i32);
var k = statement.cases.length;
// prepend initializer to inner block
var breaks = new Array<ExpressionRef>(1 + k);
breaks[0] = this.module.createSetLocal(tempLocal.index, this.compileExpression(statement.condition, Type.i32)); // initializer
// make one br_if per (possibly dynamic) labeled case (binaryen optimizes to br_table where possible)
var breakIndex = 1;
var defaultIndex = -1;
for (var i = 0; i < k; ++i) {
var case_ = statement.cases[i];
if (case_.label) {
breaks[breakIndex++] = this.module.createBreak("case" + i.toString(10) + "|" + context,
this.module.createBinary(BinaryOp.EqI32,
this.module.createGetLocal(tempLocal.index, NativeType.I32),
this.compileExpression(case_.label, Type.i32)
)
);
} else
defaultIndex = i;
}
this.currentFunction.freeTempLocal(tempLocal);
// otherwise br to default respectively out of the switch if there is no default case
breaks[breakIndex] = this.module.createBreak((defaultIndex >= 0
? "case" + defaultIndex.toString(10)
: "break"
) + "|" + context);
// nest blocks in order
var currentBlock = this.module.createBlock("case0|" + context, breaks, NativeType.None);
for (i = 0; i < k; ++i) {
case_ = statement.cases[i];
var nextLabel = i == k - 1 ? "break|" + context : "case" + (i + 1).toString(10) + "|" + context;
var l = case_.statements.length;
var body = new Array<ExpressionRef>(1 + l);
body[0] = currentBlock;
for (var j = 0; j < l; ++j)
body[j + 1] = this.compileStatement(case_.statements[j]);
currentBlock = this.module.createBlock(nextLabel, body, NativeType.None);
}
this.currentFunction.leaveBreakContext();
this.disallowContinue = previousDisallowContinue;
return currentBlock;
}
compileThrowStatement(statement: ThrowStatement): ExpressionRef {
return this.module.createUnreachable(); // TODO: waiting for exception-handling spec
}
compileTryStatement(statement: TryStatement): ExpressionRef {
throw new Error("not implemented");
// can't yet support something like: try { return ... } finally { ... }
// worthwhile to investigate lowering returns to block results (here)?
}
compileVariableStatement(statement: VariableStatement): ExpressionRef {
var declarations = statement.declarations;
// top-level variables become globals
if (this.currentFunction == this.startFunction && !this.variableIsLocal) {
var isConst = hasModifier(ModifierKind.CONST, statement.modifiers);
for (var i = 0, k = declarations.length; i < k; ++i)
this.compileGlobalDeclaration(declarations[i], isConst);
return this.module.createNop();
}
// other variables become locals
var initializers = new Array<ExpressionRef>();
for (i = 0, k = declarations.length; i < k; ++i) {
var declaration = declarations[i];
var name = declaration.name.name;
var type: Type | null = null;
var init: ExpressionRef = 0;
if (declaration.type) {
type = this.program.resolveType(<TypeNode>declaration.type, this.currentFunction.contextualTypeArguments, true); // reports
if (!type)
continue;
if (declaration.initializer)
init = this.compileExpression(declaration.initializer, type); // reports and returns unreachable
} else if (declaration.initializer) { // infer type
init = this.compileExpression(declaration.initializer, Type.void, ConversionKind.NONE); // reports and returns unreachable
if ((type = this.currentType) == Type.void)
continue;
} else {
this.error(DiagnosticCode.Type_expected, declaration.name.range.atEnd);
continue;
}
if (this.currentFunction.locals.has(name))
this.error(DiagnosticCode.Duplicate_identifier_0, declaration.name.range, name); // recoverable
else {
if (hasModifier(ModifierKind.CONST, declaration.modifiers)) {
if (init) {
init = this.precomputeExpressionRef(init);
if (_BinaryenExpressionGetId(init) == ExpressionId.Const) {
var local = new Local(this.program, name, -1, type);
switch (_BinaryenExpressionGetType(init)) {
case NativeType.I32:
local = local.withConstantIntegerValue(_BinaryenConstGetValueI32(init), 0);
break;
case NativeType.I64:
local = local.withConstantIntegerValue(_BinaryenConstGetValueI64Low(init), _BinaryenConstGetValueI64High(init));
break;
case NativeType.F32:
local = local.withConstantFloatValue(<f64>_BinaryenConstGetValueF32(init));
break;
case NativeType.F64:
local = local.withConstantFloatValue(_BinaryenConstGetValueF64(init));
break;
default:
throw new Error("concrete type expected");
}
this.currentFunction.locals.set(name, local);
continue;
} else
this.warning(DiagnosticCode.Compiling_constant_with_non_constant_initializer_as_mutable, declaration.range);
} else {
this.error(DiagnosticCode._const_declarations_must_be_initialized, declaration.range);
}
}
this.currentFunction.addLocal(type, name);
if (init)
initializers.push(this.compileAssignmentWithValue(declaration.name, init));
}
}
return initializers.length ? this.module.createBlock(null, initializers, NativeType.None) : this.module.createNop();
}
compileWhileStatement(statement: WhileStatement): ExpressionRef {
var label = this.currentFunction.enterBreakContext();
var condition = this.compileExpression(statement.condition, Type.i32);
var breakLabel = "break|" + label;
var continueLabel = "continue|" + label;
var body = this.compileStatement(statement.statement);
this.currentFunction.leaveBreakContext();
return this.module.createBlock(breakLabel, [
this.module.createLoop(continueLabel,
this.module.createIf(condition, this.module.createBlock(null, [
body,
this.module.createBreak(continueLabel)
], NativeType.None))
)
], NativeType.None);
}
// expressions
compileExpression(expression: Expression, contextualType: Type, conversionKind: ConversionKind = ConversionKind.IMPLICIT): ExpressionRef {
this.currentType = contextualType;
var expr: ExpressionRef;
switch (expression.kind) {
case NodeKind.ASSERTION:
expr = this.compileAssertionExpression(<AssertionExpression>expression, contextualType);
break;
case NodeKind.BINARY:
expr = this.compileBinaryExpression(<BinaryExpression>expression, contextualType);
break;
case NodeKind.CALL:
expr = this.compileCallExpression(<CallExpression>expression, contextualType);
break;
case NodeKind.ELEMENTACCESS:
expr = this.compileElementAccessExpression(<ElementAccessExpression>expression, contextualType);
break;
case NodeKind.IDENTIFIER:
case NodeKind.FALSE:
case NodeKind.NULL:
case NodeKind.THIS:
case NodeKind.TRUE:
expr = this.compileIdentifierExpression(<IdentifierExpression>expression, contextualType);
break;
case NodeKind.LITERAL:
expr = this.compileLiteralExpression(<LiteralExpression>expression, contextualType);
break;
case NodeKind.NEW:
expr = this.compileNewExpression(<NewExpression>expression, contextualType);
break;
case NodeKind.PARENTHESIZED:
expr = this.compileParenthesizedExpression(<ParenthesizedExpression>expression, contextualType);
break;
case NodeKind.PROPERTYACCESS:
expr = this.compilePropertyAccessExpression(<PropertyAccessExpression>expression, contextualType);
break;
case NodeKind.TERNARY:
expr = this.compileTernaryExpression(<TernaryExpression>expression, contextualType);
break;
case NodeKind.UNARYPOSTFIX:
expr = this.compileUnaryPostfixExpression(<UnaryPostfixExpression>expression, contextualType);
break;
case NodeKind.UNARYPREFIX:
expr = this.compileUnaryPrefixExpression(<UnaryPrefixExpression>expression, contextualType);
break;
default:
throw new Error("expression expected");
}
if (conversionKind != ConversionKind.NONE && this.currentType != contextualType) {
expr = this.convertExpression(expr, this.currentType, contextualType, conversionKind, expression);
this.currentType = contextualType;
}
return expr;
}
precomputeExpression(expression: Expression, contextualType: Type, conversionKind: ConversionKind = ConversionKind.IMPLICIT): ExpressionRef {
return this.precomputeExpressionRef(this.compileExpression(expression, contextualType, conversionKind));
}
precomputeExpressionRef(expr: ExpressionRef): ExpressionRef {
var nativeType = this.currentType.toNativeType();
var typeRef = this.module.getFunctionTypeBySignature(nativeType, []);
if (!typeRef)
typeRef = this.module.addFunctionType(this.currentType.toSignatureString(), nativeType, []);
var funcRef = this.module.addFunction("__precompute", typeRef, [], expr);
this.module.runPasses([ "precompute" ], funcRef);
var ret = _BinaryenFunctionGetBody(funcRef);
this.module.removeFunction("__precompute");
// TODO: also remove the function type somehow if no longer used or make the C-API accept
// a `null` typeRef, using an implicit type.
return ret;
}
convertExpression(expr: ExpressionRef, fromType: Type, toType: Type, conversionKind: ConversionKind, reportNode: Node): ExpressionRef {
if (conversionKind == ConversionKind.NONE)
return expr;
// void to any
if (fromType.kind == TypeKind.VOID) {
this.error(DiagnosticCode.Operation_not_supported, reportNode.range);
throw new Error("unexpected conversion from void");
}
// any to void
if (toType.kind == TypeKind.VOID)
return this.module.createDrop(expr);
var fromFloat = fromType.isAnyFloat;
var toFloat = toType.isAnyFloat;
var mod = this.module;
var losesInformation = false;
if (fromFloat) {
// float to float
if (toFloat) {
if (fromType.kind == TypeKind.F32) {
// f32 to f64
if (toType.kind == TypeKind.F64)
expr = mod.createUnary(UnaryOp.PromoteF32, expr);
// f64 to f32
} else if (toType.kind == TypeKind.F32) {
losesInformation = true;
expr = mod.createUnary(UnaryOp.DemoteF64, expr);
}
// float to int
} else {
losesInformation = true;
// f32 to int
if (fromType.kind == TypeKind.F32) {
if (toType.isSignedInteger) {
if (toType.isLongInteger)
expr = mod.createUnary(UnaryOp.TruncF32ToI64, expr);
else {
expr = mod.createUnary(UnaryOp.TruncF32ToI32, expr);
if (toType.isSmallInteger) {
expr = mod.createBinary(BinaryOp.ShlI32, expr, mod.createI32(toType.smallIntegerShift));
expr = mod.createBinary(BinaryOp.ShrI32, expr, mod.createI32(toType.smallIntegerShift));
}
}
} else {
if (toType.isLongInteger)
expr = mod.createUnary(UnaryOp.TruncF32ToU64, expr);
else {
expr = mod.createUnary(UnaryOp.TruncF32ToU32, expr);
if (toType.isSmallInteger)
expr = mod.createBinary(BinaryOp.AndI32, expr, mod.createI32(toType.smallIntegerMask));
}
}
// f64 to int
} else {
if (toType.isSignedInteger) {
if (toType.isLongInteger)
expr = mod.createUnary(UnaryOp.TruncF64ToI64, expr);
else {
expr = mod.createUnary(UnaryOp.TruncF64ToI32, expr);
if (toType.isSmallInteger) {
expr = mod.createBinary(BinaryOp.ShlI32, expr, mod.createI32(toType.smallIntegerShift));
expr = mod.createBinary(BinaryOp.ShrI32, expr, mod.createI32(toType.smallIntegerShift));
}
}
} else {
if (toType.isLongInteger)
expr = mod.createUnary(UnaryOp.TruncF64ToU64, expr);
else {
expr = mod.createUnary(UnaryOp.TruncF64ToU32, expr);
if (toType.isSmallInteger)
expr = mod.createBinary(BinaryOp.AndI32, expr, mod.createI32(toType.smallIntegerMask));
}
}
}
}
// int to float
} else if (toFloat) {
// int to f32
if (toType.kind == TypeKind.F32) {
if (fromType.isLongInteger) {
losesInformation = true;
if (fromType.isSignedInteger)
expr = mod.createUnary(UnaryOp.ConvertI64ToF32, expr);
else
expr = mod.createUnary(UnaryOp.ConvertU64ToF32, expr);
} else {
if (!fromType.isSmallInteger)
losesInformation = true;
if (fromType.isSignedInteger)
expr = mod.createUnary(UnaryOp.ConvertI32ToF32, expr);
else
expr = mod.createUnary(UnaryOp.ConvertU32ToF32, expr);
}
// int to f64
} else {
if (fromType.isLongInteger) {
losesInformation = true;
if (fromType.isSignedInteger)
expr = mod.createUnary(UnaryOp.ConvertI64ToF64, expr);
else
expr = mod.createUnary(UnaryOp.ConvertU64ToF64, expr);
} else
if (fromType.isSignedInteger)
expr = mod.createUnary(UnaryOp.ConvertI32ToF64, expr);
else
expr = mod.createUnary(UnaryOp.ConvertU32ToF64, expr);
}
// int to int
} else {
if (fromType.isLongInteger) {
// i64 to i32
if (!toType.isLongInteger) {
losesInformation = true;
expr = mod.createUnary(UnaryOp.WrapI64, expr); // discards upper bits
if (toType.isSmallInteger) {
if (toType.isSignedInteger) {
expr = mod.createBinary(BinaryOp.ShlI32, expr, mod.createI32(toType.smallIntegerShift));
expr = mod.createBinary(BinaryOp.ShrI32, expr, mod.createI32(toType.smallIntegerShift));
} else
expr = mod.createBinary(BinaryOp.AndI32, expr, mod.createI32(toType.smallIntegerMask));
}
}
// i32 to i64
} else if (toType.isLongInteger) {
if (toType.isSignedInteger)
expr = mod.createUnary(UnaryOp.ExtendI32, expr);
else
expr = mod.createUnary(UnaryOp.ExtendU32, expr);
// i32 or smaller to even smaller int
} else if (toType.isSmallInteger && fromType.size > toType.size) {
losesInformation = true;
if (toType.isSignedInteger) {
expr = mod.createBinary(BinaryOp.ShlI32, expr, mod.createI32(toType.smallIntegerShift));
expr = mod.createBinary(BinaryOp.ShrI32, expr, mod.createI32(toType.smallIntegerShift));
} else
expr = mod.createBinary(BinaryOp.AndI32, expr, mod.createI32(toType.smallIntegerMask));
}
}
if (losesInformation && conversionKind == ConversionKind.IMPLICIT)
this.error(DiagnosticCode.Conversion_from_type_0_to_1_possibly_loses_information_and_thus_requires_an_explicit_cast, reportNode.range, fromType.toString(), toType.toString());
return expr;
}
compileAssertionExpression(expression: AssertionExpression, contextualType: Type): ExpressionRef {
var toType = this.program.resolveType(expression.toType, this.currentFunction.contextualTypeArguments); // reports
if (!toType)
return this.module.createUnreachable();
return this.compileExpression(expression.expression, toType, ConversionKind.EXPLICIT);
}
compileBinaryExpression(expression: BinaryExpression, contextualType: Type): ExpressionRef {
var op: BinaryOp;
var left: ExpressionRef;
var right: ExpressionRef;
var compound: Token = 0;
var condition: ExpressionRef;
var tempLocal: Local;
switch (expression.operator) {
case Token.LESSTHAN:
left = this.compileExpression(expression.left, contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.I32:
op = BinaryOp.LtI32;
break;
case TypeKind.ISIZE:
op = select<BinaryOp>(BinaryOp.LtI64, BinaryOp.LtI32, this.options.target == Target.WASM64);
break;
case TypeKind.I64:
op = BinaryOp.LtI64;
break;
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
op = BinaryOp.LtU32;
break;
case TypeKind.USIZE:
// TODO: check operator overload
op = select<BinaryOp>(BinaryOp.LtU64, BinaryOp.LtU32, this.options.target == Target.WASM64);
break;
case TypeKind.U64:
op = BinaryOp.LtU64;
break;
case TypeKind.F32:
op = BinaryOp.LtF32;
break;
case TypeKind.F64:
op = BinaryOp.LtF64;
break;
default:
throw new Error("concrete type expected");
}
this.currentType = Type.bool;
break;
case Token.GREATERTHAN:
left = this.compileExpression(expression.left, contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.I32:
op = BinaryOp.GtI32;
break;
case TypeKind.ISIZE:
op = select<BinaryOp>(BinaryOp.GtI64, BinaryOp.GtI32, this.options.target == Target.WASM64);
break;
case TypeKind.I64:
op = BinaryOp.GtI64;
break;
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
op = BinaryOp.GtU32;
break;
case TypeKind.USIZE:
// TODO: check operator overload
op = select<BinaryOp>(BinaryOp.GtU64, BinaryOp.GtU32, this.options.target == Target.WASM64);
break;
case TypeKind.U64:
op = BinaryOp.GtU64;
break;
case TypeKind.F32:
op = BinaryOp.GtF32;
break;
case TypeKind.F64:
op = BinaryOp.GtF64;
break;
default:
throw new Error("concrete type expected");
}
this.currentType = Type.bool;
break;
case Token.LESSTHAN_EQUALS:
left = this.compileExpression(expression.left, contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.I32:
op = BinaryOp.LeI32;
break;
case TypeKind.ISIZE:
op = select<BinaryOp>(BinaryOp.LeI64, BinaryOp.LeI32, this.options.target == Target.WASM64);
break;
case TypeKind.I64:
op = BinaryOp.LeI64;
break;
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
op = BinaryOp.LeU32;
break;
case TypeKind.USIZE:
// TODO: check operator overload
op = select<BinaryOp>(BinaryOp.LeU64, BinaryOp.LeU32, this.options.target == Target.WASM64);
break;
case TypeKind.U64:
op = BinaryOp.LeU64;
break;
case TypeKind.F32:
op = BinaryOp.LeF32;
break;
case TypeKind.F64:
op = BinaryOp.LeF64;
break;
default:
throw new Error("concrete type expected");
}
this.currentType = Type.bool;
break;
case Token.GREATERTHAN_EQUALS:
left = this.compileExpression(expression.left, contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.I32:
op = BinaryOp.GeI32;
break;
case TypeKind.ISIZE:
op = select<BinaryOp>(BinaryOp.GeI64, BinaryOp.GeI32, this.options.target == Target.WASM64);
break;
case TypeKind.I64:
op = BinaryOp.GeI64;
break;
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
op = BinaryOp.GeU32;
break;
case TypeKind.USIZE:
// TODO: check operator overload
op = select<BinaryOp>(BinaryOp.GeU64, BinaryOp.GeU32, this.options.target == Target.WASM64);
break;
case TypeKind.U64:
op = BinaryOp.GeU64;
break;
case TypeKind.F32:
op = BinaryOp.GeF32;
break;
case TypeKind.F64:
op = BinaryOp.GeF64;
break;
default:
throw new Error("concrete type expected");
}
this.currentType = Type.bool;
break;
case Token.EQUALS_EQUALS:
case Token.EQUALS_EQUALS_EQUALS:
left = this.compileExpression(expression.left, contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.I32:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
op = BinaryOp.EqI32;
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
op = select<BinaryOp>(BinaryOp.EqI64, BinaryOp.EqI32, this.options.target == Target.WASM64);
break;
case TypeKind.I64:
case TypeKind.U64:
op = BinaryOp.EqI64;
break;
case TypeKind.F32:
op = BinaryOp.EqF32;
break;
case TypeKind.F64:
op = BinaryOp.EqF64;
break;
default:
throw new Error("concrete type expected");
}
this.currentType = Type.bool;
break;
case Token.EXCLAMATION_EQUALS:
case Token.EXCLAMATION_EQUALS_EQUALS:
left = this.compileExpression(expression.left, contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.I32:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
op = BinaryOp.NeI32;
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
op = select<BinaryOp>(BinaryOp.NeI64, BinaryOp.NeI32, this.options.target == Target.WASM64);
break;
case TypeKind.I64:
case TypeKind.U64:
op = BinaryOp.NeI64;
break;
case TypeKind.F32:
op = BinaryOp.NeF32;
break;
case TypeKind.F64:
op = BinaryOp.NeF64;
break;
default:
throw new Error("concrete type expected");
}
this.currentType = Type.bool;
break;
case Token.EQUALS:
return this.compileAssignment(expression.left, expression.right, contextualType);
case Token.PLUS_EQUALS:
compound = Token.EQUALS;
case Token.PLUS:
left = this.compileExpression(expression.left, contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.I32:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
op = BinaryOp.AddI32;
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
op = select<BinaryOp>(BinaryOp.AddI64, BinaryOp.AddI32, this.options.target == Target.WASM64);
break;
case TypeKind.I64:
case TypeKind.U64:
op = BinaryOp.AddI64;
break;
case TypeKind.F32:
op = BinaryOp.AddF32;
break;
case TypeKind.F64:
op = BinaryOp.AddF64;
break;
default:
throw new Error("concrete type expected");
}
break;
case Token.MINUS_EQUALS:
compound = Token.EQUALS;
case Token.MINUS:
left = this.compileExpression(expression.left, contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.I32:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
op = BinaryOp.SubI32;
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
op = select<BinaryOp>(BinaryOp.SubI64, BinaryOp.SubI32, this.options.target == Target.WASM64);
break;
case TypeKind.I64:
case TypeKind.U64:
op = BinaryOp.SubI64;
break;
case TypeKind.F32:
op = BinaryOp.SubF32;
break;
case TypeKind.F64:
op = BinaryOp.SubF64;
break;
default:
throw new Error("concrete type expected");
}
break;
case Token.ASTERISK_EQUALS:
compound = Token.EQUALS;
case Token.ASTERISK:
left = this.compileExpression(expression.left, contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.I32:
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
op = BinaryOp.MulI32;
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
op = select<BinaryOp>(BinaryOp.MulI64, BinaryOp.MulI32, this.options.target == Target.WASM64);
break;
case TypeKind.I64:
case TypeKind.U64:
op = BinaryOp.MulI64;
break;
case TypeKind.F32:
op = BinaryOp.MulF32;
break;
case TypeKind.F64:
op = BinaryOp.MulF64;
break;
default:
throw new Error("concrete type expected");
}
break;
case Token.SLASH_EQUALS:
compound = Token.EQUALS;
case Token.SLASH:
left = this.compileExpression(expression.left, contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.I32:
op = BinaryOp.DivI32;
break;
case TypeKind.ISIZE:
op = select<BinaryOp>(BinaryOp.DivI64, BinaryOp.DivI32, this.options.target == Target.WASM64);
break;
case TypeKind.I64:
op = BinaryOp.DivI64;
break;
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
op = BinaryOp.DivU32;
break;
case TypeKind.USIZE:
// TODO: check operator overload
op = select<BinaryOp>(BinaryOp.DivU64, BinaryOp.DivU32, this.options.target == Target.WASM64);
break;
case TypeKind.U64:
op = BinaryOp.DivU64;
break;
case TypeKind.F32:
op = BinaryOp.DivF32;
break;
case TypeKind.F64:
op = BinaryOp.DivF64;
break;
default:
throw new Error("concrete type expected");
}
break;
case Token.PERCENT_EQUALS:
compound = Token.EQUALS;
case Token.PERCENT:
left = this.compileExpression(expression.left, contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
switch (this.currentType.kind) {
case TypeKind.I8:
case TypeKind.I16:
case TypeKind.I32:
op = BinaryOp.RemI32;
break;
case TypeKind.ISIZE:
op = select<BinaryOp>(BinaryOp.RemI64, BinaryOp.RemI32, this.options.target == Target.WASM64);
break;
case TypeKind.I64:
op = BinaryOp.RemI64;
break;
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
op = BinaryOp.RemU32;
break;
case TypeKind.USIZE:
// TODO: check operator overload
op = select<BinaryOp>(BinaryOp.RemU64, BinaryOp.RemU32, this.options.target == Target.WASM64);
break;
case TypeKind.U64:
op = BinaryOp.RemU64;
break;
case TypeKind.F32:
case TypeKind.F64:
// TODO: internal fmod, possibly simply imported from JS
this.error(DiagnosticCode.Operation_not_supported, expression.range);
return this.module.createUnreachable();
default:
throw new Error("concrete type expected");
}
break;
case Token.LESSTHAN_LESSTHAN_EQUALS:
compound = Token.EQUALS;
case Token.LESSTHAN_LESSTHAN:
left = this.compileExpression(expression.left, contextualType.isAnyFloat ? Type.i64 : contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
switch (this.currentType.kind) {
default:
op = BinaryOp.ShlI32;
break;
case TypeKind.I64:
case TypeKind.U64:
op = BinaryOp.ShlI64;
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
op = select<BinaryOp>(BinaryOp.ShlI64, BinaryOp.ShlI32, this.options.target == Target.WASM64);
break;
}
break;
case Token.GREATERTHAN_GREATERTHAN_EQUALS:
compound = Token.EQUALS;
case Token.GREATERTHAN_GREATERTHAN:
left = this.compileExpression(expression.left, contextualType.isAnyFloat ? Type.i64 : contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
switch (this.currentType.kind) {
default:
op = BinaryOp.ShrI32;
break;
case TypeKind.I64:
op = BinaryOp.ShrI64;
break;
case TypeKind.ISIZE:
op = select<BinaryOp>(BinaryOp.ShrI64, BinaryOp.ShrI32, this.options.target == Target.WASM64);
break;
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.U32:
case TypeKind.BOOL:
op = BinaryOp.ShrU32;
break;
case TypeKind.U64:
op = BinaryOp.ShrU64;
break;
case TypeKind.USIZE:
// TODO: check operator overload
op = select<BinaryOp>(BinaryOp.ShrU64, BinaryOp.ShrU32, this.options.target == Target.WASM64);
break;
}
break;
case Token.GREATERTHAN_GREATERTHAN_GREATERTHAN_EQUALS:
compound = Token.EQUALS;
case Token.GREATERTHAN_GREATERTHAN_GREATERTHAN:
left = this.compileExpression(expression.left, contextualType.isAnyFloat ? Type.u64 : contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
switch (this.currentType.kind) {
default:
op = BinaryOp.ShrU32;
break;
case TypeKind.I64:
case TypeKind.U64:
op = BinaryOp.ShrU64;
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
op = select<BinaryOp>(BinaryOp.ShrU64, BinaryOp.ShrU32, this.options.target == Target.WASM64);
break;
}
break;
case Token.AMPERSAND_EQUALS:
compound = Token.EQUALS;
case Token.AMPERSAND:
left = this.compileExpression(expression.left, contextualType.isAnyFloat ? Type.i64 : contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
switch (this.currentType.kind) {
default:
op = BinaryOp.AndI32;
break;
case TypeKind.I64:
case TypeKind.U64:
op = BinaryOp.AndI64;
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
op = select<BinaryOp>(BinaryOp.AndI64, BinaryOp.AndI32, this.options.target == Target.WASM64);
break;
}
break;
case Token.BAR_EQUALS:
compound = Token.EQUALS;
case Token.BAR:
left = this.compileExpression(expression.left, contextualType.isAnyFloat ? Type.i64 : contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
switch (this.currentType.kind) {
default:
op = BinaryOp.OrI32;
break;
case TypeKind.I64:
case TypeKind.U64:
op = BinaryOp.OrI64;
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
op = select<BinaryOp>(BinaryOp.OrI64, BinaryOp.OrI32, this.options.target == Target.WASM64);
break;
}
break;
case Token.CARET_EQUALS:
compound = Token.EQUALS;
case Token.CARET:
left = this.compileExpression(expression.left, contextualType.isAnyFloat ? Type.i64 : contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
switch (this.currentType.kind) {
default:
op = BinaryOp.XorI32;
break;
case TypeKind.I64:
case TypeKind.U64:
op = BinaryOp.XorI64;
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
op = select<BinaryOp>(BinaryOp.XorI64, BinaryOp.XorI32, this.options.target == Target.WASM64);
break;
}
break;
// logical (no overloading)
case Token.AMPERSAND_AMPERSAND: // left && right
left = this.compileExpression(expression.left, contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
// simplify if left is free of side effects while tolerating one level of nesting, e.g., i32.load(i32.const)
if (condition = this.module.cloneExpression(left, true, 1))
return this.module.createIf(
this.currentType.isLongInteger
? this.module.createBinary(BinaryOp.NeI64, condition, this.module.createI64(0, 0))
: this.currentType == Type.f64
? this.module.createBinary(BinaryOp.NeF64, condition, this.module.createF64(0))
: this.currentType == Type.f32
? this.module.createBinary(BinaryOp.NeF32, condition, this.module.createF32(0))
: condition, // usual case: saves one EQZ when not using EQZ above
right,
left
);
// otherwise use a temporary local for the intermediate value
tempLocal = this.currentFunction.getAndFreeTempLocal(this.currentType);
condition = this.module.createTeeLocal(tempLocal.index, left);
return this.module.createIf(
this.currentType.isLongInteger
? this.module.createBinary(BinaryOp.NeI64, condition, this.module.createI64(0, 0))
: this.currentType == Type.f64
? this.module.createBinary(BinaryOp.NeF64, condition, this.module.createF64(0))
: this.currentType == Type.f32
? this.module.createBinary(BinaryOp.NeF32, condition, this.module.createF32(0))
: this.module.createTeeLocal(tempLocal.index, left),
right,
this.module.createGetLocal(tempLocal.index, this.currentType.toNativeType())
);
case Token.BAR_BAR: // left || right
left = this.compileExpression(expression.left, contextualType, ConversionKind.NONE);
right = this.compileExpression(expression.right, this.currentType);
// simplify if left is free of side effects while tolerating one level of nesting
if (condition = this.module.cloneExpression(left, true, 1))
return this.module.createIf(
this.currentType.isLongInteger
? this.module.createBinary(BinaryOp.NeI64, condition, this.module.createI64(0, 0))
: this.currentType == Type.f64
? this.module.createBinary(BinaryOp.NeF64, condition, this.module.createF64(0))
: this.currentType == Type.f32
? this.module.createBinary(BinaryOp.NeF32, condition, this.module.createF32(0))
: condition, // usual case: saves one EQZ when not using EQZ above
left,
right
);
// otherwise use a temporary local for the intermediate value
tempLocal = this.currentFunction.getAndFreeTempLocal(this.currentType);
condition = this.module.createTeeLocal(tempLocal.index, left);
return this.module.createIf(
this.currentType.isLongInteger
? this.module.createBinary(BinaryOp.NeI64, condition, this.module.createI64(0, 0))
: this.currentType == Type.f64
? this.module.createBinary(BinaryOp.NeF64, condition, this.module.createF64(0))
: this.currentType == Type.f32
? this.module.createBinary(BinaryOp.NeF32, condition, this.module.createF32(0))
: this.module.createTeeLocal(tempLocal.index, left),
this.module.createGetLocal(tempLocal.index, this.currentType.toNativeType()),
right
);
default:
throw new Error("not implemented");
}
if (compound) {
right = this.module.createBinary(op, left, right);
return this.compileAssignmentWithValue(expression.left, right, contextualType != Type.void);
}
return this.module.createBinary(op, left, right);
}
compileAssignment(expression: Expression, valueExpression: Expression, contextualType: Type): ExpressionRef {
var element: Element | null = null;
switch (expression.kind) {
case NodeKind.IDENTIFIER:
element = this.program.resolveIdentifier(<IdentifierExpression>expression, this.currentFunction); // reports
break;
case NodeKind.PROPERTYACCESS:
element = this.program.resolvePropertyAccess(<PropertyAccessExpression>expression, this.currentFunction); // reports
break;
default:
this.error(DiagnosticCode.Operation_not_supported, expression.range);
}
if (!element)
return this.module.createUnreachable();
var type: Type | null = null;
switch (element.kind) {
case ElementKind.LOCAL:
type = (<Local>element).type;
break;
case ElementKind.GLOBAL:
if (this.compileGlobal(<Global>element))
type = (<Global>element).type;
break;
case ElementKind.PROPERTY:
var setterPrototype = (<Property>element).setterPrototype;
if (setterPrototype) {
var setterInstance = setterPrototype.resolve(); // reports
if (setterInstance) {
if (contextualType == Type.void) { // just set if dropped anyway
return this.compileCall(setterInstance, [ valueExpression ], expression);
} else { // otherwise do a set followed by a get
var getterPrototype = (<Property>element).getterPrototype;
if (getterPrototype) {
var getterInstance = getterPrototype.resolve(); // reports
if (getterInstance) {
return this.module.createBlock(null, [
this.compileCall(setterInstance, [ valueExpression ], expression),
this.compileCall(getterInstance, [], expression)
], getterInstance.returnType.toNativeType());
}
} else
this.error(DiagnosticCode.Property_0_does_not_exist_on_type_1, expression.range, (<Property>element).simpleName, (<Property>element).parent.internalName);
}
}
} else
this.error(DiagnosticCode.Property_0_does_not_exist_on_type_1, expression.range, (<Property>element).simpleName, (<Property>element).parent.internalName);
return this.module.createUnreachable();
default:
this.error(DiagnosticCode.Operation_not_supported, expression.range);
}
if (!type)
return this.module.createUnreachable();
this.currentType = type;
return this.compileAssignmentWithValue(expression, this.compileExpression(valueExpression, type, ConversionKind.IMPLICIT), contextualType != Type.void);
}
compileAssignmentWithValue(expression: Expression, valueWithCorrectType: ExpressionRef, tee: bool = false): ExpressionRef {
var element: Element | null = null;
switch (expression.kind) {
case NodeKind.IDENTIFIER:
element = this.program.resolveIdentifier(<IdentifierExpression>expression, this.currentFunction);
break;
case NodeKind.PROPERTYACCESS:
element = this.program.resolvePropertyAccess(<PropertyAccessExpression>expression, this.currentFunction);
break;
default:
this.error(DiagnosticCode.Operation_not_supported, expression.range);
}
if (!element)
return this.module.createUnreachable();
if (element.kind == ElementKind.LOCAL) {
assert((<Local>element).type != null);
if (tee) {
this.currentType = <Type>(<Local>element).type;
return this.module.createTeeLocal((<Local>element).index, valueWithCorrectType);
}
this.currentType = Type.void;
return this.module.createSetLocal((<Local>element).index, valueWithCorrectType);
}
if (element.kind == ElementKind.GLOBAL) {
if (!this.compileGlobal(<Global>element))
return this.module.createUnreachable();
this.currentType = <Type>(<Global>element).type;
if (!(<Global>element).isMutable) {
this.error(DiagnosticCode.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, expression.range, element.internalName);
return this.module.createUnreachable();
}
if (tee) {
var globalNativeType = (<Type>(<Global>element).type).toNativeType();
return this.module.createBlock(null, [ // teeGlobal
this.module.createSetGlobal((<Global>element).internalName, valueWithCorrectType),
this.module.createGetGlobal((<Global>element).internalName, globalNativeType)
], globalNativeType);
}
this.currentType = Type.void;
return this.module.createSetGlobal((<Global>element).internalName, valueWithCorrectType);
}
// TODO: fields, (setters)
throw new Error("not implemented");
}
compileCallExpression(expression: CallExpression, contextualType: Type): ExpressionRef {
var element: Element | null = null;
var thisExpression: Expression;
switch (expression.expression.kind) {
// case NodeKind.THIS:
// case NodeKind.SUPER:
case NodeKind.IDENTIFIER:
element = this.program.resolveIdentifier(thisExpression = <IdentifierExpression>expression.expression, this.currentFunction);
break;
case NodeKind.PROPERTYACCESS:
element = this.program.resolvePropertyAccess(<PropertyAccessExpression>expression.expression, this.currentFunction);
thisExpression = (<PropertyAccessExpression>expression.expression).expression;
break;
default:
throw new Error("not implemented");
}
if (!element)
return this.module.createUnreachable();
if (element.kind == ElementKind.FUNCTION_PROTOTYPE) {
var functionPrototype = <FunctionPrototype>element;
var functionInstance: Function | null = null;
if (functionPrototype.isBuiltIn) {
var resolvedTypeArguments: Type[] | null = null;
if (expression.typeArguments) {
var k = expression.typeArguments.length;
resolvedTypeArguments = new Array<Type>(k);
var sb = new Array<string>(k);
for (var i = 0; i < k; ++i) {
var resolvedType = this.program.resolveType(expression.typeArguments[i], this.currentFunction.contextualTypeArguments, true); // reports
if (!resolvedType)
return this.module.createUnreachable();
resolvedTypeArguments[i] = resolvedType;
sb[i] = resolvedType.toString();
}
functionInstance = functionPrototype.instances.get(sb.join(","));
} else
functionInstance = functionPrototype.instances.get("");
if (!functionInstance) {
this.currentType = contextualType;
var expr = compileBuiltinCall(this, functionPrototype, resolvedTypeArguments, expression.arguments, expression);
if (!expr) {
this.error(DiagnosticCode.Operation_not_supported, expression.range);
return this.module.createUnreachable();
}
return expr;
}
} else {
// TODO: infer type arguments from parameter types if omitted
functionInstance = (<FunctionPrototype>element).resolveInclTypeArguments(expression.typeArguments, this.currentFunction.contextualTypeArguments, expression); // reports
}
if (!functionInstance)
return this.module.createUnreachable();
var numArguments = expression.arguments.length;
var numArgumentsInclThis = select<i32>(numArguments + 1, numArguments, functionInstance.instanceMethodOf != null);
var argumentIndex = 0;
var args = new Array<Expression>(numArgumentsInclThis);
if (functionInstance.instanceMethodOf)
args[argumentIndex++] = thisExpression;
for (i = 0; i < numArguments; ++i)
args[argumentIndex++] = expression.arguments[i];
return this.compileCall(functionInstance, args, expression);
}
this.error(DiagnosticCode.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, expression.range, element.internalName);
return this.module.createUnreachable();
}
/** Compiles a call to a function. If an instance method, `this` is the first element in `argumentExpressions`. */
compileCall(functionInstance: Function, argumentExpressions: Expression[], reportNode: Node): ExpressionRef {
// validate and compile arguments
var parameters = functionInstance.parameters;
var numParameters = parameters.length;
var numParametersInclThis = select<i32>(numParameters + 1, numParameters, functionInstance.instanceMethodOf != null);
var numArgumentsInclThis = argumentExpressions.length;
var numArguments = select<i32>(numArgumentsInclThis - 1, numArgumentsInclThis, functionInstance.instanceMethodOf != null);
if (numArgumentsInclThis > numParametersInclThis) { // too many arguments
this.error(DiagnosticCode.Expected_0_arguments_but_got_1, reportNode.range,
numParameters.toString(10),
numArguments.toString(10)
);
return this.module.createUnreachable();
}
var operands = new Array<ExpressionRef>(numParametersInclThis);
var operandIndex = 0;
if (functionInstance.instanceMethodOf)
operands[operandIndex++] = this.compileExpression(argumentExpressions[0], functionInstance.instanceMethodOf.type);
for (; operandIndex < numParametersInclThis; ++operandIndex) {
// argument has been provided
if (numArgumentsInclThis > operandIndex) {
operands[operandIndex] = this.compileExpression(argumentExpressions[operandIndex], parameters[operandIndex + numParameters - numParametersInclThis].type);
// argument has been omitted
} else {
var initializer = parameters[operandIndex + numParameters - numParametersInclThis].initializer;
if (initializer) { // fall back to provided initializer
operands[operandIndex] = this.compileExpression(initializer, parameters[operandIndex + numParameters - numParametersInclThis].type);
// FIXME: here, the initializer is compiled in the caller's scope.
// a solution could be to use a stub for each possible overload, calling the
// full function with optional arguments being part of the stub's body.
} else { // too few arguments
this.error(DiagnosticCode.Expected_at_least_0_arguments_but_got_1, reportNode.range,
(operandIndex + numParametersInclThis - numParameters).toString(10),
numArguments.toString(10)
);
return this.module.createUnreachable();
}
}
}
this.currentType = functionInstance.returnType;
if (!functionInstance.isCompiled)
this.compileFunction(functionInstance);
// imported function
if (functionInstance.isDeclared)
return this.module.createCallImport(functionInstance.internalName, operands, functionInstance.returnType.toNativeType());
// internal function
return this.module.createCall(functionInstance.internalName, operands, functionInstance.returnType.toNativeType());
}
compileElementAccessExpression(expression: ElementAccessExpression, contextualType: Type): ExpressionRef {
var targetExpression = expression.expression;
var target: Element | null = null;
switch (targetExpression.kind) {
// case NodeKind.THIS:
case NodeKind.IDENTIFIER:
target = this.program.resolveIdentifier(<IdentifierExpression>targetExpression, this.currentFunction);
break;
case NodeKind.PROPERTYACCESS:
target = this.program.resolvePropertyAccess(<PropertyAccessExpression>targetExpression, this.currentFunction);
break;
default:
this.error(DiagnosticCode.Operation_not_supported, expression.range);
}
if (!target)
return this.module.createUnreachable();
throw new Error("not implemented");
}
compileIdentifierExpression(expression: IdentifierExpression, contextualType: Type): ExpressionRef {
switch (expression.kind) {
case NodeKind.NULL:
if (this.options.target == Target.WASM64) {
if (!contextualType.classType) {
assert(contextualType.kind == TypeKind.USIZE);
this.currentType = Type.usize64;
}
return this.module.createI64(0, 0);
}
if (!contextualType.classType) {
assert(contextualType.kind == TypeKind.USIZE);
this.currentType = Type.usize32;
}
return this.module.createI32(0);
case NodeKind.TRUE:
this.currentType = Type.bool;
return this.module.createI32(1);
case NodeKind.FALSE:
this.currentType = Type.bool;
return this.module.createI32(0);
case NodeKind.THIS:
if (this.currentFunction.instanceMethodOf) {
this.currentType = this.currentFunction.instanceMethodOf.type;
return this.module.createGetLocal(0, this.options.target == Target.WASM64 ? NativeType.I64 : NativeType.I32);
}
this.error(DiagnosticCode._this_cannot_be_referenced_in_current_location, expression.range);
this.currentType = this.options.target == Target.WASM64 ? Type.u64 : Type.u32;
return this.module.createUnreachable();
}
var element = this.program.resolveElement(expression, this.currentFunction); // reports
if (!element)
return this.module.createUnreachable();
// local
if (element.kind == ElementKind.LOCAL) {
assert((<Local>element).type != null);
this.currentType = <Type>(<Local>element).type;
if ((<Local>element).hasConstantValue)
return makeInlineConstant(<Local>element, this.module);
assert((<Local>element).index >= 0);
return this.module.createGetLocal((<Local>element).index, this.currentType.toNativeType());
}
// global
if (element.kind == ElementKind.GLOBAL) {
if (element.isBuiltIn)
return compileBuiltinGetConstant(this, <Global>element);
var global = <Global>element;
if (!this.compileGlobal(global)) // reports
return this.module.createUnreachable();
assert(global.type != null);
this.currentType = <Type>global.type;
if (global.hasConstantValue)
return makeInlineConstant(global, this.module);
else
return this.module.createGetGlobal((<Global>element).internalName, this.currentType.toNativeType());
}
this.error(DiagnosticCode.Operation_not_supported, expression.range);
return this.module.createUnreachable();
}
compileLiteralExpression(expression: LiteralExpression, contextualType: Type): ExpressionRef {
switch (expression.literalKind) {
// case LiteralKind.ARRAY:
case LiteralKind.FLOAT: {
var floatValue = (<FloatLiteralExpression>expression).value;
if (contextualType == Type.f32)
return this.module.createF32(<f32>floatValue);
this.currentType = Type.f64;
return this.module.createF64(floatValue);
}
case LiteralKind.INTEGER: {
var intValue = (<IntegerLiteralExpression>expression).value;
if (contextualType == Type.bool && (intValue.isZero || intValue.isOne))
return this.module.createI32(intValue.isZero ? 0 : 1);
if (contextualType == Type.f64)
return this.module.createF64((<f64>intValue.lo) + (<f64>intValue.hi) * 0xffffffff);
if (contextualType == Type.f32)
return this.module.createF32((<f32>intValue.lo) + (<f32>intValue.hi) * 0xffffffff);
if (contextualType.isLongInteger)
return this.module.createI64(intValue.lo, intValue.hi);
if (contextualType.isSmallInteger)
return this.module.createI32(intValue.toI32());
if (contextualType == Type.void && !intValue.fitsInI32) {
this.currentType = Type.i64;
return this.module.createI64(intValue.lo, intValue.hi);
}
this.currentType = contextualType.isSignedInteger ? Type.i32 : Type.u32;
return this.module.createI32(intValue.toI32());
}
// case LiteralKind.OBJECT:
// case LiteralKind.REGEXP:
// case LiteralKind.STRING:
}
throw new Error("not implemented");
}
compileNewExpression(expression: NewExpression, contextualType: Type): ExpressionRef {
throw new Error("not implemented");
}
compileParenthesizedExpression(expression: ParenthesizedExpression, contextualType: Type): ExpressionRef {
// does not change types, just order
return this.compileExpression(expression.expression, contextualType, ConversionKind.NONE);
}
compilePropertyAccessExpression(propertyAccess: PropertyAccessExpression, contextualType: Type): ExpressionRef {
var expression = propertyAccess.expression;
var propertyName = propertyAccess.property.name;
// the lhs expression is either 'this', 'super', an identifier or another property access
var target: Element | null;
switch (expression.kind) {
case NodeKind.THIS:
if (!this.currentFunction.instanceMethodOf) {
this.error(DiagnosticCode._this_cannot_be_referenced_in_current_location, expression.range);
return this.module.createUnreachable();
}
target = this.currentFunction.instanceMethodOf;
break;
case NodeKind.SUPER:
if (!(this.currentFunction.instanceMethodOf && this.currentFunction.instanceMethodOf.base)) {
this.error(DiagnosticCode._super_can_only_be_referenced_in_a_derived_class, expression.range);
return this.module.createUnreachable();
}
target = this.currentFunction.instanceMethodOf.base;
break;
case NodeKind.IDENTIFIER:
target = this.program.resolveIdentifier(<IdentifierExpression>expression, this.currentFunction); // reports
break;
case NodeKind.PROPERTYACCESS:
target = this.program.resolvePropertyAccess(<PropertyAccessExpression>expression, this.currentFunction); // reports
break;
default:
throw new Error("lhs expression expected");
}
if (!target)
return this.module.createUnreachable();
// look up the property within the target to obtain the actual element
var element: Element | null;
switch (target.kind) {
case ElementKind.LOCAL:
assert((<Local>target).type != null);
element = (<Type>(<Local>target).type).classType;
if (!element) {
this.error(DiagnosticCode.Property_0_does_not_exist_on_type_1, propertyAccess.property.range, propertyName, (<Type>(<Local>target).type).toString());
return this.module.createUnreachable();
}
target = element;
break;
case ElementKind.GLOBAL:
if (!this.compileGlobal(<Global>target))
return this.module.createUnreachable();
element = (<Type>(<Global>target).type).classType;
if (!element) {
this.error(DiagnosticCode.Property_0_does_not_exist_on_type_1, propertyAccess.property.range, propertyName, (<Type>(<Local>target).type).toString());
return this.module.createUnreachable();
}
target = element;
break;
default:
if (target.members) {
element = target.members.get(propertyName);
if (!element) {
this.error(DiagnosticCode.Property_0_does_not_exist_on_type_1, propertyAccess.property.range, propertyName, target.internalName);
return this.module.createUnreachable();
}
// handle enum values right away
if (element.kind == ElementKind.ENUMVALUE) {
this.currentType = Type.i32;
if ((<EnumValue>element).hasConstantValue)
return this.module.createI32((<EnumValue>element).constantValue);
this.compileEnum((<EnumValue>element).enum);
return this.module.createGetGlobal((<EnumValue>element).internalName, NativeType.I32);
}
} else {
this.error(DiagnosticCode.Property_0_does_not_exist_on_type_1, propertyAccess.property.range, propertyName, target.internalName);
return this.module.createUnreachable();
}
break;
}
// handle the element
switch (element.kind) {
case ElementKind.LOCAL:
assert((<Local>element).type != null);
return this.module.createGetLocal((<Local>element).index, (this.currentType = <Type>(<Local>element).type).toNativeType());
case ElementKind.GLOBAL:
if (!this.compileGlobal(<Global>element))
return this.module.createUnreachable();
assert((<Global>element).type != null);
this.currentType = <Type>(<Global>element).type;
if ((<Global>element).hasConstantValue)
return makeInlineConstant(<Global>element, this.module);
else
return this.module.createGetGlobal((<Global>element).internalName, this.currentType.toNativeType());
case ElementKind.PROPERTY: // getter
var getterPrototype = (<Property>element).getterPrototype;
if (getterPrototype) {
var getterInstance = getterPrototype.resolve([], this.currentFunction.contextualTypeArguments);
if (getterInstance) {
return this.compileCall(getterInstance, [], propertyAccess);
} else {
return this.module.createUnreachable();
}
} else {
this.error(DiagnosticCode.Property_0_does_not_exist_on_type_1, propertyAccess.property.range, propertyName, target.internalName);
return this.module.createUnreachable();
}
}
this.error(DiagnosticCode.Operation_not_supported, propertyAccess.range);
throw new Error("not implemented");
}
compileTernaryExpression(expression: TernaryExpression, contextualType: Type): ExpressionRef {
var condition = this.compileExpression(expression.condition, Type.i32);
var ifThen = this.compileExpression(expression.ifThen, contextualType);
var ifElse = this.compileExpression(expression.ifElse, contextualType);
return this.module.createIf(condition, ifThen, ifElse);
}
compileUnaryPostfixExpression(expression: UnaryPostfixExpression, contextualType: Type): ExpressionRef {
var operator = expression.operator;
// make a getter for the expression (also obtains the type)
var getValue = this.compileExpression(expression.operand, contextualType, contextualType == Type.void ? ConversionKind.NONE : ConversionKind.IMPLICIT);
// use a temp local for the intermediate value
var tempLocal = this.currentFunction.getTempLocal(this.currentType);
assert(tempLocal.type != null);
var op: BinaryOp;
var nativeType: NativeType;
var nativeOne: ExpressionRef;
switch ((<Type>tempLocal.type).kind) {
default:
op = select<BinaryOp>(BinaryOp.AddI32, BinaryOp.SubI32, operator == Token.PLUS_PLUS);
nativeType = NativeType.I32;
nativeOne = this.module.createI32(1);
break;
case TypeKind.USIZE:
// TODO: check operator overload
case TypeKind.ISIZE:
if (this.options.target != Target.WASM64) {
op = select<BinaryOp>(BinaryOp.AddI32, BinaryOp.SubI32, operator == Token.PLUS_PLUS);
nativeType = NativeType.I32;
nativeOne = this.module.createI32(1);
break;
}
// fall-through
case TypeKind.I64:
case TypeKind.U64:
op = select<BinaryOp>(BinaryOp.AddI64, BinaryOp.SubI64, operator == Token.PLUS_PLUS);
nativeType = NativeType.I64;
nativeOne = this.module.createI64(1, 0);
break;
case TypeKind.F32:
op = select<BinaryOp>(BinaryOp.AddF32, BinaryOp.SubF32, operator == Token.PLUS_PLUS);
nativeType = NativeType.F32;
nativeOne = this.module.createF32(1);
break;
case TypeKind.F64:
op = select<BinaryOp>(BinaryOp.AddF64, BinaryOp.SubF64, operator == Token.PLUS_PLUS);
nativeType = NativeType.F64;
nativeOne = this.module.createF64(1);
break;
}
// make a setter that sets the new value (temp value +/- 1)
// note that this is not inlined below because it modifies currentType
var setValue = this.compileAssignmentWithValue(expression.operand,
this.module.createBinary(op,
this.module.createGetLocal(tempLocal.index, nativeType),
nativeOne
), false
);
// NOTE: can't preemptively tee_local the return value on the stack because binaryen expects
// this to be well-formed. becomes a tee_local when optimizing, though.
this.currentType = <Type>tempLocal.type;
this.currentFunction.freeTempLocal(tempLocal);
return this.module.createBlock(null, [
this.module.createSetLocal(tempLocal.index, getValue), // +++ this.module.createTeeLocal(tempLocal.index, getValue),
setValue,
this.module.createGetLocal(tempLocal.index, nativeType) // ---
], nativeType);
}
compileUnaryPrefixExpression(expression: UnaryPrefixExpression, contextualType: Type): ExpressionRef {
var operandExpression = expression.operand;
var operand: ExpressionRef;
var op: UnaryOp;
switch (expression.operator) {
case Token.PLUS:
return this.compileExpression(operandExpression, contextualType, contextualType == Type.void ? ConversionKind.NONE : ConversionKind.IMPLICIT);
case Token.MINUS:
operand = this.compileExpression(operandExpression, contextualType, contextualType == Type.void ? ConversionKind.NONE : ConversionKind.IMPLICIT);
switch (this.currentType.kind) {
default:
return this.module.createBinary(BinaryOp.SubI32, this.module.createI32(0), operand);
case TypeKind.ISIZE:
case TypeKind.USIZE:
if (this.options.target != Target.WASM64)
return this.module.createBinary(BinaryOp.SubI32, this.module.createI32(0), operand);
// fall-through
case TypeKind.I64:
case TypeKind.U64:
return this.module.createBinary(BinaryOp.SubI64, this.module.createI64(0, 0), operand);
case TypeKind.F32:
op = UnaryOp.NegF32;
break;
case TypeKind.F64:
op = UnaryOp.NegF64;
break;
}
break;
case Token.PLUS_PLUS:
operand = this.compileExpression(operandExpression, contextualType, contextualType == Type.void ? ConversionKind.NONE : ConversionKind.IMPLICIT);
switch (this.currentType.kind) {
default:
operand = this.module.createBinary(BinaryOp.AddI32, operand, this.module.createI32(1));
break;
case TypeKind.ISIZE:
case TypeKind.USIZE:
if (this.options.target != Target.WASM64) {
operand = this.module.createBinary(BinaryOp.AddI32, operand, this.module.createI32(1));
break;
}
// fall-through
case TypeKind.I64:
case TypeKind.U64:
operand = this.module.createBinary(BinaryOp.AddI64, operand, this.module.createI64(1, 0));
break;
case TypeKind.F32:
operand = this.module.createBinary(BinaryOp.AddF32, operand, this.module.createF32(1));
break;
case TypeKind.F64:
operand = this.module.createBinary(BinaryOp.AddF64, operand, this.module.createF64(1));
break;
}
return this.compileAssignmentWithValue(operandExpression, operand, contextualType != Type.void);
case Token.MINUS_MINUS:
operand = this.compileExpression(operandExpression, contextualType, contextualType == Type.void ? ConversionKind.NONE : ConversionKind.IMPLICIT);
switch (this.currentType.kind) {
default:
operand = this.module.createBinary(BinaryOp.SubI32, operand, this.module.createI32(1));
break;
case TypeKind.ISIZE:
case TypeKind.USIZE:
if (this.options.target != Target.WASM64) {
operand = this.module.createBinary(BinaryOp.SubI32, operand, this.module.createI32(1));
break;
}
// fall-through
case TypeKind.I64:
case TypeKind.U64:
operand = this.module.createBinary(BinaryOp.SubI64, operand, this.module.createI64(1, 0));
break;
case TypeKind.F32:
operand = this.module.createBinary(BinaryOp.SubF32, operand, this.module.createF32(1));
break;
case TypeKind.F64:
operand = this.module.createBinary(BinaryOp.SubF64, operand, this.module.createF64(1));
break;
}
return this.compileAssignmentWithValue(operandExpression, operand, contextualType != Type.void);
case Token.EXCLAMATION:
operand = this.compileExpression(operandExpression, Type.bool, ConversionKind.NONE);
switch (this.currentType.kind) {
default:
op = UnaryOp.EqzI32;
break;
case TypeKind.ISIZE:
case TypeKind.USIZE:
op = select<UnaryOp>(UnaryOp.EqzI64, UnaryOp.EqzI32, this.options.target == Target.WASM64);
break;
case TypeKind.I64:
case TypeKind.U64:
op = UnaryOp.EqzI64;
break;
case TypeKind.F32:
this.currentType = Type.bool;
return this.module.createBinary(BinaryOp.EqF32, operand, this.module.createF32(0));
case TypeKind.F64:
this.currentType = Type.bool;
return this.module.createBinary(BinaryOp.EqF64, operand, this.module.createF64(0));
}
this.currentType = Type.bool;
break;
case Token.TILDE:
operand = this.compileExpression(operandExpression, contextualType.isAnyFloat ? Type.i64 : contextualType, contextualType == Type.void ? ConversionKind.NONE : ConversionKind.IMPLICIT);
switch (this.currentType.kind) {
default:
return this.module.createBinary(BinaryOp.XorI32, operand, this.module.createI32(-1));
case TypeKind.ISIZE:
case TypeKind.USIZE:
if (this.options.target != Target.WASM64)
return this.module.createBinary(BinaryOp.XorI32, operand, this.module.createI32(-1));
// fall-through
case TypeKind.I64:
case TypeKind.U64:
return this.module.createBinary(BinaryOp.XorI64, operand, this.module.createI64(-1, -1));
}
default:
throw new Error("unary operator expected");
}
return this.module.createUnary(op, operand);
}
}
// helpers
/** Tests whether an element is a module-level export from the entry file. */
function isModuleExport(element: Element, declaration: DeclarationStatement): bool {
if (!element.isExported)
return false;
if (declaration.range.source.isEntry)
return true;
var parentNode = declaration.parent;
if (!parentNode)
return false;
if (parentNode.kind == NodeKind.VARIABLE)
if (!(parentNode = parentNode.parent))
return false;
if (parentNode.kind != NodeKind.NAMESPACE && parentNode.kind != NodeKind.CLASS)
return false;
var parent = element.program.elements.get((<DeclarationStatement>parentNode).internalName);
if (!parent)
return false;
return isModuleExport(parent, <DeclarationStatement>parentNode);
}
/** Creates an inlined expression of a constant variable-like element. */
function makeInlineConstant(element: VariableLikeElement, module: Module): ExpressionRef {
assert(element.hasConstantValue);
assert(element.type != null);
switch ((<Type>element.type).kind) {
case TypeKind.I8:
case TypeKind.I16:
var shift = (<Type>element.type).smallIntegerShift;
return module.createI32(element.constantIntegerValue ? element.constantIntegerValue.toI32() << shift >> shift : 0);
case TypeKind.U8:
case TypeKind.U16:
case TypeKind.BOOL:
return module.createI32(element.constantIntegerValue ? element.constantIntegerValue.toI32() & (<Type>element.type).smallIntegerMask: 0);
case TypeKind.I32:
case TypeKind.U32:
return module.createI32(element.constantIntegerValue ? element.constantIntegerValue.lo : 0)
case TypeKind.ISIZE:
case TypeKind.USIZE:
if (element.program.target != Target.WASM64)
return module.createI32(element.constantIntegerValue ? element.constantIntegerValue.lo : 0)
// fall-through
case TypeKind.I64:
case TypeKind.U64:
return element.constantIntegerValue
? module.createI64(element.constantIntegerValue.lo, element.constantIntegerValue.hi)
: module.createI64(0, 0);
case TypeKind.F32:
return module.createF32((<VariableLikeElement>element).constantFloatValue);
case TypeKind.F64:
return module.createF64((<VariableLikeElement>element).constantFloatValue);
}
throw new Error("concrete type expected");
}
|
b81dbacd06f948c5104f25ae3258d417a3313dc1
|
TypeScript
|
TrueChat/Frontend
|
/src/services/UserService.ts
| 2.5625
| 3
|
import {RegistrationData} from "./AuthService";
import {ConstraintViolation, Request, Response, ResponseHandler} from "./types";
export interface Image {
imageURL: string
}
export type UserProfile = {
first_name: string,
last_name: string,
username: string,
about: string,
images: Image[]
}
export type SubmissionFailureHandler = (violations: ConstraintViolation[]) => void;
export type SubmissionSuccessHandler = () => void;
export default interface UserService {
login(
username: string,
password: string,
onSuccess?: SubmissionSuccessHandler,
onFailure?: SubmissionFailureHandler
) : void;
register(
data: RegistrationData,
onSuccess?: SubmissionSuccessHandler,
onFailure?: SubmissionFailureHandler
) : void;
loadProfileForCurrentUser() : Promise<UserProfile>;
loadProfile(username: string) : Promise<UserProfile>;
updateProfileForCurrentUser(
profile: UserProfile,
onSuccess?: SubmissionSuccessHandler,
onFailure?: SubmissionFailureHandler
) : void;
getCurrentUser() : string;
userIsPresent(): boolean;
searchUsers(searchString: string): Promise<UserProfile[]>
sendAuthorizedRequest(
request: Request,
onSuccess: (response: Response<any>) => void,
onFailure: (response: Response<any>) => void
) : void;
logout(doAfter: () => void) : void;
uploadImage(
file: File,
onSuccess: ResponseHandler<any>,
onFailure: ResponseHandler<any>
) : void;
}
|
febe19375c66f381cb95611ed05d6e30ec33f702
|
TypeScript
|
essitepp/Fullstack
|
/osa9/patientor-backend/src/utils.ts
| 2.96875
| 3
|
import { Entry, EntryType, Gender, HealhtCheckRating, HealthCheckEntryInput, OccupationalHealthEntryInput, HospitalEntryInput, NewEntryInput, NewPatientInput, SickLeave, Discharge, HealthCheckEntry, Diagnosis, BaseEntry, HospitalEntry, OccupationalHealthEntry, } from "./types";
type PatientFields = { name: unknown, dateOfBirth: unknown, ssn: unknown, gender: unknown, occupation: unknown, entries: unknown };
const toNewPatientInput = ( object: PatientFields ): NewPatientInput => {
const newPatient: NewPatientInput = {
name: parseName(object.name),
dateOfBirth: parseDateOfBirth(object.dateOfBirth),
ssn: parseSsn(object.ssn),
gender: parseGender(object.gender),
occupation: parseOccupation(object.occupation),
entries: parseEntries(object.entries || [])
};
return newPatient;
};
const parseName = (name: unknown): string => {
if (!name || !isString(name)) {
throw new Error(`Invalid name: ${name}`);
}
return name;
};
const parseDateOfBirth = (dateOfBirth: unknown): string => {
if (!dateOfBirth || !isString(dateOfBirth)) {
throw new Error(`Invalid date of birth: ${dateOfBirth}`);
}
return dateOfBirth;
};
const parseSsn = (ssn: unknown): string => {
if (!ssn || !isString(ssn)) {
throw new Error(`Invalid ssn: ${ssn}`);
}
return ssn;
};
const parseGender = (gender: unknown): Gender => {
if (!gender || !isGender(gender)) {
throw new Error(`Invalid gender: ${gender}`);
}
return gender;
};
const parseOccupation = (occupation: unknown): string => {
if (!occupation || !isString(occupation)) {
throw new Error(`Invalid occupation: ${occupation}`);
}
return occupation;
};
const parseEntries = (entries: unknown): Entry[] => {
if (!entries || !isEntriesArray(entries)) {
throw new Error(`Invalid entries: ${entries}`);
}
return entries;
};
const parseDiagnosisCodes = (diagnosisCodes: unknown): Array<Diagnosis['code']> => {
if (!diagnosisCodes || !isDiagnosisCodes(diagnosisCodes)) {
throw new Error(`Invalid diagnosis codes: ${diagnosisCodes}`);
}
return diagnosisCodes;
};
const isString = (param: unknown): param is string => {
return typeof param === 'string' || param instanceof String;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isGender = (param: any): param is Gender => {
return Object.values(Gender).includes(param);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isEntriesArray = (param: any): param is Entry[] => {
if (!(param instanceof Array)) {
return false;
}
return param.every(isEntry);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isEntry = (param: any): param is Entry => {
if (isHealthCheckEntry(param) || isOccupationalHealthEntry(param) || isHospitalEntry(param)) {
return true;
}
return false;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isBaseEntry = (param: any): param is BaseEntry => {
if (
!isString(param.id) || !isString(param.description) || !isString(param.date)
|| !isString(param.specialist) || (param.diagnosisCodes && !isDiagnosisCodes(param.diagnosisCodes))
) {
return false;
}
return true;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isDiagnosisCodes = (param: any): param is Array<Diagnosis['code']> => {
if (!(param instanceof Array)) {
return false;
}
return param.every(isString);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isHealthCheckEntry = (param: any): param is HealthCheckEntry => {
if (!(param.type === EntryType.HealthCheck) || !isHealthCheckRating(param.healthCheckRating)) {
return false;
}
if (!isBaseEntry(param)) {
return false;
}
return true;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isOccupationalHealthEntry = (param: any): param is OccupationalHealthEntry => {
if (!(param.type === EntryType.OccupationalHealthcare) || !isString(param.employerName)) {
return false;
}
if (param.sickLeave && !isSickLeave(param.sickLeave)) {
return false;
}
if (!isBaseEntry(param)) {
return false;
}
return true;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isHospitalEntry = (param: any): param is HospitalEntry => {
if (!(param.type === EntryType.Hospital)) {
return false;
}
if (param.discharge && !isDischarge(param.discharge)) {
return false;
}
if (!isBaseEntry(param)) {
return false;
}
return true;
};
type EntryFields = {
type: unknown, description: unknown, date: unknown, specialist: unknown, diagnosisCodes: unknown
};
const toNewEntryInput = ( object: EntryFields ): NewEntryInput => {
const type = parseType(object.type);
switch(type) {
case EntryType.HealthCheck:
return toHealthCheckInput(object);
case EntryType.OccupationalHealthcare:
return toOccupationalHealthcareInput(object);
case EntryType.Hospital:
return toHospitalInput(object);
}
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const toHealthCheckInput = ( object: any ): HealthCheckEntryInput => {
const newEntry: HealthCheckEntryInput = {
type: EntryType.HealthCheck,
description: parseDescription(object.description),
date: parseDate(object.date),
specialist: parseSpecialist(object.specialist),
diagnosisCodes: parseDiagnosisCodes(object.diagnosisCodes || []),
healthCheckRating: parseHealthCheckRating(object.healthCheckRating),
};
return newEntry;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const toOccupationalHealthcareInput = ( object: any ): OccupationalHealthEntryInput => {
const newEntry: OccupationalHealthEntryInput = {
type: EntryType.OccupationalHealthcare,
description: parseDescription(object.description),
date: parseDate(object.date),
specialist: parseSpecialist(object.specialist),
diagnosisCodes: parseDiagnosisCodes(object.diagnosisCodes || []),
employerName: parseEmployerName(object.employerName),
};
if (object.sickLeave) {
newEntry.sickLeave = parseSickLeave(object.sickLeave);
}
return newEntry;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const toHospitalInput = ( object: any ): HospitalEntryInput => {
const newEntry: HospitalEntryInput = {
type: EntryType.Hospital,
description: parseDescription(object.description),
date: parseDate(object.date),
specialist: parseSpecialist(object.specialist),
diagnosisCodes: parseDiagnosisCodes(object.diagnosisCodes || []),
};
if (object.discharge) {
newEntry.discharge = parseDischarge(object.discharge);
}
return newEntry;
};
const parseEmployerName = (employerName: unknown): string => {
if (!employerName || !isString(employerName)) {
throw new Error(`Invalid employer name: ${employerName}`);
}
return employerName;
};
const parseSickLeave = (sickLeave: unknown): SickLeave => {
if (!sickLeave || !isSickLeave(sickLeave)) {
throw new Error(`Invalid sick leave: ${sickLeave}`);
}
return sickLeave;
};
const parseDischarge = (discharge: unknown): Discharge => {
if (!discharge || !isDischarge(discharge)) {
throw new Error(`Invalid discharge: ${discharge}`);
}
return discharge;
};
const parseDescription = (description: unknown): string => {
if (!description || !isString(description)) {
throw new Error(`Invalid description: ${description}`);
}
return description;
};
const parseSpecialist = (specialist: unknown): string => {
if (!specialist || !isString(specialist)) {
throw new Error(`Invalid specialist: ${specialist}`);
}
return specialist;
};
const parseHealthCheckRating = (healthCheckRating: unknown): HealhtCheckRating => {
if ((!healthCheckRating && healthCheckRating !== 0) || !isHealthCheckRating(healthCheckRating)) {
throw new Error(`Invalid health check rating: ${healthCheckRating}`);
}
return healthCheckRating;
};
const parseDate = (date: unknown): string => {
if (!date || !isString(date)) {
throw new Error(`Invalid date: ${date}`);
}
return date;
};
const parseType = (type: unknown): EntryType => {
if (!type || !isType(type)) {
throw new Error(`Invalid type: ${type}`);
}
return type;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isType = (param: any): param is EntryType => {
return Object.values(EntryType).includes(param);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isHealthCheckRating = (param: any): param is HealhtCheckRating => {
return Object.values(HealhtCheckRating).includes(param);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isSickLeave = (param: any): param is SickLeave => {
if (!isString(param.startDate) || !isString(param.endDate)) {
return false;
}
return true;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isDischarge = (param: any): param is Discharge => {
if (!isString(param.date) || !isString(param.criteria)) {
return false;
}
return true;
};
export {
toNewPatientInput,
toNewEntryInput,
};
|
c3d1fcb3b92e4eca9c6ed75b4cf8a7d7bec68e22
|
TypeScript
|
boilerz/tsconfig
|
/src/generate.ts
| 2.640625
| 3
|
import fs from 'fs';
import util from 'util';
import type { PackageJson } from 'type-fest';
import packageJson from '../package.json';
import cliConfig from './cli';
import { Config } from './common';
import defaultConfig from './default';
import reactNativeConfig from './react-native';
const mkdirAsync = util.promisify(fs.mkdir);
const writeFileAsync = util.promisify(fs.writeFile);
const rmdirAsync = util.promisify(fs.rmdir);
const readFileAsync = util.promisify(fs.readFile);
const {
version,
repository,
author,
license,
dependencies,
} = packageJson as PackageJson;
let readme: string;
function createPackageFile(name: string, config: Config): PackageJson {
return {
name: `@boilerz/${name}`,
version,
description: config.description,
repository,
author,
license,
main: 'tsconfig.json',
files: ['tsconfig.json'],
dependencies: {
...(config.base.extends?.startsWith('@tsconfig')
? {
[config.base.extends]: dependencies![config.base.extends],
}
: {}),
},
};
}
async function generatePackage(config: Config): Promise<void> {
const packageName = `tsconfig${config.suffix ? `-${config.suffix}` : ''}`;
const productionPackageName = `${packageName}-production`;
const packageNames = [packageName, productionPackageName];
await Promise.all(
packageNames.map((name) =>
mkdirAsync(`packages/${name}`, { recursive: true }),
),
);
await Promise.all(
packageNames.map((name) =>
Promise.all([
writeFileAsync(
`packages/${name}/README.md`,
readme
.replace(/@boilerz\/tsconfig/g, `@boilerz/${name}`)
.replace('> TS Config.', `> ${config.description}`),
),
writeFileAsync(
`packages/${name}/tsconfig.json`,
JSON.stringify(
name.includes('production') ? config.production : config.base,
null,
2,
),
),
writeFileAsync(
`packages/${name}/package.json`,
JSON.stringify(createPackageFile(name, config), null, 2),
),
]),
),
);
}
async function generate(
configs: Config[] = [defaultConfig, cliConfig, reactNativeConfig],
): Promise<void> {
readme = (await readFileAsync('README.md')).toString('utf-8');
await rmdirAsync('packages', { recursive: true });
await Promise.all(configs.map(generatePackage));
}
generate().catch(console.error);
|
a2fff413a899a9e270c9e2556b54aaed0d382b79
|
TypeScript
|
ls-espirit/fsxa-ui
|
/src/documentation/routes.ts
| 2.921875
| 3
|
const components = [
{
label: "Accordion",
path: "/components/accordion",
meta: {
description:
"provides an item with a title which, when clicked, expands to show the element text.",
},
children: [],
},
{
label: "Button",
path: "/components/button",
meta: {
description:
"shows a button allowing users to take actions and make choices with a single tap (or click).",
},
children: [],
},
{
label: "Container",
path: "/components/container",
meta: {
description: "provides a basic layout element to structure your site.",
},
children: [],
},
{
label: "Counter",
path: "/components/counter",
meta: {
description:
"displays a layout block showing a number with a corresponding text (usually somthing countable).",
},
children: [],
},
{
label: "Dropdown",
path: "/components/dropdown",
meta: {
description: "displays a dropdown list with a number of options.",
},
children: [],
},
{
label: "Headline",
path: "/components/headline",
meta: {
description:
"is a structuring element representing a page's or section's title.",
},
children: [],
},
{
label: "Image",
path: "/components/image",
meta: {
description: "displays a picture with optional dimming and zoom effect.",
},
children: [],
},
{
label: "ImageSlider",
path: "/components/image-slider",
meta: {
description: "provides a slider to showcase your images.",
},
children: [],
},
{
label: "Navigation",
path: "/components/navigation",
meta: {
description: "allows users to navigate through your site's structure.",
},
children: [],
},
{
label: "NewsDetail",
path: "/components/news-detail",
meta: {
description:
"a news section consisting of title, teaser, text, an image, and some other elements.",
},
children: [],
},
{
label: "Quote",
path: "/components/quote",
meta: {
description:
"displays some text in a colored box next to a quotation mark.",
},
children: [],
},
{
label: "ProductListItem",
path: "/components/product-list-item",
meta: {
description:
"is used to display product information in the context of a ListSection. It will be as wide as the surrounding element.",
},
children: [],
},
{
label: "LineSeparator",
path: "/components/line-separator",
meta: {
description:
"can be used to separate content sections with a horizontal bar.",
},
children: [],
},
{
label: "Slider",
path: "/components/slider",
meta: {
description:
"provides a fully functional slider to display your contents.",
},
children: [],
},
];
const sections = [
{
label: "AccordionSection",
path: "/sections/accordion-section",
meta: {
description:
"consists of multiple connected text accordions which open and close when clicked on.",
},
children: [],
},
{
label: "FullWidthSliderSection",
path: "/sections/full-width-slider-section",
meta: {
description:
"provides a customizable section with a big slider component, for images or other content you want to showcase.",
},
children: [],
},
{
label: "GoogleMapsSection",
path: "/sections/google-maps-section",
meta: {
description:
"for showing Google Maps, typically showing a set of locations highlighted with markers.",
},
children: [],
},
{
label: "HeaderSection",
path: "/sections/header-section",
meta: {
description:
"displays a title together with a background image and (optionally) breadcrumbs.",
},
children: [],
},
{
label: "InterestingFactsSection",
path: "/sections/interesting-facts-section",
meta: {
description:
"displays a text together with a background image and counter elements.",
},
children: [],
},
{
label: "ListSection",
path: "/sections/list-section",
meta: {
description:
"displays numerous items, with the possibility to also specify and display filters for them.",
},
children: [],
},
{
label: "ProductDetailSection",
path: "/sections/product-detail-section",
meta: {
description:
"displays a detailed product description including a collection of pictures and additional information.",
},
children: [],
},
{
label: "TeaserSection",
path: "/sections/teaser-section",
meta: {
description: "displays information next to a picture.",
},
children: [],
},
];
const routes = [
{
label: "Introduction",
path: "/",
children: [],
},
{
label: "Getting Started",
path: "/getting-started",
children: [],
},
{
label: "Components",
path: "/components",
children: components.sort((a, b) => a.label.localeCompare(b.label)),
},
{
label: "Sections",
path: "/sections",
children: sections.sort((a, b) => a.label.localeCompare(b.label)),
},
];
export default routes;
|
ce2020d2d015755eb7693acb38de7cb6ab615177
|
TypeScript
|
matiashrnndz/flight-data-app
|
/FlightDataMW/Services-Api/src/controller/flightController.ts
| 2.515625
| 3
|
import axios from 'axios';
import * as convert from 'xml-js';
import { Logger } from '../logger/loggerApi';
export class FlightController {
constructor() { }
async deliver(url: string, flight, protocol: string) {
axios.post(url, flight, {
headers: { "Content-Type": protocol }
})
.then((res) => {
Logger.info(`Flight dlivered to ${url} correctly : ${JSON.stringify(flight)}`);
})
.catch((error) => {
Logger.error("FlightController > deliver threw " + error);
});
}
}
|
30ea58a68a3cfcb77237fc2f2e9ca9c9f6097f94
|
TypeScript
|
amarczuk/that-build-library
|
/src/utils/clean.ts
| 2.890625
| 3
|
import * as fs from 'fs'
import * as del from 'del'
/**
* Clean a folder (remove its contents)
*/
export async function clean(fld: string, leaveRoot: boolean = false) {
if (!leaveRoot) {
await del([fld])
} else {
const promises = []
fs.readdirSync(fld).forEach(child => {
promises.push(del(fld + '/' + child))
})
return Promise.all(promises)
}
}
|
2ee38c9b57e75ef6daa9355bad9ee90d420b82d9
|
TypeScript
|
SocialGouv/archimail-pst-extractor
|
/src/ColumnDescriptor.ts
| 2.71875
| 3
|
import long from "long";
import type { NodeInfo } from "./NodeInfo";
export class ColumnDescriptor {
private readonly _ibData: number;
public get ibData(): number {
return this._ibData;
}
private readonly _cbData: number;
public get cbData(): number {
return this._cbData;
}
private readonly _type: number;
public get type(): number {
return this._type;
}
private readonly _iBit: number;
public get iBit(): number {
return this._iBit;
}
private readonly _id: number;
public get id(): number {
return this._id;
}
/**
* Creates an instance of ColumnDescriptor.
*/
constructor(nodeInfo: NodeInfo, offset: number) {
this._type = nodeInfo
.seekAndReadLong(long.fromValue(offset), 2)
.toNumber(); // & 0xFFFF;
this._id = nodeInfo
.seekAndReadLong(long.fromValue(offset + 2), 2)
.toNumber(); // & 0xFFFF;
this._ibData = nodeInfo
.seekAndReadLong(long.fromValue(offset + 4), 2)
.toNumber(); // & 0xFFFF;
this._cbData = nodeInfo.pstNodeInputStream.read(); // & 0xFFFF;
this._iBit = nodeInfo.pstNodeInputStream.read(); // & 0xFFFF;
}
/**
* JSON stringify the object properties.
*/
public toJSON(): unknown {
return this;
}
}
|
879e6c8e9561e7fd4974368f4aca95837123e209
|
TypeScript
|
tmplinshi/vscode-autohotkey
|
/src/parser/model.ts
| 2.890625
| 3
|
import * as vscode from "vscode";
export interface Script {
methods: Method[];
refs: Ref[];
labels: Label[];
variables: Variable[];
blocks: Block[];
}
export interface Variable {
name: string; document: vscode.TextDocument; line: number; character: number;
method: Method; isGlobal: boolean;
}
export class Label {
constructor(public name: string, public document: vscode.TextDocument, public line: number, public character: number) { }
}
export class Ref {
constructor(public name: string, public document: vscode.TextDocument, public line: number, public character: number) { }
}
export class Block {
constructor(public name: string, public document: vscode.TextDocument, public line: number, public character: number) { }
}
export class Method {
public params: string[];
public variables: Variable[];
public full: string;
public endLine: number;
constructor(public origin: string, public name: string, public document: vscode.TextDocument,
public line: number, public character: number, public withQuote: boolean, public comment: string) {
this.buildParams();
this.variables = []
}
private buildParams() {
const refPattern = /\s*\((.+?)\)\s*$/;
if (this.origin != this.name) {
const paramsMatch = this.origin.match(refPattern);
if (paramsMatch) {
this.params = paramsMatch[1].split(",").filter(param => param.trim() != "").map(param => {
const paramMatch = param.match(/[^:=* \t]+/);
return paramMatch != null ? paramMatch[0] : param;
});
this.full = this.origin.replace(paramsMatch[1], this.params.join(","));
}
else {
this.params = []
this.full = this.origin;
}
}
}
public pushVariable(variables: Variable | Variable[]) {
if (!Array.isArray(variables)) {
variables = [variables];
}
loop: for (const variable of variables) {
for (const curVariable of this.variables) {
if (curVariable.name == variable.name) continue loop;
}
for (const paramStr of this.params) {
if (paramStr == variable.name) continue loop;
}
this.variables.push(variable)
}
}
}
|
dcbe9c8a55bebb076fd21501bd7a5ca929415832
|
TypeScript
|
anupvarghese/recipeql
|
/src/schema.ts
| 2.71875
| 3
|
import axios from "axios";
import {
GraphQLInt,
GraphQLList,
GraphQLObjectType,
GraphQLSchema,
GraphQLString
} from "graphql";
import qs from "querystring";
interface IQueryArgs {
ingredients: string[];
dish: string;
page: number;
}
interface IRecipeResponse {
results: [
{
title: string;
href: string;
ingredients: string[];
thumbnail: string;
}
];
}
const recipeType = new GraphQLList(
new GraphQLObjectType({
fields: () => ({
href: { type: GraphQLString },
ingredients: { type: GraphQLString },
thumbnail: { type: GraphQLString },
title: { type: GraphQLString }
}),
name: "recipe"
})
);
const queryType = new GraphQLObjectType({
fields: () => ({
recipes: {
args: {
dish: { type: GraphQLString },
ingredients: { type: GraphQLList(GraphQLString) },
page: { type: GraphQLInt }
},
resolve: async (_, { ingredients, dish, page = 1 }: IQueryArgs) => {
const query = qs.stringify({
i: ingredients.join(","),
p: page,
q: dish
});
const url = `http://www.recipepuppy.com/api?${query}`;
return axios
.get<IRecipeResponse>(url)
.then(res => {
return res.data.results;
})
.catch(() => {
return [];
});
},
type: recipeType
}
}),
name: "Query"
});
const schema = new GraphQLSchema({ query: queryType });
export default schema;
|
460b76200994433ddc425b913c36f2a80c3ea75e
|
TypeScript
|
anderjason/observable
|
/src/ReadOnlyObservable/index.ts
| 2.765625
| 3
|
import { ObservableBase } from "../Observable";
import { asyncGivenObservable } from "../Observable/_internal/asyncGivenObservable";
import { TypedEvent } from "../TypedEvent";
export class ReadOnlyObservable<T> implements ObservableBase<T> {
static givenObservable<T>(
observable: ObservableBase<T>
): ReadOnlyObservable<T> {
return new ReadOnlyObservable<T>(observable);
}
private _observable: ObservableBase<T>;
private _isObservable = true;
private constructor(observable: ObservableBase<T>) {
this._observable = observable;
}
get value(): T {
return this._observable.value;
}
get didChange(): TypedEvent<T> {
return this._observable.didChange;
}
toPromise(filter?: (value: T) => boolean): Promise<T> {
return asyncGivenObservable({
observable: this,
filter,
});
}
}
|
0eb3baa7ebbfd920db1fa529546577776225fb10
|
TypeScript
|
green-fox-academy/jkerezsi
|
/week-03/day-03/trees.ts
| 3.40625
| 3
|
'use strict';
// trees = [
// {type:'American Hornbeam', color:'brown', age: '12', sex:'male'},
// {type:'Gingko', color:'green', age: '10', sex:'female'},
// {type:'Honey Locust', color:'light green', age: '444', sex:'male'},
// {type:'Japanese Pagoda', color:'yellow', age: '232', sex:'female'},
// {type:'Hardy Rubber Tree', color:'dark green', age: '23', sex:'female'}
// ]
class Tree {
type: string;
leafColor: string;
age: number;
gender: string;
isEvergreen: boolean;
constructor(type:string, leafColor:string,gender:string, isEvergreen:boolean) {
this.age = 0;
this.type = type;
this.leafColor = leafColor;
this.gender = gender;
this.isEvergreen = isEvergreen;
}
giveMeInfoAboutMyTree(): void {
console.log(`Your tree is a(n) ${this.gender + ' ' + this.type} aged ${this.age} with ${this.leafColor} leaves and it is ${this.isEvergreen ? 'evergreen' : 'not evergreen'}`)
}
}
const myFirstTree: Tree = new Tree ('oak','green','female',false);
myFirstTree.giveMeInfoAboutMyTree();
|
aaaa8c4743e1f5aebfde99359f400699983dbd87
|
TypeScript
|
Hawkie/WebLib
|
/src/ts/gamelib/Actors/Helpers/Angle.test.ts
| 2.6875
| 3
|
import { VerticallyAligned } from "./Angle";
test("right", () => {
const a: number = 90;
const result: boolean = VerticallyAligned(a);
expect(result).toBe(false);
});
test("left", () => {
const a: number = -90;
const result: boolean = VerticallyAligned(a);
expect(result).toBe(false);
});
test("down", () => {
const a: number = 180;
const result: boolean = VerticallyAligned(a);
expect(result).toBe(false);
});
test("upright", () => {
const a: number = 0;
const result: boolean = VerticallyAligned(a);
expect(result).toBe(true);
});
test("upright neg tolerance", () => {
const a: number = -0.1;
const result: boolean = VerticallyAligned(a);
expect(result).toBe(true);
});
test("upright pos tolerance", () => {
const a: number = 0.1;
const result: boolean = VerticallyAligned(a);
expect(result).toBe(true);
});
|
6370a8fa3f26c6891b6b3882d363d173533bc1c8
|
TypeScript
|
kalleguld/threeJS-crash-test
|
/view/app.ts
| 2.59375
| 3
|
class ThreeTest {
readonly content: HTMLElement;
numTests = 0;
scene: THREE.Scene;
camera: THREE.PerspectiveCamera;
renderer: THREE.WebGLRenderer = null;
lights: THREE.SpotLight[] = [];
boxCircle: THREE.Group;
texture: THREE.Texture;
textureUrls = ["img/1.jpg",
"img/2.jpg",
"img/3.jpg",
"img/4.jpg",
"img/5.jpg",
"img/6.jpg",
"img/7.jpg",
"img/1.png",
"img/2.png",
"img/3.png",
"img/4.png",
"img/5.png",
]
textures: THREE.Texture[];
constructor(elem: HTMLElement) {
this.content = elem;
}
public async loop(): Promise<void> {
this.numTests++;
this.renderer = ThreeTest.createRenderer(this.content);
this.scene = new THREE.Scene();
this.lights = ThreeTest.getLights();
for (let light of this.lights) {
this.scene.add(light);
}
//this.scene.add(new THREE.AmbientLight(0xffffff, 2));
this.texture = await ThreeTest.getTexture("img/256.jpg");
//this.scene.add(ThreeTest.getBoxSpiral(texture, 200));
//let otherBoxes = ThreeTest.getBoxSpiral(texture, 200);
//otherBoxes.rotateZ(Math.PI);
//this.scene.add(otherBoxes);
this.textures = await ThreeTest.getTextures(this.textureUrls);
this.boxCircle = ThreeTest.getBoxCircle(this.textures, 25, 5);
this.scene.add(this.boxCircle);
let ground = await ThreeTest.getGround();
this.scene.add(ground);
this.camera = new THREE.PerspectiveCamera(75, 1, 0.01, 1000);
this.camera.position.set(0, 2, 10);
console.debug(this.scene.toJSON());
this.startAnimate();
}
public static createRenderer(parent: HTMLElement) {
let result = new THREE.WebGLRenderer({
antialias: true,
});
result.shadowMap.type = THREE.PCFSoftShadowMap;
result.shadowMap.enabled = true;
while (parent.children.length > 0) {
parent.removeChild(parent.firstChild);
}
result.setSize(parent.clientWidth, parent.clientHeight);
parent.appendChild(result.domElement);
return result;
}
private static getLights(): THREE.SpotLight[] {
let result = [];
let numLights = 5;
for (let i = 0; i < numLights; i++) {
let iPi = i / numLights * 2 * Math.PI;
let color = new THREE.Vector3(
0.5 + 0.5 * Math.sin(iPi),
0.5 + 0.5 * Math.cos(iPi),
1);
let light = new THREE.SpotLight(ThreeTest.getHexColor(color), 6 / numLights, 25);
//let light = new THREE.SpotLight(0xffffff, 2, 25);
light.position.set(4 * Math.sin(iPi), 7 * Math.cos(iPi), 0);
light.castShadow = true;
light.shadow.mapSize.width = 1024;
light.shadow.mapSize.height = 1024;
result.push(light);
}
return result;
}
private static getBoxCircle(textures: THREE.Texture[],
numBoxes: number,
radius: number
): THREE.Group {
let result = new THREE.Group();
for (let i = 0; i < numBoxes; i++) {
let geo = new THREE.BoxGeometry(1, 1, 1);
let mat = new THREE.MeshPhongMaterial({
map: textures[i % textures.length]
});
let cube = new THREE.Mesh(geo, mat);
cube.castShadow = true;
let iPi = i / numBoxes * Math.PI * 2;
cube.position.set(
radius * Math.sin(iPi),
0.5,
radius * Math.cos(iPi))
cube.rotateY(iPi);
result.add(cube);
}
return result;
}
private static getBoxSpiral(texture: THREE.Texture, numBoxes: number): THREE.Group {
let result = new THREE.Group();
for (let i = 0; i < numBoxes; i++) {
result.add(ThreeTest.getSingleSpiralBox(i, texture));
}
return result;
}
private static getSingleSpiralBox(boxNum: number, texture: THREE.Texture): THREE.Mesh {
let geo = new THREE.BoxGeometry(1, 1, 1);
let tex = texture.clone();
tex.wrapS = tex.wrapT = THREE.MirroredRepeatWrapping;
tex.repeat.set(boxNum / 10 + 1, boxNum / 10 + 1);
tex.needsUpdate = true;
let mat = new THREE.MeshPhongMaterial({
map: tex,
});
let cube = new THREE.Mesh(geo, mat);
cube.castShadow = cube.receiveShadow = true;
cube.position.set(Math.sin(boxNum / 3) * 5, Math.cos(boxNum / 3) * 5, boxNum);
return cube;
}
private static async getGround(): Promise<THREE.Object3D> {
let geo = new THREE.PlaneGeometry(50, 50);
let tex = await ThreeTest.getTexture("img/212.jpg");
tex.repeat.set(50, 50);
tex.wrapS = tex.wrapT = THREE.MirroredRepeatWrapping;
let mat = new THREE.MeshPhongMaterial({
map: tex,
});
let mesh = new THREE.Mesh(geo, mat);
mesh.receiveShadow = true;
mesh.rotateX(Math.PI / -2);
mesh.position.y = -0.5;
return mesh;
}
private startAnimate() {
let t = performance.now();
this.animate(t, t);
}
private animate(
startTime: number,
currentTIme: number
): void {
if (this.time(currentTIme - startTime)) {
this.renderer.render(this.scene, this.camera);
requestAnimationFrame(c => this.animate(startTime, c));
}
else
this.loop();
}
private time(currentTime: number): boolean {
let lifetime = 1000;
//if (currentTime > lifetime)
// return false;
//this.scene.remove(this.boxCircle);
//let boxCircle = ThreeTest.getBoxCircle(this.textures,
// ThreeTest.polate(5, 35, currentTime / lifetime),
// 5);
//this.boxCircle = boxCircle;
//this.scene.add(boxCircle);
let i = 0;
for (let box of this.boxCircle.children) {
box.position.y = Math.abs(Math.sin(i/4 + (currentTime / 200)));
i++;
}
//let iPi = (currentTime / 10000);
//this.camera.position.x = 10 * Math.sin(iPi);
//this.camera.position.z = 10 * Math.cos(iPi);
return true;
}
//private time(currentTime: number): boolean {
// let endTime = 10000;
// if (currentTime > endTime) {
// return false;
// }
// let cameraZStart = 250;
// let cameraEnd = 0;
// let cameraPos = ThreeTest.polate(cameraZStart, cameraEnd, currentTime / endTime);
// this.camera.position.z = cameraPos;
// for (let light of this.lights) {
// light.position.z = cameraPos;
// }
// return true;
//}
private static polate(start: number, stop: number, normalizedPos: number): number{
return (start * (1-normalizedPos)) + (stop * normalizedPos);
}
private static getTexture(url: string): Promise<THREE.Texture> {
return new Promise<THREE.Texture>((resolve, reject) => {
let loader = new THREE.TextureLoader();
loader.load(url, resolve);
});
}
private static getTextures(urls: string[]): Promise<THREE.Texture[]> {
let promises = [];
for (let url of urls) {
promises.push(ThreeTest.getTexture(url));
}
return Promise.all(promises);
}
private static getHexColor(normalizedRgb: THREE.Vector3): number {
let r = normalizedRgb.x * 255;
let g = normalizedRgb.y * 255;
let b = normalizedRgb.z * 255;
return r * (2 << 16) + g * (2 << 8) + b;
}
}
window.onload = () => {
var el = document.getElementById('content');
var threeTest = new ThreeTest(el);
threeTest.loop();
window["threeTest"] = threeTest;
};
|
873bbc6b604f4e1b66d71b7be7b4902ae993ecb2
|
TypeScript
|
dongnguyenvie/Design-patterns-notes
|
/creational-patterns/builder-pattern/builder-pattern.ts
| 3.4375
| 3
|
/**
* WHEN TO USE THE BUILDER PATTERN
*
* - When dealing a complex object that requires a lot of parammeters
* - When trying to prevent mistakes from creating a complex objects
* - When trying to avoid unreadable, big constructors that are sometimes required complex object creation
*/
;(() => {
const NonePattern = () => {
class OnlineStoreAccount {
private id: string
private name: string
private address: string
private budget: number
private discountRate: number
constructor(
id: string,
name: string,
address: string,
budget: number,
discountRate: number
) {
this.id = id
this.name = name
this.address = address
this.budget = budget
this.discountRate = discountRate
}
}
const johnSmith = new OnlineStoreAccount('1L', 'Join Smith', 'Liberty lane 23', 100, 2)
const janeTaylor = new OnlineStoreAccount('2L', 'Jane Taylor', 'Goethe Street 55', 2, 100)
console.log('none pattern', { johnSmith, janeTaylor })
// it required u must put full params. but some case u don't want to put discountRate. builder pattern will help u solving
// this thing
}
const applyPattern = () => {
class OnlineStoreAccount {
private id: string
private name: string
private address: string
private budget: number
private discountRate: number
static Builder = class {
private id: string
private name: string
private address: string
private budget: number
private discountRate: number
constructor(id: string) {
this.id = id
}
public withName(name: string) {
this.name = name
return this
}
public withAdress(address: string) {
this.address = address
return this
}
public withBudget(budget: number) {
this.budget = budget
return this
}
public withDiscountRate(discountRate: number) {
this.discountRate = discountRate
return this
}
public build() {
const onlineStoreAccount = new OnlineStoreAccount()
onlineStoreAccount.id = this.id
onlineStoreAccount.name = this.name
onlineStoreAccount.address = this.address
onlineStoreAccount.budget = this.budget
onlineStoreAccount.discountRate = this.discountRate
return onlineStoreAccount
}
}
}
// Client code
function clientCode() {
const joinSmith = new OnlineStoreAccount.Builder('1L')
.withName('JoinSmith')
.withAdress('Oxford lane 35A')
.withBudget(100)
.build()
console.log('applyPattern', { joinSmith })
}
clientCode()
}
console.log('>>>> BUILDER PATTERN')
NonePattern()
applyPattern()
console.log('BUILDER PATTERN <<<<')
console.log('\n')
})()
|
5f966947521c55e93635707b3f8348a8d203c857
|
TypeScript
|
01alchemist/js-to-ts-migration
|
/src/components/migration/index.spec.ts
| 2.734375
| 3
|
import * as path from "path";
import * as fs from "fs";
import { migrate } from ".";
describe("Migration test suite", () => {
describe("Export tests", () => {
describe("When passing a commonjs single function module export", () => {
it("Should replace module.exports with export", () => {
const script = "module.exports = someFunction;";
const expected = "export = someFunction;\n";
expect(migrate(script)).toBe(expected);
});
});
describe("When passing a commonjs single require module export", () => {
it("Should replace module.exports with export", () => {
const script = `module.exports.constants = require("./constants.js");`;
const expected = `export const constants = require("./constants.js");\n`;
expect(migrate(script)).toBe(expected);
});
});
describe("When passing a commonjs single object module export", () => {
it("Should replace module.exports with export", () => {
const script = "module.exports = { someProp: 'someValue' };";
const expected = "export = { someProp: 'someValue' };\n";
expect(migrate(script)).toBe(expected);
});
});
describe("When passing a commonjs multiple functions exports with same name", () => {
it("Should remove commonjs export and export functions directly", () => {
const script = `
function someFunction(){}
function someAnotherFunction (){}
module.exports.someFunction = someFunction;
module.exports.someAnotherFunction = someAnotherFunction;`;
const expected = `
export function someFunction(){}
export function someAnotherFunction (){}\n`;
expect(migrate(script)).toBe(expected);
});
});
describe("When passing a commonjs multiple const exports with same name", () => {
it("Should remove commonjs export and export functions directly", () => {
const script = `
const someVar = {};
const someAnotherVar = {};
module.exports.someVar = someVar;
module.exports.someAnotherVar = someAnotherVar;`;
const expected = `
export const someVar = {};
export const someAnotherVar = {};\n`;
expect(migrate(script)).toBe(expected);
});
});
describe("When passing a commonjs multiple functions exports with different names", () => {
it("Should replace commonjs exports with const export", () => {
const script = `
function someFunction(){};
function someAnotherFunction(){};
module.exports.someFunction2 = someFunction;
module.exports.someAnotherFunction2 = someAnotherFunction;`;
const expected = `
function someFunction(){};
function someAnotherFunction(){};
export const someFunction2 = someFunction;
export const someAnotherFunction2 = someAnotherFunction;\n`;
expect(migrate(script)).toBe(expected);
});
});
describe("When passing a commonjs multiple functions exports with different names", () => {
it("Should remove same name exports and directly export functions and replace different name exports with const", () => {
const script = `
function someFunction(){};
function someAnotherFunction(){};
module.exports.someFunction = someFunction;
module.exports.someAnotherFunction = someAnotherFunction;
module.exports.someFunction2 = someFunction;
module.exports.someAnotherFunction2 = someAnotherFunction;`;
const expected = `
export function someFunction(){};
export function someAnotherFunction(){};
export const someFunction2 = someFunction;
export const someAnotherFunction2 = someAnotherFunction;\n`;
expect(migrate(script)).toBe(expected);
});
});
describe("When passing a commonjs with all type of exports", () => {
it("Should replace module.exports with export, remove same name exports and directly export functions and replace different name exports with const", () => {
const script = `
module.exports = {
someProp: 'someValue'
};
function someFunction(){};
function someAnotherFunction(){};
module.exports.someFunction = someFunction;
module.exports.someAnotherFunction = someAnotherFunction;
module.exports.someFunction2 = someFunction;
module.exports.someAnotherFunction2 = someAnotherFunction;`;
const expected = `
export = {
someProp: 'someValue'
};
export function someFunction(){};
export function someAnotherFunction(){};
export const someFunction2 = someFunction;
export const someAnotherFunction2 = someAnotherFunction;\n`;
expect(migrate(script)).toBe(expected);
});
});
});
describe("Import tests", () => {
describe("When passing a commonjs const require", () => {
it("Should replace const with import", () => {
const script = `const resource = require("../resource");`;
const expected = `import resource = require("../resource");\n`;
expect(migrate(script)).toBe(expected);
});
});
describe("When passing a commonjs const require with property access", () => {
it("Should not replace const with import", () => {
const script = `const { Types } = require("mongoose").Schema;
const { createSchemaMethod } = require("./server/service/index");
const schema = require("mongoose").Schema;
const resource = require("../resource");`;
const expected = `const { Types } = require("mongoose").Schema;
import { createSchemaMethod } from "./server/service/index";
const schema = require("mongoose").Schema;
import resource = require("../resource");\n`;
expect(migrate(script)).toBe(expected);
});
});
describe("When passing a named commonjs const require", () => {
it("Should replace const with import and '= require()' with from", () => {
const script = `const { Industry } = require("../../../../models");
const { productLabelByProductId } = require("../../../../models/constants");`;
const expected = `import { Industry } from "../../../../models";
import { productLabelByProductId } from "../../../../models/constants";\n`;
expect(migrate(script)).toBe(expected);
});
});
describe("When passing a multi-line named commonjs const require", () => {
it("Should replace const with import and '= require()' with from", () => {
const script = fs.readFileSync(
path.resolve(__dirname, "./__testdata__/module1.js"),
"utf-8"
);
const expected = fs.readFileSync(
path.resolve(__dirname, "./__testdata__/module1.ts"),
"utf-8"
);
expect(migrate(script)).toBe(expected);
});
});
describe("When passing imports with spread as members", () => {
it("Should replace object spread to import as", () => {
const script = `const { some: someAs, one: OneAS } = require("some-module");`;
const expected = `import { some as someAs, one as OneAS } from "some-module";\n`;
expect(migrate(script)).toBe(expected);
});
it("Should not replace object spread of non-require variables", () => {
const script = `
const { some: someAs, one: OneAS } = require("some-module");
const { some: someAs, one: OneAS } = someVar;`;
const expected = `
import { some as someAs, one as OneAS } from "some-module";
const { some: someAs, one: OneAS } = someVar;\n`;
expect(migrate(script)).toBe(expected);
});
it("Should replace object spread to import as in js file", () => {
const script = fs.readFileSync(
path.resolve(__dirname, "./__testdata__/module2.js"),
"utf-8"
);
const expected = fs.readFileSync(
path.resolve(__dirname, "./__testdata__/module2.ts"),
"utf-8"
);
expect(migrate(script)).toBe(expected);
});
});
});
});
|
d0c8d9cee355d5b7c9f080d0ade076f304b83604
|
TypeScript
|
pshihn/lit-matrix
|
/src/parser.ts
| 3.515625
| 4
|
import { Token } from './tokenizer';
type Associativity = 'left' | 'right';
const associativityMap: { [op: string]: Associativity } = {
'!': 'right',
'*': 'left',
'/': 'left',
'+': 'left',
'-': 'left'
};
const precedenceMap: { [op: string]: number } = {
'!': 4,
'*': 3,
'/': 3,
'+': 2,
'-': 2
};
export interface SyntaxNode {
token: Token;
leftChild?: SyntaxNode;
rightChild?: SyntaxNode;
}
export function parse(tokens: Token[]): SyntaxNode {
const outStack: SyntaxNode[] = [];
const stack: Token[] = [];
const pushNodeToOutStack = (pop?: Token) => {
if (pop) {
const onode: SyntaxNode = {
token: pop,
rightChild: outStack.pop(),
leftChild: outStack.pop()
};
outStack.push(onode);
}
};
tokens.forEach((t) => {
switch (t.type) {
case 'literal':
case 'variable':
outStack.push({
token: t
});
break;
case 'operator':
while (true) {
let check = false;
const topOfStack = stack.length ? stack[stack.length - 1] : null;
if (topOfStack && topOfStack.type === 'operator') {
const o = topOfStack.value as string;
const tv = t.value as string;
if (precedenceMap[o] > precedenceMap[tv]) {
check = true;
} else if (precedenceMap[o] === precedenceMap[tv] && associativityMap[o] === 'left') {
check = true;
}
}
if (check) {
pushNodeToOutStack(stack.pop());
} else {
break;
}
}
stack.push(t);
break;
case 'lparen':
stack.push(t);
break;
case 'rparen':
while (stack.length) {
const pop = stack.pop()!;
if (pop.type === 'lparen') {
break;
} else {
pushNodeToOutStack(pop);
}
}
break;
}
});
while (stack.length) {
pushNodeToOutStack(stack.pop());
}
if (outStack.length !== 1) {
throw new Error('Failed to parse expression');
}
return outStack[0];
}
|
d745aa80a99f7a3d53498ecb980eed284c966f0f
|
TypeScript
|
raster-foundry/raster-foundry-docs
|
/src/app/services/auth.service.ts
| 2.53125
| 3
|
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Http, Response } from '@angular/http';
import { JwtHelper } from 'angular2-jwt';
import { SettingsService } from './settings.service';
export class TokenExpiredError extends Error {
constructor(public message: string) {
super(message);
this.name = 'Token Expired Error';
this.message = message;
this.stack = (<any>new Error()).stack;
}
toString() {
return `${this.name}: ${this.message}`;
}
}
export class TokenParseError extends Error {
constructor(public message: string, error?: Error) {
super(message);
this.name = 'Token Parse Error';
this.message = message;
this.stack = error ? error.stack : (<any>new Error()).stack;
}
static fromError(error: Error) {
return new TokenParseError(error.message, error);
}
toString() {
return `${this.name}: ${this.message}`;
}
}
@Injectable()
export class AuthService {
private sessionToken: string;
jwtHelper: JwtHelper = new JwtHelper();
constructor(private http: Http, private settingsService: SettingsService) { }
validateToken(token: string): Error | any {
let error: Error;
try {
let decoded = this.jwtHelper.decodeToken(token);
if (this.jwtHelper.isTokenExpired(token)) {
let expiredAt = this.jwtHelper.getTokenExpirationDate(token)
error = new TokenExpiredError(`Expired at ${expiredAt}`);
} else if (!decoded) {
error = new TokenParseError('Error parsing token');
} else {
return decoded;
}
} catch (e) {
error = TokenParseError.fromError(e);
}
return error;
}
set token(token: string) {
let validationResult = this.validateToken(token);
if (validationResult instanceof Error) {
throw (validationResult as Error);
} else {
this.sessionToken = token;
}
}
public setToken(token: string) {
try {
let decodedToken = this.jwtHelper.decodeToken(token);
if (this.jwtHelper.isTokenExpired(token)) {
return { error: 'Token is expired' };
}
this.sessionToken = token;
return decodedToken;
} catch (e) {
return { error: e.message };
}
}
get token() {
if (this.sessionToken && this.jwtHelper.isTokenExpired(this.sessionToken)) {
this.sessionToken = null;
}
return this.sessionToken;
}
public getSessionToken(refreshToken: string): Observable<any> {
let requestUrl = `${this.settingsService.apiUrl}/tokens`
return this.http.post(requestUrl, {refresh_token: refreshToken});
}
}
|
148a977a3d1ada01aa8452eb59241371b4d2b3ee
|
TypeScript
|
isabella232/helium-js
|
/packages/http/src/models/PendingTransaction.ts
| 2.734375
| 3
|
import camelcaseKeys from 'camelcase-keys'
import { Balance, CurrencyType } from '@helium/currency'
import DataModel from './DataModel'
export interface HTTPPendingTransactionObject {
type: string
txn: object | null
status: string
hash: string
failed_reason: string | null
created_at: string
updated_at: string
}
export type PendingTransactionData = PendingTransaction
function processTxn(transaction: HTTPPendingTransactionObject): any {
if (transaction.status === 'received') return null
const rawTxn = transaction.txn as any
const txn = camelcaseKeys(rawTxn)
switch (transaction.type) {
case 'payment_v1':
return {
...txn,
amount: new Balance(txn.amount, CurrencyType.default),
}
case 'payment_v2':
return {
...txn,
payments: txn.payments.map((p: any) => ({
...p,
amount: new Balance(p.amount, CurrencyType.default),
})),
totalAmount: new Balance(
txn.payments.reduce((sum: number, { amount }: any) => sum + amount, 0),
CurrencyType.default,
),
}
default:
return txn
}
}
export default class PendingTransaction extends DataModel {
public type: string
public txn: any
public status: string
public hash: string
public failedReason: string | null
public createdAt: string
public updatedAt: string
constructor(transaction: HTTPPendingTransactionObject) {
super()
this.type = transaction.type
this.txn = processTxn(transaction)
this.status = transaction.status
this.failedReason = transaction.failed_reason
this.hash = transaction.hash
this.createdAt = transaction.created_at
this.updatedAt = transaction.updated_at
}
get data(): PendingTransactionData {
return this
}
}
|
d4e3c6cf34007e15bc6900f30c4bef19537a25cf
|
TypeScript
|
ike18t/mock_module
|
/lib/test-fixtures.ts
| 2.609375
| 3
|
import { NgModule, Component, Injectable, Directive, Pipe, PipeTransform } from '@angular/core';
@Directive({selector: '[example-directive]'})
export class ExampleDirective {}
@Pipe({name: 'examplePipe'})
export class ExamplePipe implements PipeTransform {
transform(text: string) {
return `Example: ${text}`;
}
}
@Injectable()
export class ExampleService {
get(id: number) {
return `Got: ${id}`;
}
}
@Component({
selector: 'example-private-component',
template: '<span>Private thing</span>'
})
export class ExamplePrivateComponent { }
@Component({
selector: 'example-component',
template: '<span>My Example</span>'
})
export class ExampleComponent { }
@NgModule({
declarations: [ ExamplePrivateComponent, ExampleComponent, ExamplePipe, ExampleDirective ],
exports: [ ExampleComponent, ExamplePipe, ExampleDirective ],
providers: [ ExampleService ]
})
export class ChildModule {}
@NgModule({
imports: [ ChildModule ],
})
export class ParentModule {}
|
e48a6c3e6ffbc85d00ec41367fb839722b7ebab7
|
TypeScript
|
mooyoul/is-webp-extended
|
/index.ts
| 2.9375
| 3
|
const RIFF = new Uint8Array([
0x52, 0x49, 0x46, 0x46,
]);
const WEBP = new Uint8Array([
0x57, 0x45, 0x42, 0x50,
]);
const ANMF = new Uint8Array([
0x41, 0x4e, 0x4d, 0x46,
]);
export async function isWebP(input: ArrayBuffer | Blob) {
const chunk = await readBytes(input, 0, 12);
const buf = new Uint8Array(chunk);
return isEqual(RIFF, buf.slice(0, 4)) &&
isEqual(WEBP, buf.slice(8, 12));
}
export async function isAnimatedWebP(input: ArrayBuffer | Blob) {
if (await isWebP(input) === false) {
return false;
}
let offset = 12;
const size = getSize(input);
do {
const bufHeader = await readBytes(input, offset, 8);
offset += 8;
const chunkType = new Uint8Array(bufHeader.slice(0, 4));
const [ payloadSize ] = new Uint32Array(bufHeader.slice(4, 8));
offset += payloadSize;
if (isEqual(ANMF, chunkType)) {
return true;
}
} while (offset <= size);
return false;
}
function readBytes(input: Blob | ArrayBuffer, offset: number, size: number): Promise<ArrayBuffer> {
if (input instanceof Blob) {
return new Promise<ArrayBuffer>((resolve, reject) => {
const reader = new FileReader();
reader.onerror = (e) => {
reader.onerror = null;
reader.onload = null;
reject(e);
};
reader.onload = (e) => {
reader.onerror = null;
reader.onload = null;
resolve(e.target!.result as ArrayBuffer);
};
reader.readAsArrayBuffer(
input.slice(offset, offset + size),
);
});
}
return Promise.resolve(input.slice(offset, offset + size));
}
function getSize(input: Blob | ArrayBuffer) {
return input instanceof Blob ?
input.size :
input.byteLength;
}
function isEqual(a: Uint8Array, b: Uint8Array) {
if (a.byteLength !== b.byteLength) {
return false;
}
const maxLength = Math.max(a.byteLength, b.byteLength);
for (let i = 0 ; i < maxLength ; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
|
6b6eedc7ffd915d880820bd5910f297ed3d7bd8b
|
TypeScript
|
atlj/kelime-oyunu
|
/src/utils/validate.ts
| 3.046875
| 3
|
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
function validateGame(obj): boolean {
let result = true;
if (
typeof obj !== "object" ||
typeof obj.name !== "string" ||
typeof obj.time !== "number" ||
typeof obj.questions !== "object" || //Might be unnecessary
!Array.isArray(obj.questions)
) {
return false;
}
obj.questions.forEach((question) => {
if (
typeof question.answer !== "string" ||
typeof question.question !== "string"
) {
result = false;
}
});
return result;
}
export { validateGame };
|
2c628351542945ed1a343b737e8463d1aca76624
|
TypeScript
|
rsboarder/Evo-UI-Kit
|
/projects/evo-ui-kit/src/lib/components/evo-paginator/evo-paginator.component.ts
| 2.765625
| 3
|
import { Component, Output, EventEmitter, Input, ChangeDetectionStrategy } from '@angular/core';
export interface PageEvent {
currentPage: number;
previousPage: number;
pageSize: number;
pagesTotal: number;
}
// use only odd numbers please
const PAGES_VISIBLE = 5;
@Component({
selector: 'evo-paginator',
templateUrl: './evo-paginator.component.html',
styleUrls: ['./evo-paginator.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class EvoPaginatorComponent {
@Output() pageClick = new EventEmitter<PageEvent>();
@Input('currentPage') set setCurrentPage(value: string | number) {
this.currentPage = parseInt(value as string, 10) || 1;
}
@Input('itemsTotal') set setItemsTotal(itemsTotal: number) {
this.itemsTotal = itemsTotal > 0 ? itemsTotal : 0;
this.updatePagesList();
}
@Input('pageSize') set setPageSize(pageSize: number) {
this.pageSize = pageSize > 0 ? pageSize : 10;
this.updatePagesList();
}
pagesTotal = 1;
hasMinPage = false;
hasMaxPage = false;
pagesList = [1];
private pageSize = 10;
private itemsTotal = 0;
private currentPage = 1; // starts with 1
onPageClick(page: number) {
if (page === this.currentPage) {
return;
}
const payload: PageEvent = {
currentPage: page,
previousPage: this.currentPage,
pageSize: this.pageSize,
pagesTotal: this.pagesTotal,
};
this.currentPage = page;
this.pageClick.emit(payload);
this.updatePagesList();
}
isActivePage(page: string | number) {
return parseInt(page as string, 10) === this.currentPage;
}
private updatePagesList() {
this.pagesList = [];
this.pagesTotal = Math.ceil(this.itemsTotal / this.pageSize) || 1;
const halfVisible = (PAGES_VISIBLE - 1) / 2;
if (this.currentPage > this.pagesTotal) {
return;
}
const createPagesList = (total: number, getItem: (index: number) => number) => {
for (let index = 0; index < total; index++) {
this.pagesList.push(getItem(index));
}
};
if (this.pagesTotal <= PAGES_VISIBLE + 2) {
this.hasMinPage = false;
this.hasMaxPage = false;
return createPagesList(this.pagesTotal, (index) => index + 1);
}
if (this.currentPage - 1 < halfVisible + 2) {
this.hasMinPage = false;
this.hasMaxPage = true;
return createPagesList(PAGES_VISIBLE + 1, (index) => index + 1);
}
if (this.currentPage - 1 > this.pagesTotal - PAGES_VISIBLE) {
this.hasMinPage = true;
this.hasMaxPage = false;
return createPagesList(PAGES_VISIBLE + 1, (index) => index + this.pagesTotal - PAGES_VISIBLE);
}
this.hasMinPage = true;
this.hasMaxPage = true;
return createPagesList(PAGES_VISIBLE, (index) => index + this.currentPage - halfVisible);
}
}
|
a87fec5852ce808ab7c3ea45d58ed596424ab131
|
TypeScript
|
sea5625/class_mall
|
/src/apis/products.ts
| 2.6875
| 3
|
import axios from "axios";
import { PAGINATION_LIMIT } from "../utills/const";
export async function getAllProducts() {
const response: any = await axios.get<ProductModel>(
`http://localhost:4000/products`
);
return response;
}
export async function getProducts(payload: number) {
const response = await getAllProducts();
const indexOf = payload === 1 ? 0 : PAGINATION_LIMIT * (payload - 1);
return {
products: [...response.data]
.sort((a, b) => b.score - a.score)
.splice(indexOf, PAGINATION_LIMIT),
total: response.length
};
}
export interface ProductModel {
id: string;
title: string;
coverImage: string;
price: number;
score: number;
availableCoupon?: undefined | boolean;
}
|
748d56d12512f83c7a9b74a6965acd712aed96a5
|
TypeScript
|
FishOrBear/csg.ts
|
/src/core/math/Polygon3.ts
| 2.875
| 3
|
import { solidFromSlices } from "../../api/solidFromSlices";
import { CAG } from "../CAG";
import { fromPointsNoCheck } from "../CAGFactories";
import { areaEPS, getTag, _CSGDEBUG } from "../constants";
import { CSG } from "../CSG";
import { fromPolygons } from "../CSGFactories";
import { Matrix4x4 } from "./Matrix4";
import { Plane } from "./Plane";
import { Side } from "./Side";
import { Vector2D } from "./Vector2";
import { Vector3D } from "./Vector3";
import { Vertex3D } from "./Vertex3";
/** Class Polygon
* Represents a convex polygon. The vertices used to initialize a polygon must
* be coplanar and form a convex loop. They do not have to be `Vertex`
* instances but they must behave similarly (duck typing can be used for
* customization).
* <br>
* Each convex polygon has a `shared` property, which is shared between all
* polygons that are clones of each other or were split from the same polygon.
* This can be used to define per-polygon properties (such as surface color).
* <br>
* The plane of the polygon is calculated from the vertex coordinates if not provided.
* The plane can alternatively be passed as the third argument to avoid calculations.
*
*表示凸多边形。 用于初始化多边形的顶点必须共面并形成凸环。
*每个凸多边形都有一个`shared`属性,在所有属性之间共享
*多边形是彼此克隆或从同一多边形分割的多边形。
*这可用于定义每个多边形属性(例如表面颜色)。
*/
export class Polygon
{
cachedBoundingSphere: any;
cachedBoundingBox: any;
sides: Side[];
cachePoints2d: Vector2D[];
constructor(public vertices: Vertex3D[], public shared = defaultShared, public plane?: Plane)
{
if (!plane)
this.plane = Plane.fromVector3Ds(
vertices[0].pos,
vertices[1].pos,
vertices[2].pos
);
if (_CSGDEBUG)
if (!this.checkIfConvex()) throw new Error("Not convex!");
}
/** Check whether the polygon is convex. (it should be, otherwise we will get unexpected results)*/
checkIfConvex(): boolean
{
return Polygon.verticesConvex(this.vertices, this.plane.normal);
}
getSignedVolume()
{
let signedVolume = 0;
for (let i = 0; i < this.vertices.length - 2; i++)
{
signedVolume += this.vertices[0].pos.dot(
this.vertices[i + 1].pos.cross(this.vertices[i + 2].pos)
);
}
signedVolume /= 6;
return signedVolume;
}
// Note: could calculate vectors only once to speed up
// 可以只计算一次矢量来加速
getArea()
{
let polygonArea = 0;
for (let i = 0; i < this.vertices.length - 2; i++)
{
polygonArea += this.vertices[i + 1].pos
.minus(this.vertices[0].pos)
.cross(this.vertices[i + 2].pos.minus(this.vertices[i + 1].pos))
.length();
}
polygonArea /= 2;
return polygonArea;
}
// Extrude a polygon into the direction offsetvector
// Returns a CSG object
extrude(offsetvector: Vector3D): CSG
{
let newPolygons: Polygon[] = [];
let polygon1: Polygon = this;
let direction = polygon1.plane.normal.dot(offsetvector);
if (direction > 0)
polygon1 = polygon1.flipped();
newPolygons.push(polygon1);
let polygon2 = polygon1.translate(offsetvector);
let numvertices = this.vertices.length;
for (let i = 0; i < numvertices; i++)
{
let sidefacepoints: Vector3D[] = [];
let nexti = i < numvertices - 1 ? i + 1 : 0;
sidefacepoints.push(polygon1.vertices[i].pos);
sidefacepoints.push(polygon2.vertices[i].pos);
sidefacepoints.push(polygon2.vertices[nexti].pos);
sidefacepoints.push(polygon1.vertices[nexti].pos);
let sidefacepolygon = Polygon.createFromPoints(
sidefacepoints,
this.shared
);
newPolygons.push(sidefacepolygon);
}
polygon2 = polygon2.flipped();
newPolygons.push(polygon2);
return fromPolygons(newPolygons);
}
translate(offset: Vector3D)
{
return this.transform(Matrix4x4.translation(offset));
}
// returns an array with a Vector3D (center point) and a radius
boundingSphere()
{
if (!this.cachedBoundingSphere)
{
let box = this.boundingBox();
let middle = box[0].plus(box[1]).times(0.5);
let radius3 = box[1].minus(middle);
let radius = radius3.length();
this.cachedBoundingSphere = [middle, radius];
}
return this.cachedBoundingSphere;
}
// returns an array of two Vector3Ds (minimum coordinates and maximum coordinates)
boundingBox()
{
if (!this.cachedBoundingBox)
{
let minpoint: Vector3D;
let maxpoint: Vector3D;
let vertices = this.vertices;
let numvertices = vertices.length;
if (numvertices === 0)
minpoint = new Vector3D(0, 0, 0);
else
minpoint = vertices[0].pos;
maxpoint = minpoint;
for (let i = 1; i < numvertices; i++)
{
let point = vertices[i].pos;
minpoint = minpoint.min(point);
maxpoint = maxpoint.max(point);
}
this.cachedBoundingBox = [minpoint, maxpoint];
}
return this.cachedBoundingBox;
}
flipped()
{
let newvertices = this.vertices.map(v => v.flipped());
newvertices.reverse();
let newplane = this.plane.flipped();
return new Polygon(newvertices, this.shared, newplane);
}
// Affine transformation of polygon. Returns a new Polygon
transform(matrix4x4)
{
let newvertices = this.vertices.map(v => v.transform(matrix4x4));
let newplane = this.plane.transform(matrix4x4);
if (matrix4x4.isMirroring())
{
// need to reverse the vertex order
// in order to preserve the inside/outside orientation:
newvertices.reverse();
}
return new Polygon(newvertices, this.shared, newplane);
}
toString()
{
let result = "Polygon plane: " + this.plane.toString() + "\n";
for (let v of this.vertices) result += " " + v.toString() + "\n";
return result;
}
// project the 3D polygon onto a plane
projectToOrthoNormalBasis(orthobasis)
{
let points2d = this.vertices.map(vertex => orthobasis.to2D(vertex.pos));
let result = fromPointsNoCheck(points2d);
let area = result.area;
if (Math.abs(area) < areaEPS)
{
// the polygon was perpendicular to the orthnormal plane. The resulting 2D polygon would be degenerate
// return an empty area instead:
result = new CAG();
}
else if (area < 0)
{
result = result.flipped();
}
return result;
}
// ALIAS ONLY!!
solidFromSlices(options)
{
return solidFromSlices(this, options);
}
static createFromPoints(points: Vector3D[], shared?: Shared, plane?: Plane): Polygon
{
let vertices = points.map(p => new Vertex3D(p));
if (arguments.length < 3)
return new Polygon(vertices, shared);
else
return new Polygon(vertices, shared, plane);
}
// create from an untyped object with identical property names:
static fromObject(obj)
{
let vertices = obj.vertices.map(v =>
{
return Vertex3D.fromObject(v);
});
let shared = Shared.fromObject(obj.shared);
let plane = Plane.fromObject(obj.plane);
return new Polygon(vertices, shared, plane);
}
static verticesConvex(vertices: Vertex3D[], planenormal: Vector3D)
{
let count = vertices.length;
if (count < 3) return false;
let prevPrevPos = vertices[count - 2].pos;
let prevPos = vertices[count - 1].pos;
for (let i = 0; i < count; i++)
{
let pos = vertices[i].pos;
if (!Polygon.isConvexPoint(prevPrevPos, prevPos, pos, planenormal))
return false;
prevPrevPos = prevPos;
prevPos = pos;
}
return true;
}
// 计算3点是否凸角
static isConvexPoint(prevpoint: Vector3D, point: Vector3D, nextpoint: Vector3D, normal: Vector3D)
{
let crossproduct = point.minus(prevpoint).cross(nextpoint.minus(point));
let crossdotnormal = crossproduct.dot(normal);
return crossdotnormal >= 0;
}
}
/** Class Polygon.Shared
* Holds the shared properties for each polygon (Currently only color).
* @constructor
* @param {Array[]} color - array containing RGBA values, or null
*
* @example
* let shared = new CSG.Polygon.Shared([0, 0, 0, 1])
*/
export class Shared
{
tag: number;
constructor(public color: number[])
{
if (color && color.length !== 4)
{
throw new Error("Expecting 4 element array");
}
}
getTag()
{
let result = this.tag;
if (!result)
{
result = getTag();
this.tag = result;
}
return result;
}
// get a string uniquely identifying this object
getHash()
{
if (!this.color) return "null";
return this.color.join("/");
}
/** Create Polygon.Shared from color values.
* @param {number} r - value of RED component
* @param {number} g - value of GREEN component
* @param {number} b - value of BLUE component
* @param {number} [a] - value of ALPHA component
* @param {Array[]} [color] - OR array containing RGB values (optional Alpha)
*
* @example
* let s1 = Polygon.Shared.fromColor(0,0,0)
* let s2 = Polygon.Shared.fromColor([0,0,0,1])
*/
static fromColor(args)
{
let color;
if (arguments.length === 1)
{
color = arguments[0].slice(); // make deep copy
}
else
{
color = [];
for (let i = 0; i < arguments.length; i++)
{
color.push(arguments[i]);
}
}
if (color.length === 3)
{
color.push(1);
}
else if (color.length !== 4)
{
throw new Error(
"setColor expects either an array with 3 or 4 elements, or 3 or 4 parameters."
);
}
return new Shared(color);
}
static fromObject(obj)
{
return new Shared(obj.color);
}
}
export const defaultShared = new Shared(null);
|
00ec61af39cf66e319ff33473e1b724cb9c0d1c1
|
TypeScript
|
weichx/hex-editor-ui
|
/src/math/matrix4x4.ts
| 3.046875
| 3
|
import {MathUtil} from "./math_util";
import {Quaternion} from "./quaternion";
import {Vector3} from "./vector3";
export const enum MatrixIndex {
RotScale00,
RotScale01,
RotScale02,
RotScale10,
RotScale11,
RotScale12,
RotScale20,
RotScale21,
RotScale22,
PositionX,
PositionY,
PositionZ
}
export class Matrix {
public readonly m : Float32Array;
constructor() {
this.m = new Float32Array(16);
this.m[0] = 1.0;
this.m[5] = 1.0;
this.m[10] = 1.0;
this.m[15] = 1.0;
}
public isIdentity() : boolean {
if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
return false;
return !(this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0);
}
/**
* Returns the matrix determinant (float).
*/
public determinant() : number {
var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
(this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
(this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
}
public invert() : Matrix {
return this.invertNew(this);
}
public add(other : Matrix) : Matrix {
return this.addNew(other, this);
}
public addNew(other : Matrix, result : Matrix = null) : Matrix {
if(result === null) {
result = new Matrix();
}
for (var index = 0; index < 16; index++) {
result.m[index] = this.m[index] + other.m[index];
}
return result;
}
public invertNew(out? : Matrix) : Matrix {
out = out || new Matrix();
var l1 = this.m[0];
var l2 = this.m[1];
var l3 = this.m[2];
var l4 = this.m[3];
var l5 = this.m[4];
var l6 = this.m[5];
var l7 = this.m[6];
var l8 = this.m[7];
var l9 = this.m[8];
var l10 = this.m[9];
var l11 = this.m[10];
var l12 = this.m[11];
var l13 = this.m[12];
var l14 = this.m[13];
var l15 = this.m[14];
var l16 = this.m[15];
var l17 = (l11 * l16) - (l12 * l15);
var l18 = (l10 * l16) - (l12 * l14);
var l19 = (l10 * l15) - (l11 * l14);
var l20 = (l9 * l16) - (l12 * l13);
var l21 = (l9 * l15) - (l11 * l13);
var l22 = (l9 * l14) - (l10 * l13);
var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
var l28 = (l7 * l16) - (l8 * l15);
var l29 = (l6 * l16) - (l8 * l14);
var l30 = (l6 * l15) - (l7 * l14);
var l31 = (l5 * l16) - (l8 * l13);
var l32 = (l5 * l15) - (l7 * l13);
var l33 = (l5 * l14) - (l6 * l13);
var l34 = (l7 * l12) - (l8 * l11);
var l35 = (l6 * l12) - (l8 * l10);
var l36 = (l6 * l11) - (l7 * l10);
var l37 = (l5 * l12) - (l8 * l9);
var l38 = (l5 * l11) - (l7 * l9);
var l39 = (l5 * l10) - (l6 * l9);
out.m[0] = l23 * l27;
out.m[4] = l24 * l27;
out.m[8] = l25 * l27;
out.m[12] = l26 * l27;
out.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
out.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
out.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
out.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
out.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
out.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
out.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
out.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
out.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
out.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
out.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
out.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
return out;
}
public setTranslationValues(x : number, y : number, z : number) : Matrix {
this.m[12] = x;
this.m[13] = y;
this.m[14] = z;
return this;
}
public setTranslation(vector3 : Vector3) : Matrix {
this.m[12] = vector3.x;
this.m[13] = vector3.y;
this.m[14] = vector3.z;
return this;
}
public getTranslation(result? : Vector3) : Vector3 {
return (result || new Vector3()).set(this.m[12], this.m[13], this.m[14]);
}
/**
* Remove rotation and scaling part from the Matrix.
* Returns the updated Matrix.
*/
public removeRotationAndScaling() : Matrix {
this.setRowFromFloats(0, 1, 0, 0, 0);
this.setRowFromFloats(1, 0, 1, 0, 0);
this.setRowFromFloats(2, 0, 0, 1, 0);
return this;
}
public multiply(other : Matrix) : Matrix {
return Matrix.Multiply(this, other, this);
}
public copy(other : Matrix) : Matrix {
for (var index = 0; index < 16; index++) {
this.m[index] = other.m[index];
}
return this;
}
public static MakeIdentityInFloatBuffer(buffer : Float32Array, offset : integer) {
buffer[offset + 0] = 1;
buffer[offset + 1] = 0;
buffer[offset + 2] = 0;
buffer[offset + 3] = 0;
buffer[offset + 4] = 0;
buffer[offset + 5] = 1;
buffer[offset + 6] = 0;
buffer[offset + 7] = 0;
buffer[offset + 8] = 0;
buffer[offset + 9] = 0;
buffer[offset + 10] = 1;
buffer[offset + 11] = 0;
buffer[offset + 12] = 0;
buffer[offset + 13] = 0;
buffer[offset + 14] = 0;
buffer[offset + 15] = 1;
}
public static FloatArrayMultiply(
source : Float32Array, srcOffset : integer,
target : Float32Array, targetOffset : integer,
dest : Float32Array, destOffset : integer) {
const m = source;
const om = target;
var tm0 = m[srcOffset + 0];
var tm1 = m[srcOffset + 1];
var tm2 = m[srcOffset + 2];
var tm3 = m[srcOffset + 3];
var tm4 = m[srcOffset + 4];
var tm5 = m[srcOffset + 5];
var tm6 = m[srcOffset + 6];
var tm7 = m[srcOffset + 7];
var tm8 = m[srcOffset + 8];
var tm9 = m[srcOffset + 9];
var tm10 = m[srcOffset + 10];
var tm11 = m[srcOffset + 11];
var tm12 = m[srcOffset + 12];
var tm13 = m[srcOffset + 13];
var tm14 = m[srcOffset + 14];
var tm15 = m[srcOffset + 15];
var om0 = om[targetOffset + 0];
var om1 = om[targetOffset + 1];
var om2 = om[targetOffset + 2];
var om3 = om[targetOffset + 3];
var om4 = om[targetOffset + 4];
var om5 = om[targetOffset + 5];
var om6 = om[targetOffset + 6];
var om7 = om[targetOffset + 7];
var om8 = om[targetOffset + 8];
var om9 = om[targetOffset + 9];
var om10 = om[targetOffset + 10];
var om11 = om[targetOffset + 11];
var om12 = om[targetOffset + 12];
var om13 = om[targetOffset + 13];
var om14 = om[targetOffset + 14];
var om15 = om[targetOffset + 15];
dest[destOffset + 0] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
dest[destOffset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
dest[destOffset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
dest[destOffset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
dest[destOffset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
dest[destOffset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
dest[destOffset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
dest[destOffset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
dest[destOffset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
dest[destOffset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
dest[destOffset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
dest[destOffset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
dest[destOffset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
dest[destOffset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
dest[destOffset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
dest[destOffset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
}
//todo -- bottom row never changes, no need to multiply (probably)
public multiplyNew(other : Matrix, result? : Matrix) : Matrix {
const m = this.m;
const om = other.m;
var tm0 = m[0];
var tm1 = m[1];
var tm2 = m[2];
var tm3 = m[3];
var tm4 = m[4];
var tm5 = m[5];
var tm6 = m[6];
var tm7 = m[7];
var tm8 = m[8];
var tm9 = m[9];
var tm10 = m[10];
var tm11 = m[11];
var tm12 = m[12];
var tm13 = m[13];
var tm14 = m[14];
var tm15 = m[15];
var om0 = om[0];
var om1 = om[1];
var om2 = om[2];
var om3 = om[3];
var om4 = om[4];
var om5 = om[5];
var om6 = om[6];
var om7 = om[7];
var om8 = om[8];
var om9 = om[9];
var om10 = om[10];
var om11 = om[11];
var om12 = om[12];
var om13 = om[13];
var om14 = om[14];
var om15 = om[15];
result = result || new Matrix();
const resultMatrix = result.m;
resultMatrix[0] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
resultMatrix[1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
resultMatrix[2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
resultMatrix[3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
resultMatrix[4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
resultMatrix[5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
resultMatrix[6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
resultMatrix[7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
resultMatrix[8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
resultMatrix[9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
resultMatrix[10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
resultMatrix[11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
resultMatrix[12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
resultMatrix[13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
resultMatrix[14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
resultMatrix[15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
return result;
}
/**
* Boolean : True is the current Matrix and the passed one values are strictly equal.
*/
public equals(value : Matrix) : boolean {
return value &&
(this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
}
public clone(out? : Matrix) : Matrix {
out = out || new Matrix();
return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3],
this.m[4], this.m[5], this.m[6], this.m[7],
this.m[8], this.m[9], this.m[10], this.m[11],
this.m[12], this.m[13], this.m[14], this.m[15], out);
}
public getHashCode() : number {
let hash = this.m[0] || 0;
for (let i = 1; i < 16; i++) {
hash = (hash * 397) ^ (this.m[i] || 0);
}
return hash;
}
/**
* Decomposes the current Matrix into :
* - a scale vector3 passed as a reference to highPriorityUpdate,
* - a rotation quaternion passed as a reference to highPriorityUpdate,
* - a translation vector3 passed as a reference to highPriorityUpdate.
* Returns the boolean `true`.
*/
public decompose(scale : Vector3, rotation : Quaternion, translation : Vector3) : boolean {
translation.x = this.m[12];
translation.y = this.m[13];
translation.z = this.m[14];
var xs = MathUtil.sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
var ys = MathUtil.sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
var zs = MathUtil.sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
rotation.x = 0;
rotation.y = 0;
rotation.z = 0;
rotation.w = 1;
return false;
}
Matrix.FromValues(
this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0,
this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0,
this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0,
0, 0, 0, 1, internalScratch0);
Quaternion.FromRotationMatrix(internalScratch0, rotation);
return true;
}
public getScaleVector(out? : Vector3) : Vector3 {
out = out || new Vector3();
var xs = MathUtil.sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
var ys = MathUtil.sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
var zs = MathUtil.sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
out.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
out.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
out.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
return out;
}
public getScaleX() : number {
var xs = MathUtil.sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
return xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
}
public getScaleY() : number {
var ys = MathUtil.sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
return ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
}
public getScaleZ() : number {
var zs = MathUtil.sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
return zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
}
/**
* Returns a new Matrix as the extracted rotation matrix from the current one.
*/
public getRotationMatrix(out? : Matrix) : Matrix {
const result = out instanceof Matrix ? out : Matrix.Identity();
var m = this.m;
var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
Matrix.FromValues(
m[0] / sx, m[1] / sx, m[2] / sx, 0,
m[4] / sy, m[5] / sy, m[6] / sy, 0,
m[8] / sz, m[9] / sz, m[10] / sz, 0,
0, 0, 0, 1, result);
return result;
}
public static FromArray(array : Array<number>, offset = 0, out : Matrix = null) : Matrix {
if(out === null) {
out = new Matrix();
}
const m = out.m;
m[0] = array[offset + 0];
m[1] = array[offset + 1];
m[2] = array[offset + 2];
m[3] = array[offset + 3];
m[4] = array[offset + 4];
m[5] = array[offset + 5];
m[6] = array[offset + 6];
m[7] = array[offset + 7];
m[8] = array[offset + 8];
m[9] = array[offset + 9];
m[10] = array[offset + 10];
m[11] = array[offset + 11];
m[12] = array[offset + 12];
m[13] = array[offset + 13];
m[14] = array[offset + 14];
m[15] = array[offset + 15];
return out;
}
public static FromValues(initialM11 : number, initialM12 : number, initialM13 : number, initialM14 : number,
initialM21 : number, initialM22 : number, initialM23 : number, initialM24 : number,
initialM31 : number, initialM32 : number, initialM33 : number, initialM34 : number,
initialM41 : number, initialM42 : number, initialM43 : number, initialM44 : number, result? : Matrix) : Matrix {
result = result || new Matrix();
result.m[0] = initialM11;
result.m[1] = initialM12;
result.m[2] = initialM13;
result.m[3] = initialM14;
result.m[4] = initialM21;
result.m[5] = initialM22;
result.m[6] = initialM23;
result.m[7] = initialM24;
result.m[8] = initialM31;
result.m[9] = initialM32;
result.m[10] = initialM33;
result.m[11] = initialM34;
result.m[12] = initialM41;
result.m[13] = initialM42;
result.m[14] = initialM43;
result.m[15] = initialM44;
return result;
}
/**
* Sets the index-th row of the current matrix with the passed 4 x float values.
* Returns the updated Matrix.
*/
public setRowFromFloats(index : number, x : number, y : number, z : number, w : number) : Matrix {
if (index < 0 || index > 3) {
return this;
}
const i = index * 4;
this.m[i + 0] = x;
this.m[i + 1] = y;
this.m[i + 2] = z;
this.m[i + 3] = w;
return this;
}
// public static FloatArrayCompose(buffer : Float32Array, offset : integer, dest : Float32Array, destOffset : integer) {
// dest[destOffset + 0] = buffer[offset + LocalTransformIndices.ScaleX];
// dest[destOffset + 1] = 0;
// dest[destOffset + 2] = 0;
// dest[destOffset + 3] = 0;
// dest[destOffset + 4] = 0;
// dest[destOffset + 5] = buffer[offset + LocalTransformIndices.ScaleY];
// dest[destOffset + 6] = 0;
// dest[destOffset + 7] = 0;
// dest[destOffset + 8] = 0;
// dest[destOffset + 9] = 0;
// dest[destOffset + 10] = buffer[offset + LocalTransformIndices.ScaleZ];
// dest[destOffset + 11] = 0;
// dest[destOffset + 12] = 0;
// dest[destOffset + 13] = 0;
// dest[destOffset + 14] = 0;
// dest[destOffset + 15] = 1;
// const rotation = Quaternion.scratch0;
// rotation.x = buffer[offset + LocalTransformIndices.RotationX];
// rotation.y = buffer[offset + LocalTransformIndices.RotationY];
// rotation.z = buffer[offset + LocalTransformIndices.RotationW];
// rotation.w = buffer[offset + LocalTransformIndices.RotationZ];
// // todo -- rotation needs to work!
// // rotation.toRotationMatrix(internalScratch1);
// // internalScratch0.multiplyNew(internalScratch1, out);
// dest[destOffset + 12] = buffer[offset + LocalTransformIndices.PositionX];
// dest[destOffset + 13] = buffer[offset + LocalTransformIndices.PositionY];
// dest[destOffset + 14] = buffer[offset + LocalTransformIndices.PositionZ];
// }
public static Compose(scale : Vector3, rotation : Quaternion, translation : Vector3, result? : Matrix) : Matrix {
result = result || new Matrix();
const m = result.m;
m[0] = scale.x;
m[1] = 0;
m[2] = 0;
m[3] = 0;
m[4] = 0;
m[5] = scale.y;
m[6] = 0;
m[7] = 0;
m[8] = 0;
m[9] = 0;
m[10] = scale.z;
m[11] = 0;
m[12] = 0;
m[13] = 0;
m[14] = 0;
m[15] = 1;
if(!rotation.isIdentity()) {
rotation.toRotationMatrix(internalScratch1);
internalScratch0.multiplyNew(internalScratch1, result);
}
m[12] = translation.x;
m[13] = translation.y;
m[14] = translation.z;
return result;
}
public static Identity(out? : Matrix) : Matrix {
out = out || new Matrix();
return Matrix.FromValues(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0, out);
}
/**
* Returns a new zero Matrix.
*/
public static Zero() : Matrix {
return Matrix.FromValues(0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 0.0);
}
/**
* Returns a new rotation matrix for "angle" radians around the X axis.
*/
public static RotationX(angle : number) : Matrix {
var result = new Matrix();
Matrix.RotationXToRef(angle, result);
return result;
}
public static Multiply(mat0 : Matrix, mat1 : Matrix, result? : Matrix) : Matrix {
return mat0.multiplyNew(mat1, result || new Matrix());
}
/**
* Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
*/
public static RotationXToRef(angle : number, result : Matrix) : void {
var s = Math.sin(angle);
var c = Math.cos(angle);
result.m[0] = 1.0;
result.m[15] = 1.0;
result.m[5] = c;
result.m[10] = c;
result.m[9] = -s;
result.m[6] = s;
result.m[1] = 0.0;
result.m[2] = 0.0;
result.m[3] = 0.0;
result.m[4] = 0.0;
result.m[7] = 0.0;
result.m[8] = 0.0;
result.m[11] = 0.0;
result.m[12] = 0.0;
result.m[13] = 0.0;
result.m[14] = 0.0;
}
/**
* Returns a new rotation matrix for "angle" radians around the Y axis.
*/
public static RotationY(angle : number) : Matrix {
var result = new Matrix();
Matrix.RotationYToRef(angle, result);
return result;
}
/**
* Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
*/
public static RotationYToRef(angle : number, result : Matrix) : void {
var s = Math.sin(angle);
var c = Math.cos(angle);
result.m[5] = 1.0;
result.m[15] = 1.0;
result.m[0] = c;
result.m[2] = -s;
result.m[8] = s;
result.m[10] = c;
result.m[1] = 0.0;
result.m[3] = 0.0;
result.m[4] = 0.0;
result.m[6] = 0.0;
result.m[7] = 0.0;
result.m[9] = 0.0;
result.m[11] = 0.0;
result.m[12] = 0.0;
result.m[13] = 0.0;
result.m[14] = 0.0;
}
/**
* Returns a new rotation matrix for "angle" radians around the Z axis.
*/
public static RotationZ(angle : number) : Matrix {
var result = new Matrix();
Matrix.RotationZToRef(angle, result);
return result;
}
/**
* Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
*/
public static RotationZToRef(angle : number, result : Matrix) : void {
var s = Math.sin(angle);
var c = Math.cos(angle);
result.m[10] = 1.0;
result.m[15] = 1.0;
result.m[0] = c;
result.m[1] = s;
result.m[4] = -s;
result.m[5] = c;
result.m[2] = 0.0;
result.m[3] = 0.0;
result.m[6] = 0.0;
result.m[7] = 0.0;
result.m[8] = 0.0;
result.m[9] = 0.0;
result.m[11] = 0.0;
result.m[12] = 0.0;
result.m[13] = 0.0;
result.m[14] = 0.0;
}
/**
* Returns a new rotation matrix for "angle" radians around the passed axis.
*/
public static RotationAxis(axis : Vector3, angle : number) : Matrix {
var result = Matrix.Zero();
Matrix.RotationAxisToRef(axis, angle, result);
return result;
}
/**
* Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
*/
public static RotationAxisToRef(axis : Vector3, angle : number, result : Matrix) : void {
var s = Math.sin(-angle);
var c = Math.cos(-angle);
var c1 = 1 - c;
axis.normalize();
result.m[0] = (axis.x * axis.x) * c1 + c;
result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
result.m[3] = 0.0;
result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
result.m[5] = (axis.y * axis.y) * c1 + c;
result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
result.m[7] = 0.0;
result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
result.m[10] = (axis.z * axis.z) * c1 + c;
result.m[11] = 0.0;
result.m[15] = 1.0;
}
/**
* Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
*/
public static RotationYawPitchRoll(yaw : number, pitch : number, roll : number, out? : Matrix) : Matrix {
out = out || new Matrix();
const q = Quaternion.scratch0;
Quaternion.RotationYawPitchRoll(yaw, pitch, roll, q);
return q.toRotationMatrix(out);
}
public static CreateScale(x : number, y : number, z : number, result? : Matrix) : Matrix {
result = result || new Matrix();
result.m[0] = x;
result.m[1] = 0.0;
result.m[2] = 0.0;
result.m[3] = 0.0;
result.m[4] = 0.0;
result.m[5] = y;
result.m[6] = 0.0;
result.m[7] = 0.0;
result.m[8] = 0.0;
result.m[9] = 0.0;
result.m[10] = z;
result.m[11] = 0.0;
result.m[12] = 0.0;
result.m[13] = 0.0;
result.m[14] = 0.0;
result.m[15] = 1.0;
return result;
}
public static CreateTranslation(x : number, y : number, z : number, out? : Matrix) : Matrix {
return Matrix.FromValues(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
x, y, z, 1.0, out || new Matrix());
}
public static CreateTRS() {
}
/**
* Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
*/
public static Lerp(startValue : Matrix, endValue : Matrix, gradient : number) : Matrix {
var result = Matrix.Zero();
for (var index = 0; index < 16; index++) {
result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
}
return result;
}
/**
* Returns a new Matrix whose values are computed by :
* - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
* - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
* - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
*/
public static DecomposeLerp(startValue : Matrix, endValue : Matrix, gradient : number) : Matrix {
var startScale = new Vector3(0, 0, 0);
var startRotation = new Quaternion();
var startTranslation = new Vector3(0, 0, 0);
startValue.decompose(startScale, startRotation, startTranslation);
var endScale = new Vector3(0, 0, 0);
var endRotation = new Quaternion();
var endTranslation = new Vector3(0, 0, 0);
endValue.decompose(endScale, endRotation, endTranslation);
var resultScale = Vector3.Lerp(startScale, endScale, gradient);
var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
return Matrix.Compose(resultScale, resultRotation, resultTranslation);
}
public static GetAsMatrix2x2(matrix : Matrix) : Float32Array {
return new Float32Array([
matrix.m[0], matrix.m[1],
matrix.m[4], matrix.m[5]
]);
}
public static GetAsMatrix3x3(matrix : Matrix) : Float32Array {
return new Float32Array([
matrix.m[0], matrix.m[1], matrix.m[2],
matrix.m[4], matrix.m[5], matrix.m[6],
matrix.m[8], matrix.m[9], matrix.m[10]
]);
}
/**
* Compute the transpose of the passed Matrix.
* Returns a new Matrix.
*/
public static Transpose(matrix : Matrix) : Matrix {
var result = new Matrix();
result.m[0] = matrix.m[0];
result.m[1] = matrix.m[4];
result.m[2] = matrix.m[8];
result.m[3] = matrix.m[12];
result.m[4] = matrix.m[1];
result.m[5] = matrix.m[5];
result.m[6] = matrix.m[9];
result.m[7] = matrix.m[13];
result.m[8] = matrix.m[2];
result.m[9] = matrix.m[6];
result.m[10] = matrix.m[10];
result.m[11] = matrix.m[14];
result.m[12] = matrix.m[3];
result.m[13] = matrix.m[7];
result.m[14] = matrix.m[11];
result.m[15] = matrix.m[15];
return result;
}
/**
* Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
*/
public static FromXYZAxesToRef(xaxis : Vector3, yaxis : Vector3, zaxis : Vector3, mat : Matrix) {
mat.m[0] = xaxis.x;
mat.m[1] = xaxis.y;
mat.m[2] = xaxis.z;
mat.m[3] = 0.0;
mat.m[4] = yaxis.x;
mat.m[5] = yaxis.y;
mat.m[6] = yaxis.z;
mat.m[7] = 0.0;
mat.m[8] = zaxis.x;
mat.m[9] = zaxis.y;
mat.m[10] = zaxis.z;
mat.m[11] = 0.0;
mat.m[12] = 0.0;
mat.m[13] = 0.0;
mat.m[14] = 0.0;
mat.m[15] = 1.0;
}
/**
* Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
*/
public static FromQuaternionToRef(quat : Quaternion, result : Matrix) {
var xx = quat.x * quat.x;
var yy = quat.y * quat.y;
var zz = quat.z * quat.z;
var xy = quat.x * quat.y;
var zw = quat.z * quat.w;
var zx = quat.z * quat.x;
var yw = quat.y * quat.w;
var yz = quat.y * quat.z;
var xw = quat.x * quat.w;
result.m[0] = 1.0 - (2.0 * (yy + zz));
result.m[1] = 2.0 * (xy + zw);
result.m[2] = 2.0 * (zx - yw);
result.m[3] = 0.0;
result.m[4] = 2.0 * (xy - zw);
result.m[5] = 1.0 - (2.0 * (zz + xx));
result.m[6] = 2.0 * (yz + xw);
result.m[7] = 0.0;
result.m[8] = 2.0 * (zx + yw);
result.m[9] = 2.0 * (yz - xw);
result.m[10] = 1.0 - (2.0 * (yy + xx));
result.m[11] = 0.0;
result.m[12] = 0.0;
result.m[13] = 0.0;
result.m[14] = 0.0;
result.m[15] = 1.0;
}
public static scratch0 = new Matrix();
public static scratch1 = new Matrix();
public static scratch2 = new Matrix();
public static scratch3 = new Matrix();
public static scratch4 = new Matrix();
public static scratch5 = new Matrix();
}
const internalScratch0 = new Matrix();
const internalScratch1 = new Matrix();
|
2a2d3ae4611d4756b80703c5399117c65764f3be
|
TypeScript
|
matthewjosephtaylor/say-my-name
|
/src/js/project/ProjectGlobals.ts
| 2.640625
| 3
|
export type ProjectPackage = {
name: string;
version: string;
description: string;
};
/**
* @see webpack.config.js
*/
declare const PROJECT_PACKAGE: ProjectPackage;
export function getProjectPackage(): ProjectPackage {
return PROJECT_PACKAGE;
}
export function getProjectVersion(): string {
return getProjectPackage().version;
}
/**
* @see webpack.config.js
*/
declare const BUILD_TIME_MILLIS: string;
export function getBuildTimeMills(): number {
return Number(BUILD_TIME_MILLIS);
}
export function getBuildTimeIso(): string {
const date = new Date(getBuildTimeMills());
return date.toISOString();
}
|
7de0855bddbf6f83719e1e6f3504c033138672b6
|
TypeScript
|
joshdcuneo/tsm
|
/src/utility.ts
| 2.875
| 3
|
import { ObjectProto } from './types';
export const isType = <T>(type: ObjectProto, object: any): object is T =>
type.isPrototypeOf(object);
export const isTypeP = <T>(type: ObjectProto) => (object: any): object is T =>
isType(type, object);
export const immutable = <T>(proto: ObjectProto, object: T): T =>
Object.freeze(Object.assign(Object.create(proto), object));
|
31ec35a5de740f1d3864daf81acbd619cd7ed843
|
TypeScript
|
ttionya/eslint-config
|
/tests/typescript/common/explicit-function-return-type/good.ts
| 2.953125
| 3
|
/* eslint-disable @typescript-eslint/no-unused-vars */
export default 1
function test(): void {
// do something
}
interface IObjectType {
foo(): number
}
const objectProp: IObjectType = {
foo: () => 1,
}
const arrowFn = () => (): void => { /* do something */ }
|
993df05ca46ebac5c71bf731663d624bc1cc5203
|
TypeScript
|
maurer2/poescho-radio
|
/frontend/src/form-component/form-component.ts
| 2.578125
| 3
|
/* eslint-disable class-methods-use-this */
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
/* eslint-disable no-underscore-dangle */
/* eslint-disable import/prefer-default-export */
import {
LitElement, html, customElement, property,
} from 'lit-element';
import { FormComponentStyles } from './form-component.styles';
@customElement('form-component')
export class FormComponent extends LitElement {
static get styles() {
return [
FormComponentStyles,
];
}
@property({ type: String })
serialNumber = '';
@property({ type: Number })
calculatedNumber = 1234;
private handleSubmit(event: Event) {
event.preventDefault();
console.log('handle submit', event);
}
private handleReset(event: Event) {
event.preventDefault();
this.serialNumber = '';
console.log('handle reset', event);
}
private handleInput(event: InputEvent) {
if (!event.currentTarget) {
return;
}
const newInputValue = (event.currentTarget as HTMLInputElement).value;
this.serialNumber = newInputValue;
}
render() {
return html`
<form
class="form"
action=""
method="post"
@submit=${(event: Event) => this.handleSubmit(event)}
@reset=${(event: Event) => this.handleReset(event)}
>
<div>
<label for="serialNumber">Serial number:</label>
<input
type="text"
id="serial-number"
name="serial-number"
placeholder="Serial number"
.value=${this.serialNumber}
@input=${(event: InputEvent) => this.handleInput(event)}
/>
</div>
<div class="buttons">
<button type="submit">Calculate code</button>
<button type="reset">Reset fields</button>
</div>
<dl class="results">
<dt class="key">Serial number:</dt>
<dd class="value">
<code>
${this.serialNumber ? this.serialNumber : '-----'}
</code>
</dd>
<dt class="key">Calculated number:</dt>
<dd class="value"><code>${this.calculatedNumber}</code></dd>
</dl>
</form>
`;
}
}
declare global {
interface HTMLElementTagNameMap {
'form-component': FormComponent;
}
}
|
cdad72f562d58ac1efdafa16c0ef27edae3f9ac2
|
TypeScript
|
ChikaEche/coding-problems
|
/subarray-sort.ts
| 3.46875
| 3
|
function subarraySort(array) {
let indx = []
let highest = -1
let smallest = -1
for (let i = array.length - 1; i > 0; i--) {
if(array[i] < array[i-1]) {
highest = highestIndex(array, i-1, array[i-1]);
smallest = smallestIndex(array, i, array[i])
break;
}
}
indx.push(smallest, highest)
return indx
}
function smallestIndex(array, smallest, value) {
for (let i = smallest; i >= 0; i--) {
console.log(array[i], array[i-1], i)
if(array[i] > value ) {
let temp = array[i]
array[i] = array[smallest]
array[smallest] = temp
smallest = i
}
else {
value = array[i]
}
}
return smallest;
}
function highestIndex(array, highest, value) {
let highidx = highest
for (let i = highest+1; i < array.length; i++) {
if(array[i] > value) {
highest = i-1
break;
}
}
return highest === highidx ? array.length - 1 : highest;
}
|
a4a771506fd1758b876c3c2877eab7277215c675
|
TypeScript
|
vkbhati1991/ts-decoraters
|
/src/controllers/LoginController.ts
| 2.875
| 3
|
import { NextFunction, Request, Response } from "express";
import { get, controller, use, bodyValidator, post } from "./decorators";
function logger(req: Request, res: Response, next: NextFunction) {
console.log('middle call');
next();
}
@controller('/auth')
export class LoginController {
@get('/loginss')
add(a: number): number {
return a + 3;
}
@get('/login')
@use(logger)
getLogin(req: Request, res: Response): void {
res.send(
`
<form method="POST">
<input type="text" name="email" />
<button>Submit</button>
</form>
`
);
}
@post('/login')
@bodyValidator('email')
postLogin(req: Request, res: Response): void {
const { email } = req.body;
if (email && email === 'vinod@gmail.com') {
res.redirect('/auth/login');
} else {
res.send('Invalid UserName ')
}
}
}
|
3913c4d67405d58fbea592d83f273908a126932d
|
TypeScript
|
ester5775/GymnasticsStudio
|
/GymnasticsStudioClient/src/app/classes/lesson.ts
| 2.640625
| 3
|
export class Lesson {
public Id:number;
public Name:string;
public TeacherId:number;
public Day:string;
public StartHower:string;
public FinishHower:string;
public MaxStudensNum:number;
public MaxSerologersStudensNum:number;
public LessonKind:number;
constructor(init?: Partial<Lesson>) {
Object.assign(this, init);
}
}
|
38b25833b597496e27fb7238bd5a65240b9a92b4
|
TypeScript
|
santigarcor/vscode-phpunit-extended
|
/src/Helper.ts
| 2.953125
| 3
|
export class Helper {
private readonly regex = {
method: /\s*(public\s+){0,1}function\s+(\w+)\s*\(/gi,
class: /class\s+(\w*)\s*{?/gi
};
public getRegex() {
return this.regex;
}
public getClassNameOrMethod(editor, type: string): string | undefined {
if (!this.regex.hasOwnProperty(type)) {
throw new Error('Invalid type property passed: ' + type);
}
let result = undefined;
let position = 0;
let modifier = 1;
if (type === 'method') {
position = editor.selection.active.line;
modifier = -1;
}
while (result === undefined && position > -1) {
let line = editor.document.lineAt(position);
let regexResult = null;
if ((regexResult = this.regex[type].exec(line.text))) {
result = regexResult[type === 'method' ? 2 : 1].toString().trim();
}
position += modifier;
}
return result;
}
}
|
c51504567e5b06462eccafac25997612e4ba874d
|
TypeScript
|
ivolimasilva/react-vite
|
/src/use-fetch.ts
| 2.75
| 3
|
import { useState, useEffect } from "react";
const getUrl = (year: string) => `https://ergast.com/api/f1/${year}/driverStandings.json`;
interface Driver {
driverId: string;
permanentNumber: string;
code: string;
url: string;
givenName: string;
familyName: string;
dateOfBirth: string;
nationality: string;
}
interface Standings {
Driver: Driver;
points: string;
}
const useFetch = (year: string) => {
const [loading, setLoading] = useState(false);
const [data, setData] = useState<Standings[]>();
const [error, setError] = useState(null);
useEffect(() => {
async function go() {
try {
setLoading(true);
const url = getUrl(year);
const response = await fetch(url);
const raw = await response.json();
setData(raw['MRData']['StandingsTable']['StandingsLists'][0]['DriverStandings']);
} catch (error) {
setError(error);
} finally {
setLoading(false);
}
}
go();
}, [year]);
return { loading, data, error };
};
export default useFetch;
|
5f6d82c0cbdbf939ec5396d63b520b853c2c2e4e
|
TypeScript
|
unlock-protocol/unlock
|
/locksmith/src/controllers/v2/receiptController.ts
| 2.5625
| 3
|
import { Request, Response } from 'express'
import { Receipt } from '../../models/receipt'
import * as z from 'zod'
import Normalizer from '../../utils/normalizer'
import logger from '../../logger'
import * as receiptOperations from '../../../src/operations/receiptOperations'
export const PurchaserBody = z.object({
fullname: z.string().optional().default(''),
businessName: z.string().optional().default(''),
addressLine1: z.string().optional().default(''),
addressLine2: z.string().optional().default(''),
city: z.string().optional().default(''),
state: z.string().optional().default(''),
zip: z.string().optional().default(''),
country: z.string().optional().default(''),
})
export type PurchaserBodyProps = z.infer<typeof PurchaserBody>
export class ReceiptController {
// Get Receipts details by providing `network` / `lockAddress` / `hash`
async getReceipt(request: Request, response: Response) {
const network = Number(request.params.network || 1)
const lockAddress = Normalizer.ethereumAddress(request.params.lockAddress)
const hash = request.params.hash
try {
const receiptDetails = await receiptOperations.getReceiptDetails({
lockAddress,
network,
hash,
})
// Returns receipts details
return response.status(200).json(receiptDetails)
} catch (err: any) {
logger.error(err.message)
return response.status(500).send({
message: 'Impossible to retrieve receipt details.',
})
}
}
// Save Purchaser details for Receipts
async savePurchaser(request: Request, response: Response) {
const network = Number(request.params.network || 1)
const lockAddress = Normalizer.ethereumAddress(request.params.lockAddress)
const hash = request.params.hash ?? ''
const props = await PurchaserBody.parseAsync(request.body)
try {
const [{ dataValues }] = await Receipt.upsert(
{
lockAddress,
network,
hash,
...props,
},
{
conflictFields: ['hash'],
returning: true,
}
)
return response.status(200).json({
...dataValues,
})
} catch (err: any) {
logger.error(err.message)
return response.status(500).json({
message: 'Failed to save purchaser details.',
})
}
}
}
|
ed9cf4ebb9479fa115c1c59021bfa7536c956e65
|
TypeScript
|
zyp94021/laya2.0-cli
|
/src/core/game/script/HLabel.ts
| 2.8125
| 3
|
/**
* 多语言Label
*/
export default class HLabel extends Laya.Script {
constructor() {
super()
}
/** @prop {name:LanguageID,type:string}*/
public LanguageID: string
/** @prop {name:IsFit,type:Bool}*/
public IsFit: boolean = true
/** @prop {name:IsFill,tips:"1,0",type:Bool}*/
public IsFill: boolean = false
private _langLabel: Laya.Label
onAwake() {
this._langLabel = this.owner as Laya.Label
this.lang()
}
private lang() {
if (this.LanguageID) {
this._langLabel.text = this.LanguageID
}
this.fit()
}
public fit() {
if (!this.IsFit) return
if (!this._langLabel.wordWrap) {
if (this.IsFill) {
if (this._langLabel['_tf'].textWidth > this._langLabel.width) this.fitShortWidth()
else this.fitLongWidth()
} else this.fitShortWidth()
} else {
if (this.IsFill) {
if (this._langLabel['_tf'].textHeight > this._langLabel.height) this.fitShortHeight()
else this.fitLongHeight()
} else this.fitShortHeight()
}
}
private fitShortWidth() {
var flag = this._langLabel['_tf'].textWidth > this._langLabel.width
var fSize = this._langLabel.fontSize
while (flag) {
fSize = fSize - 1
Laya.Browser.context.font = fSize + 'px Arial'
var browserText = Laya.Browser.context.measureText(this._langLabel.text)
flag = browserText.width > this._langLabel.width && fSize > 12
}
this._langLabel.fontSize = fSize
}
private fitLongWidth() {
var flag = this._langLabel['_tf'].textWidth < this._langLabel.width
var fSize = this._langLabel.fontSize
while (flag) {
fSize = fSize + 1
Laya.Browser.context.font = fSize + 'px Arial'
var browserText = Laya.Browser.context.measureText(this._langLabel.text)
flag = browserText.width < this._langLabel.width
}
this._langLabel.fontSize = fSize
}
private fitShortHeight() {
var flag = this._langLabel['_tf'].textHeight > this._langLabel.height
var fSize = this._langLabel.fontSize
while (flag) {
fSize = fSize - 1
Laya.Browser.context.font = fSize + 'px Arial'
this._langLabel.fontSize = fSize
flag = this._langLabel['_tf'].textHeight > this._langLabel.height && fSize > 12
}
}
private fitLongHeight() {
var flag = this._langLabel['_tf'].textHeight < this._langLabel.height
var fSize = this._langLabel.fontSize
while (flag) {
fSize = fSize + 1
Laya.Browser.context.font = fSize + 'px Arial'
this._langLabel.fontSize = fSize
flag = this._langLabel['_tf'].textHeight < this._langLabel.height
}
this._langLabel.fontSize = fSize - 1
}
}
|
2b9ce115e41ecc837237d1da89a5e8d80123e572
|
TypeScript
|
PrimeEuler/PWA
|
/public/certificates-viewer/dist/types/utils/download_from_buffer.d.ts
| 2.515625
| 3
|
/**
* @license
* Copyright (c) Peculiar Ventures, LLC.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* Download from buffer
*
* @example
* ```js
* import { downloadFromBuffer } from 'ui-utils';
*
* downloadFromBuffer(arrayBufferValue, 'applciation/pdf', 'myFile', 'pdf');
* ```
*/
export default function downloadFromBuffer(value: ArrayBuffer, mime: string, name: string, extension: string): Promise<unknown>;
|
ff1e6112f585f8fbb78c7be7fa6d1c183a8ff7eb
|
TypeScript
|
jeremydeal/savvy-stream
|
/savvy-stream-api/src/apis/airQualityApi.ts
| 2.75
| 3
|
import fetch from 'node-fetch'
const key = "F4F31AC2-102C-48C7-B777-CEB8CA208E83"
// see: https://docs.airnowapi.org/ForecastsByZip/query
// API username: jeremy.n.deal
const getUrl = (zip: string, date: string) =>
`http://www.airnowapi.org/aq/forecast/zipCode/?format=application/json&zipCode=${zip}&date=${date}&distance=25&API_KEY=${key}`
export const getAirQuality = async (zip: string, date: Date) => {
const url = getUrl(zip, formatDate(date))
return fetch(url)
.then(res => res.json())
.then(
(data: any) => {
// console.log(data);
const candidatesForToday = data.filter((x: any) => formatDate(new Date(x.DateForecast)) === formatDate(new Date(Date.now())));
if (candidatesForToday.length === 0) {
console.log("ERROR")
return
}
const today = candidatesForToday[0];
if (!today) return null;
return {
location: `${today.ReportingArea}, ${today.StateCode}`,
quality: today.Category.Name
};
}
)
.catch(ex => console.log(ex))
}
function formatDate(d: Date) {
return `${d.getFullYear()}-${d.getMonth()+1}-${d.getDate()}`;
}
|
e77564285c535daecc7231a4cdf65794ab84c0dd
|
TypeScript
|
Ssioo/ArThings
|
/src/utils/iot-configurator.ts
| 2.609375
| 3
|
export enum DeviceConnectionType {
BLE,
WIFI,
LTE,
UWB,
UNKNOWN
}
export interface MyIotDevice extends IotDevice {
}
export interface LatLng {
latitude: number
longitude: number
altitude?: number
}
export interface IotDevice {
address: string
networkType: DeviceConnectionType
name?: string
location?: LatLng
estimatedDistance: number
estimatedAzimuth: number
}
export class IotConfigurator {
myDevice: MyIotDevice | null = null
otherDevices: IotDevice[] = [] // 서비스에 알려진 다른 디바이스
constructor() {
}
init() {
}
syncOtherDevices() {
}
async discoverDevices() {
}
}
|
c86962b8a6a5325d83a8b07c29bdb7ecdef7b25e
|
TypeScript
|
esilva2902/stripe-course
|
/server/stripe-webhooks.route.ts
| 2.671875
| 3
|
import { Request, Response } from 'express';
import { db, getDocData } from './database';
// Remember, in order to initialize the Stripe node module, we must passed our STRIPE_SECRET_KEY:
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
/**
* ONE TIME PURCHASE / RECURRING CHARGE
*
* 5. Due to Stripe will send us the cancelation or confirmation as an Event types, we
* expose only one endpoint to Stripe ('/stripe-webhooks'). Inside the request
* handler we manage which type of event is sent.
*
* IMPORTANT: This endpoint is invoked only by Stripe. Every request must be
* validated. That is why every request is signed with a sepecial
* secret stored in STRIPE_WEBHOOK_SECRET.
*/
export async function stripeWebhooks(req: Request, res:Response) {
try {
/**
* Stripe sends us every request signed with the STRIPE_WEBHOOK_SECRET.
*
* The signature must be validated, then the signature is taken from
* the request headers.
*/
const signature = req.headers["stripe-signature"];
console.log(`stripeWebhooks was called with the following signature: ${signature}`);
/**
* Signature validation is done via the Stripe node module. The method
* stripe.webhooks.constructEvent will validate every request and returns
* the corresponding event info.
*/
const event = stripe.webhooks.constructEvent(
req.body, signature, process.env.STRIPE_WEBHOOK_SECRET);
/**
* checkout.session.completed event type means that the user payment has
* been successfully processed.
*/
if (event.type == "checkout.session.completed") {
// Stripe session is taken from the data of the sent event:
const session = event.data.object;
/**
* ONE TIME PURCHASE / RECURRING CHARGE
*
* 5.1. Since Stripe has marked the session as complete, we must do
* the same in our Firestore database.
*/
await onCheckoutSessionCompleted(session);
}
/**
* ONE TIME PURCHASE / RECURRING CHARGE
*
* 5.2. Once purchaseSession collection was updated, an event
* acknowledment is sent to Stripe.
*
* IMPORTANT: Stripe will invoke our successful URL only if Stripe
* has received the event acknowledgment from our backend
* server.
*
* 5.3. Stripe invoke our successful URL.
*/
res.json({received:true});
}
catch(err) {
console.log('Error processing webhook event, reason: ', err);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
}
// ONE TIME PURCHASE / RECURRING CHARGE
async function onCheckoutSessionCompleted(session) {
// Take the unique id of our purchaseSession collection document from the client_reference_id:
const purchaseSessionId = session.client_reference_id;
// Get the corresponding ids from purchaseSessions collection:
const {userId, courseId, pricingPlanId} =
await getDocData(`purchaseSessions/${purchaseSessionId}`);
/**
* IMPORTANT:
*
* It does not matter what resource the customer is buying, the customer id, assigned by Stripe,
* is taken in order to group all the payments done by the same user.
*
* The customer id assigned by Stripe is found in the session object in customer field.
*/
// The customer is buying a course:
if (courseId) {
await fulfillCoursePurchase(userId, courseId, purchaseSessionId, session.customer);
}
else if (pricingPlanId) {
// The customer is buying a subscription:
await fulfillSubscriptionPurchase(purchaseSessionId, userId,
session.customer, pricingPlanId);
}
}
async function fulfillSubscriptionPurchase(purchaseSessionId:string, userId:string,
stripeCustomerId:string, pricingPlanId:string) {
/**
* RECURRING CHARGE
*
* 5.1. To finish the purchase operation we must associate the user
* who bought the subscription with the pricingPlanId.
*
* REMEMBER: The pricingPlanId was created in the Stripe platform an it represents
* the Price of the subscription. The subscription was created in
* Stripe platform as well, and is the Product associated with the
* giving pricingPlanId.
*
* IMPORTANT: All the database operations are done via a Firestore batch. It
* means all of them run in a single atomic transaction.
*/
const batch = db.batch();
/**
* (a). The first operation to perform is marking our purchase session as 'completed':
*/
// Retrieve the reference for the given purchase session doc path:
const purchaseSessionRef = db.doc(`purchaseSessions/${purchaseSessionId}`);
// Then update the doc ref with the status of "completed":
batch.update(purchaseSessionRef, {status: "completed"});
/**
* (b). The second operation is granting access to all courses the user
* who is buying the subscription.
*
* NOTE: When a user buys only one course, the courseId is stored in coursesOwned
* collection which is beneath the users collection.
*
* coursesOwned collection is used exclusively to stored courses
* that was bougth separately. Therefore, when a subscription is bought
* the pricingPlanId will be stored in the users collection directly.
*/
// Get a doc ref to the corresponding user doc path:
const userRef = db.doc(`users/${userId}`);
// Then add/update the Stripe customer id and the pricingPlanId. If the users collection does not exist, then it will be created.
batch.set(userRef, {pricingPlanId, stripeCustomerId}, {merge: true} );
return batch.commit();
}
async function fulfillCoursePurchase(userId:string, courseId:string,
purchaseSessionId:string,
stripeCustomerId:string) {
/**
* ONE TIME PURCHASE
*
* 5.1. To finish the purchase operation we must associate the user
* who bought the course with the course itself.
*
* IMPORTANT: All the database operations are done via a Firestore batch. It
* means all of them run in a single atomic transaction.
*/
const batch = db.batch();
/**
* (a). The first operation to perform is marking our purchase session as 'completed':
*/
// Retrieve the reference for the given purchase session doc path:
const purchaseSessionRef = db.doc(`purchaseSessions/${purchaseSessionId}`);
// Then update the doc ref with the status of "completed":
batch.update(purchaseSessionRef, {status: "completed"});
/**
* (b). The second operation is creating the list of courses the user has access.
* This collection will be beneath the users collection.
*/
// Get a doc ref to the desired path:
const userCoursesOwnedRef = db.doc(`users/${userId}/coursesOwned/${courseId}`);
// Since we only want to store the course id, we create an empty doc:
batch.create(userCoursesOwnedRef, {});
/**
* (c). The last operation is taking the id assigned to the customer by Stripe.
* The Stripe customer id will be added to the users collection.
*/
// Get a doc ref to the users path:
const userRef = db.doc(`users/${userId}`);
// Then add/update the Stripe customer id. If the users collection does not exist, then it will be created.
batch.set(userRef, {stripeCustomerId}, {merge: true});
return batch.commit();
}
|
251ddb06a586b0c44b7bd372b9b3a85dcd69c324
|
TypeScript
|
dongryphon/siesta
|
/tests/siesta/test/spies.t.ts
| 3.0625
| 3
|
import { describe } from "../../../index.js"
import { Spy } from "../../../src/siesta/test/Spy.js"
describe('Spy executing strategies', t => {
let obj : { someProp : any, setSomeProp : (...args) => typeof obj }
let obj2 : { someProp : any, setSomeProp : (...args) => typeof obj2 }
t.beforeEach(t => {
obj = {
someProp : null,
setSomeProp : function (value) { this.someProp = value; return this }
}
})
t.it("Spy should track the calls to it", t => {
const spy = t.spyOn(obj, 'setSomeProp')
obj.setSomeProp()
obj.setSomeProp(0, 1, 1)
obj.setSomeProp(0, 1)
t.expect(obj.setSomeProp).toHaveBeenCalled()
t.expect(obj.setSomeProp).toHaveBeenCalledWith(0, 1, t.any(Number))
t.is(obj.someProp, 0, "`someProp` has change")
t.isInstanceOf(spy, Spy)
t.is(spy.calls.any(), true)
t.is(spy.calls.count(), 3)
t.equal(spy.calls.argsFor(2), [ 0, 1 ])
t.equal(spy.calls.allArgs(), [ [], [ 0, 1, 1 ], [ 0, 1 ] ])
t.equal(spy.calls.mostRecent(), { object : obj, args : [ 0, 1 ], returnValue : obj })
t.equal(spy.calls.first(), { object : obj, args : [], returnValue : obj })
spy.calls.reset()
t.is(spy.calls.any(), false)
t.is(spy.calls.count(), 0)
})
t.it("Spy should be able to call through and stub", t => {
const spy = t.spyOn(obj, 'setSomeProp').callThrough()
obj.setSomeProp(1)
t.expect(obj.setSomeProp).toHaveBeenCalled()
t.is(obj.someProp, 1, "`someProp` has changed")
spy.stub()
obj.setSomeProp(11)
t.is(obj.someProp, 1, "`someProp` hasn't changed")
})
t.it("Spy should be able to call fake", t => {
const spy = t.spyOn(obj, 'setSomeProp').callFake(function (this : typeof obj) { this.someProp = 11; return obj2 })
t.is(obj.setSomeProp(1), obj2, 'Return value from fake function')
t.expect(spy).toHaveBeenCalledWith(1)
t.is(obj.someProp, 11, "`someProp` has been changed by the fake function")
})
t.it("Spy should be able to throw", t => {
t.spyOn(obj, 'setSomeProp').throwError('wrong')
t.expect(() => obj.setSomeProp(1)).toThrow('wrong')
})
t.it("Spy should be able to return value", t => {
t.spyOn(obj, 'setSomeProp').returnValue(obj2)
t.is(obj.setSomeProp(1), obj2, "`someProp` has been changed by the fake function")
t.is(obj.someProp, null, "`someProp` hasn't change")
})
})
describe('Standalone spies', t => {
t.it("Should be able to create a spy", t => {
const spy = t.createSpy('007')
spy()
spy(0, 1)
spy(0, 1, '1')
t.expect(spy).toHaveBeenCalled()
t.expect(spy).toHaveBeenCalledWith(0, t.any(Number), t.any(String))
t.isInstanceOf(spy.spy, Spy)
t.is(spy.spy.calls.any(), true)
t.is(spy.spy.calls.count(), 3)
spy.spy.calls.reset()
t.is(spy.spy.calls.any(), false)
t.is(spy.spy.calls.count(), 0)
})
t.it("Should be able to create a spy object", t => {
const spyObj = t.createSpyObj([ 'shoot', 'seduce'])
// @ts-ignore
t.equal(spyObj, { shoot : t.any(Function), seduce : t.any(Function) })
spyObj.shoot('gun')
spyObj.seduce('Girl1')
spyObj.seduce('Girl2')
t.expect(spyObj.shoot).toHaveBeenCalledWith('gun')
t.expect(spyObj.seduce).toHaveBeenCalledWith('Girl1')
t.expect(spyObj.seduce).toHaveBeenCalledWith('Girl2')
})
})
describe('Spies removal after the spec', t => {
const obj = {
someProp : null,
setSomeProp : function (...args : unknown[]) { this.someProp = args[ 0 ]; return this }
}
t.it("Setting up the spy", t => {
const spy = t.spyOn(obj, 'setSomeProp').stub()
obj.setSomeProp()
obj.setSomeProp(0, 1, '1')
obj.setSomeProp(0, '1')
t.is(obj.someProp, null, "`someProp` has not change")
t.expect(spy).toHaveBeenCalled()
t.expect(spy).toHaveBeenCalledWith(0, t.any(Number), t.any(String))
})
t.it("Spy should be removed in this spec", t => {
obj.setSomeProp(0)
t.is(obj.someProp, 0, "`someProp` has change - spy has been removed")
})
})
|
64b68176608555252ed8ea604a8ba0a63a5fb195
|
TypeScript
|
howmanysmall/StyluaPlugin
|
/cli/index.ts
| 2.515625
| 3
|
export interface StyluaStudioArguments {
_: string[];
p: number;
port: number;
h: boolean;
help: boolean;
path: string;
files: string;
config: string;
}
import { Application, Router } from "https://deno.land/x/oak/mod.ts";
import FormatController from "./Controllers/FormatController.ts";
import { ensureDir } from "https://deno.land/std@0.92.0/fs/mod.ts";
import { SEP as Separator } from "https://deno.land/std@0.92.0/path/mod.ts";
import { parse } from "https://deno.land/std@0.92.0/flags/mod.ts";
import GetOrSetEnv from "./Utility/GetOrSetEnv.ts";
import { red, bold } from "https://deno.land/std@0.92.0/fmt/colors.ts";
import { OPTIONS_STRING } from "./Constants.ts";
function main(args: string[]) {
const home = Deno.env.get("HOME") || Deno.env.get("USERPROFILE");
console.log(home);
const formatterArguments = parse(args, {
"--": false,
default: {
port: 62017,
path: "stylua",
files: `${home}${Separator}LuaFiles`,
config: "",
},
alias: {
"p": "port",
"h": "help",
},
}) as StyluaStudioArguments;
if (formatterArguments.help === true) console.log(OPTIONS_STRING);
else if (!formatterArguments.files || !formatterArguments.path)
console.log(`${red(bold("Error:"))} You are missing the ${bold("path")} or ${bold("files")} flag.\n${OPTIONS_STRING}`);
else {
const luaFiles = GetOrSetEnv("LuaFiles", formatterArguments.files);
GetOrSetEnv("StyluaPath", formatterArguments.path);
GetOrSetEnv("Config", formatterArguments.config)
ensureDir(luaFiles).then(() => {
const app = new Application();
const appRouter = new Router();
const port = 62017;
appRouter
.post("/formatLuau", FormatController.formatLuau)
.get("/getTest", FormatController.getTest);
app.use(appRouter.routes());
app.use(appRouter.allowedMethods());
app.addEventListener("listen", ({ secure, hostname, port }) => {
const protocol = secure ? "https://" : "http://";
const url = `${protocol}${hostname ?? "localhost"}:${port}`;
console.log(`Listening on: ${url}`);
})
app.listen({ port }).catch(error => console.warn(`Failed to listen on port ${port}: ${error}`));
}).catch(error => console.warn(`ensureDir(luaFiles) failed and returned error: ${error}`));
}
}
main(Deno.args);
|
0eaf158fe9aaf5e746181df408c190db115e3f06
|
TypeScript
|
akx/glitch2
|
/libglitch/modules/afterimage.ts
| 2.703125
| 3
|
import dataBlend from '../lib/dataBlend';
import * as p from '../param';
import GlitchContext from '../GlitchContext';
interface AfterimageOptions {
strengthIn: number;
strengthOut: number;
counterStrengthOut: number;
}
function afterimage(
glitchContext: GlitchContext,
pOptions: Partial<AfterimageOptions>,
) {
const options = { ...afterimageDefaults, ...pOptions };
const data = glitchContext.getImageData();
const afterimageData = glitchContext.persist.afterimageData as
| ImageData
| undefined;
if (afterimageData) {
dataBlend(
afterimageData,
data,
options.strengthOut,
options.counterStrengthOut,
'screen',
);
}
if (afterimageData && options.strengthIn < 1) {
dataBlend(
data,
afterimageData,
options.strengthIn,
1.0 - options.strengthIn,
'normal',
);
} else {
glitchContext.setImageData(data);
glitchContext.persist.afterimageData = glitchContext.copyImageData();
}
glitchContext.setImageData(data);
}
const afterimageDefaults: AfterimageOptions = {
strengthOut: 0.2,
counterStrengthOut: 0.3,
strengthIn: 0.2,
};
afterimage.paramDefaults = afterimageDefaults;
afterimage.params = [
p.num('strengthOut', { description: 'Afterimage write strength' }),
p.num('counterStrengthOut', {
description: 'Afterimage write counter-strength',
}),
p.num('strengthIn', { description: 'Afterimage read strength' }),
];
export default afterimage;
|
fdf0fd298be56a3c2afd3a69afea638a8aa9fd43
|
TypeScript
|
robblovell/toy-public-package
|
/src/compareOrder.ts
| 2.984375
| 3
|
export const compareOrder = (a, b) => {
const nameA = a.toUpperCase(); // ignore upper and lowercase
const nameB = b.toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0
}
|
b1b4182fa6fbce7a37222a19c4b00b08c2b77452
|
TypeScript
|
Raykid/Olympus
|
/trunk/src/engine/audio/AudioTagImpl.ts
| 2.6875
| 3
|
import { core } from "../../core/Core";
import { environment } from "../env/Environment";
import AudioMessage from "./AudioMessage";
import IAudio, { AudioPlayParams } from "./IAudio";
/**
* @author Raykid
* @email initial_r@qq.com
* @create date 2017-10-30
* @modify date 2017-10-30
*
* 使用Audio标签实现IAudio接口的实现类
*/
export default class AudioTagImpl implements IAudio
{
private _disposed:boolean = false;
public get disposed():boolean
{
return this._disposed;
}
private _mute:boolean = false;
private _playingDict:{[url:string]:AudioPlayParams} = {};
/**
* 静音状态
*
* @type {boolean}
* @memberof AudioTagImpl
*/
public get mute():boolean
{
return this._mute;
}
public set mute(value:boolean)
{
this._mute = value;
// 静音,暂停所有声音
for(var url in this._playingDict)
{
if(value)
{
// 静音,停止音频,不可调用stop方法,因为要保持播放中的音频状态
this._doStop(url);
}
else
{
// 非静音,播放音频
var params:AudioPlayParams = this._playingDict[url];
this.play(params);
}
}
}
private listenProgress(data:AudioData):void
{
data.node.ontimeupdate = (evt:Event)=>{
// 只有播放状态可以派发PROGRESS事件
if(data.status == AudioStatus.PLAYING)
{
// 我们规定使用毫秒值作为单位
var curTime:number = data.node.currentTime * 1000;
var totalTime:number = data.node.duration * 1000;
// 派发播放进度事件
core.dispatch(AudioMessage.AUDIO_PLAY_PROGRESS, data.playParams.url, curTime, totalTime, data.playParams);
}
};
}
private _audioCache:{[url:string]:AudioData} = {};
/**
* 加载音频
*
* @param {string} url 音频地址
* @memberof AudioTagImpl
*/
public load(url:string):void
{
var toUrl:string = environment.toCDNHostURL(url);
// 尝试获取缓存数据
var data:AudioData = this._audioCache[toUrl];
// 如果没有缓存才去加载
if(!data)
{
// 派发加载开始事件
core.dispatch(AudioMessage.AUDIO_LOAD_STARTED, url);
// 使用Audio标签加载
var node:HTMLAudioElement = document.createElement("audio");
// 这里强制使用autoplay,因为在IOS的safari上如果没这个参数,则根本不会触发onloadeddata事件
node.autoplay = true;
node.src = toUrl;
// 保存数据
this._audioCache[toUrl] = data = {node: node, status: AudioStatus.LOADING, playParams: null};
// 监听加载
node.onloadeddata = ()=>{
// 记录加载完毕
data.status = AudioStatus.PAUSED;
// 派发加载完毕事件
core.dispatch(AudioMessage.AUDIO_LOAD_ENDED, url);
// 如果不自动播放则暂停
if(!data.playParams)
{
node.pause();
}
else
{
var params:AudioPlayParams = data.playParams;
// 设置状态
data.status = AudioStatus.PLAYING;
// 记录播放中
this._playingDict[toUrl] = params;
// 派发播放开始事件
core.dispatch(AudioMessage.AUDIO_PLAY_STARTED, params.url, params);
// 监听播放进度
this.listenProgress(data);
}
};
node.onended = ()=>{
this.stop(url);
// 派发播放完毕事件
core.dispatch(AudioMessage.AUDIO_PLAY_ENDED, url, data.playParams);
// 如果循环则再开
if(data.playParams.loop)
this.play(data.playParams);
};
node.onerror = (evt:ErrorEvent)=>{
//派发错误事件
core.dispatch(AudioMessage.AUDIO_ERROR, url, evt);
};
}
}
/**
* 播放音频,如果音频没有加载则先加载再播放
*
* @param {AudioPlayParams} params 音频播放参数
* @returns {void}
* @memberof AudioTagImpl
*/
public play(params:AudioPlayParams):void
{
var toUrl:string = environment.toCDNHostURL(params.url);
// 尝试获取缓存数据
var data:AudioData = this._audioCache[toUrl];
if(!data)
{
// 没有加载过,开始加载音频
this.load(params.url);
// 设置播放参数
this._audioCache[toUrl].playParams = params;
}
else
{
switch(data.status)
{
case AudioStatus.LOADING:
// 正在加载中,替换自动播放参数
data.playParams = params;
break;
case AudioStatus.PLAYING:
// 正在播放,关闭后再播放
this.stop(params.url);
this.play(params);
break;
case AudioStatus.PAUSED:
// 已经加载完毕,暂停中,直接播放
data.playParams = params;
if(params.stopOthers) this.stopAll();
if(params.loop != null) data.node.loop = params.loop;
if(params.time != null) data.node.currentTime = params.time * 0.001;
// 监听播放进度
this.listenProgress(data);
// 开始播放,safari不支持直接play(WTF?)所以要用autoplay加load进行播放
data.node.autoplay = true;
data.node.load();
// 设置状态
data.status = AudioStatus.PLAYING;
// 记录播放中
this._playingDict[toUrl] = params;
// 派发播放开始事件
core.dispatch(AudioMessage.AUDIO_PLAY_STARTED, params.url, params);
break;
}
}
}
private _doStop(url:string, time?:number):void
{
var toUrl:string = environment.toCDNHostURL(url);
if(this._playingDict[toUrl])
{
var data:AudioData = this._audioCache[toUrl];
data.node.autoplay = false;
data.node.pause();
// 设置停止时间
if(time != null) data.node.currentTime = time * 0.001;
// 设置状态
data.status = AudioStatus.PAUSED;
// 派发播放停止事件
core.dispatch(AudioMessage.AUDIO_PLAY_STOPPED, url, data.playParams);
}
}
/**
* 暂停音频(不会重置进度)
*
* @param {string} url 音频URL
* @memberof AudioTagImpl
*/
public pause(url:string):void
{
this._doStop(url);
// 移除播放中
var toUrl:string = environment.toCDNHostURL(url);
delete this._playingDict[toUrl];
}
/**
* 停止音频(会重置进度)
*
* @param {string} url 音频URL
* @memberof AudioTagImpl
*/
public stop(url:string):void
{
this._doStop(url, 0);
// 移除播放中
var toUrl:string = environment.toCDNHostURL(url);
delete this._playingDict[toUrl];
}
/**
* 停止所有音频
*
* @memberof AudioTagImpl
*/
public stopAll():void
{
for(var url in this._audioCache)
{
this.stop(url);
}
}
/**
* 跳转音频进度
*
* @param {string} url 音频URL
* @param {number} time 要跳转到的音频位置,毫秒值
* @memberof AudioTagImpl
*/
public seek(url:string, time:number):void
{
var data:AudioData = this._audioCache[url];
if(data) data.node.currentTime = time * 0.001;
}
public dispose():void
{
if(!this._disposed)
{
this.stopAll();
this._disposed = true;
}
}
}
enum AudioStatus
{
/**
* 加载中
*/
LOADING,
/**
* 已暂停
*/
PAUSED,
/**
* 播放中
*/
PLAYING
}
interface AudioData
{
/**
* 音频的HTML节点
*
* @type {HTMLAudioElement}
* @memberof AudioData
*/
node:HTMLAudioElement;
/**
* 音频状态
*
* @type {AudioStatus}
* @memberof AudioData
*/
status:AudioStatus;
/**
* 播放参数
*
* @type {AudioPlayParams}
* @memberof AudioData
*/
playParams:AudioPlayParams;
}
|
4c4988592c2186445dae710f601b55c3a4103598
|
TypeScript
|
green-fox-academy/somakanyasi
|
/Week04/Day-04/count-letters.test.ts
| 2.59375
| 3
|
'use strict';
import { countLetters } from './count-letters';
import { myString } from './count-letters';
const test = require('tape');
test('It should count the letters in a given string', (test) => {
test.equal(countLetters(myString), true, 'should be the same');
test.end();
});
|
4f1fb8d5545f55e4f987b79ce27899036d74eb93
|
TypeScript
|
Atticus29/angular-recipe-box
|
/app/app.component.ts
| 2.703125
| 3
|
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app/app.component.html'
})
export class AppComponent {
recipes: Recipe[] =[
new Recipe('Apple pie', 'Just make an apple pie'),
new Recipe('Salad', 'you should already know'),
new Recipe('Tv dinner', 'epic fail....')
];
selectedRecipe = null;
editMode = null;
turnOnEditMode(){
this.editMode = true;
}
hideDetails() {
this.selectedRecipe = null;
this.editMode = null;
}
revealDetails(currentRecipe) {
this.selectedRecipe = currentRecipe;
}
}
export class Recipe{
constructor (public title: string, public details: string){}
revealDetails(currentRecipe){
}
}
|
109bb027a79230c363ef8e2c5ce1f02378e7f6fe
|
TypeScript
|
davidsantander9/intro-typescript
|
/src/exercises/06-fun-desestructuring.ts
| 3.28125
| 3
|
export interface Product{
desc: string;
price: number;
}
const phone: Product = {
desc: 'Nokia A1',
price: 150,
}
const tablet: Product = {
desc: 'iPad',
price: 350,
}
export function calcISV( products: Product[]):[number, number] {
let total: number = 0;
products.forEach( ({ price }) => {
total += price;
})
return [total, total * 0.15];
}
const articles = [ phone, tablet ];
const [total, isv] = calcISV(articles);
console.log(total, isv);
|
8a3af606153f7b611ae031ebc368142f4138996e
|
TypeScript
|
otienonick/Quote-App
|
/src/app/quote.ts
| 2.515625
| 3
|
export class Quote {
id:number;
author:string;
quote:string;
quoteDetails:string;
showDetails:boolean;
constructor(id:number,author:string,quote:string, quoteDetails:string,public completeDate: Date )
{
this.id = id;
this.author = author;
this.quote = quote;
this.quoteDetails = quoteDetails;
this.showDetails = false;
}
}
|
b47a11ad3204cae330d581cbfb4d5dbebe732d2c
|
TypeScript
|
lanets/scavengets
|
/angular-client/src/app/shared/services/challenge.service.ts
| 2.59375
| 3
|
import {EventEmitter, Injectable} from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Observable';
import {Challenge} from '@models';
@Injectable()
export class ChallengeService {
// Link to our api, pointing to localhost
private readonly API = 'http://localhost:3000';
// Declare empty list of people
private challenges: any[] = [];
private challengeIsEdit = new EventEmitter<Challenge>();
constructor(private http: Http) { }
// Add one challenge to the API
public addChallenge(challenge: Challenge) {
const body = JSON.stringify(challenge);
return this.http.post(`${this.API}/challenges`, body)
.map(res => {
const result = res.json();
const cha = new Challenge(result.obj.title, result.obj.description, result.obj.points, result.obj._id);
this.challenges.push(cha);
});
}
// Get all users from the API
public getAllChallenges() {
return this.http.get(`${this.API}/challenges`)
.map(res => {
const challenges = res.json().obj;
const transformedChallenges: Challenge[] = [];
for (const challenge of challenges){
transformedChallenges.push(new Challenge(challenge.title, challenge.description, challenge.points, challenge._id));
}
this.challenges = transformedChallenges;
return transformedChallenges;
})
.catch((err: Response) => Observable.throw(err.json()));
}
public editChallenge(challenge: Challenge) {
this.challengeIsEdit.emit(challenge);
}
// public updateChallenge(challenge: Challenge){
// const body = JSON.stringify(challenge);
// return this.http.patch(`${this.API}/challenges` + challenge.challengeId, body)
// .map((res) => res.json())
// .catch((err) => Observable.throw(err.json()));
// }
public deleteMessage(challenge: Challenge) {
this.challenges.splice(this.challenges.indexOf(challenge), 1);
return this.http.delete(`${this.API}/challenges` + challenge.challengeId)
.map((res => res.json()))
.catch((err => Observable.throw(err.json())));
}
}
|
15cbf4b3e86bdf1a448375df3f4243929b985c46
|
TypeScript
|
vmauricio93/MyPlanner
|
/src/app/shared/autocomplete.directive.ts
| 2.6875
| 3
|
import { Directive, ElementRef, Input, OnInit } from '@angular/core';
import autocomplete, { AutocompleteItem } from 'autocompleter';
type Option = string & AutocompleteItem;
@Directive({
selector: '[appAutocomplete]'
})
export class AutocompleteDirective implements OnInit {
@Input() options: string[];
fetch: any;
constructor(private el: ElementRef) { }
ngOnInit(): void {
this.fetch = (text: string, update: (items: string[]) => void) => {
text = text.toLowerCase();
let suggestions = this.options.filter(
option => option.toLowerCase().startsWith(text)
);
update(suggestions);
return { text, suggestions };
};
this.autocomplete();
}
// Should these methods be private?
autocomplete(): void {
autocomplete<Option>({
input: this.el.nativeElement,
minLength: 1,
fetch: this.fetch,
onSelect: this.setValueOnSelect,
render: this.render
});
}
setValueOnSelect(item: string, input: HTMLInputElement): string {
input.value = item;
// Trigger input value change event to update model value
input.dispatchEvent(new Event('input'));
return input.value;
}
render(item: string, currentValue: string): HTMLDivElement | undefined {
const itemElement = document.createElement("div");
itemElement.textContent = item;
return itemElement;
}
}
|
afeadeed9122c208de5cf65e12bc35c0fef91af3
|
TypeScript
|
Fershark/react-native-login
|
/app/redux/AuthSlice.spec.ts
| 2.625
| 3
|
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import authReducer, {logout, login, AuthState} from './AuthSlice';
import AuthService from '../services/AuthService';
jest.mock('../services/AuthService');
const mockStore = configureMockStore([thunk]);
const initialState: AuthState = {
status: 'idle',
auth: null,
error: null,
};
const authLoginParams = {
email: 'test',
password: 'test',
};
const expectedAuth = {
id: '0b9a9a6b-df41-46f2-a4b8-05844eb97f91',
first_name: 'Mo Demo',
last_name: 'User',
};
describe('auth reducer', () => {
it('should handle initial state', () => {
expect(authReducer(undefined, {} as any)).toEqual(initialState);
});
it('should handle login request', () => {
expect(
authReducer(
{...initialState, error: {message: 'Error'}},
{type: login.pending.type},
),
).toEqual({
...initialState,
status: 'loading',
});
});
it('should handle login success', () => {
expect(
authReducer(
{...initialState, status: 'loading'},
{
type: login.fulfilled.type,
payload: expectedAuth,
},
),
).toEqual({
...initialState,
auth: expectedAuth,
});
});
it('should handle login error', () => {
const expectedError = {
message: 'Error',
};
expect(
authReducer(
{...initialState, status: 'loading'},
{
type: login.rejected.type,
error: expectedError,
},
),
).toEqual({
...initialState,
status: 'failed',
error: expectedError,
});
});
it('should dispatch actions login.pending and login.fulfilled', async () => {
AuthService.login = jest
.fn()
.mockImplementationOnce((params) => expectedAuth);
const store = mockStore({});
await store.dispatch(login(authLoginParams));
const actions = store.getActions();
expect(actions[0].type).toBe(login.pending.type);
expect(actions[1].type).toBe(login.fulfilled.type);
expect(actions[1].payload).toBe(expectedAuth);
});
it('should dispatch actions login.pending and login.rejected', async () => {
const expectedError = new Error('Network Error');
AuthService.login = jest
.fn()
.mockImplementationOnce((params) => Promise.reject(expectedError));
const store = mockStore({});
await store.dispatch(login(authLoginParams));
const actions = store.getActions();
expect(actions[0].type).toBe(login.pending.type);
expect(actions[1].type).toBe(login.rejected.type);
expect(actions[1].error).toBeDefined();
});
});
|
ce6755a31d9038acb8203cf4cf941f9f6163f677
|
TypeScript
|
MatheusClaudi/use
|
/src/app/models/detection/detection_report.ts
| 2.640625
| 3
|
import { DetectionAction } from '../enum/detection_action';
export class DetectionReport{
action: DetectionAction;
label: string;
previousNumberObjects: number;
newNumberObjects: number;
moment: Date;
makeEntryReport(label, previousNumberObjects, newNumberObjects, moment){
this.action = DetectionAction.ENTRY;
this.label = label;
this.previousNumberObjects = previousNumberObjects;
this.newNumberObjects = newNumberObjects;
this.moment = moment;
}
makeExitReport(label, previousNumberObjects, newNumberObjects, moment){
this.action = DetectionAction.EXIT;
this.label = label;
this.previousNumberObjects = previousNumberObjects;
this.newNumberObjects = newNumberObjects;
this.moment = moment;
}
}
|
91e94082d18fe5bf14a3f72cab300556df0f22f4
|
TypeScript
|
xiong35/type-challenges-solutions
|
/src/2070-DropChar-medium/index.ts
| 3.21875
| 3
|
namespace T2070 {
/* 答案 */
type Split<S extends string, Arr extends string[] = []> = S extends `${infer F}${infer R}`
? Split<R, [...Arr, F]>
: Arr
type Length<S extends string> = Split<S>["length"]
type DropChar<
S extends string,
C extends string,
D extends string = ""
> = Length<C> extends 1
? S extends `${infer F}${infer R}`
? F extends C
? DropChar<R, C, D>
: DropChar<R, C, `${D}${F}`>
: D
: never;
/* 测试 */
type Butterfly = DropChar<" b u t t e r f l y ! ", " ">; // 'butterfly!'
}
|
2d14127bb52f11fdff01952e89d70140d41c0158
|
TypeScript
|
njmyers/javascript-monorepo
|
/packages/component-library/src/utils/safe-ref.ts
| 2.65625
| 3
|
import * as React from 'react';
export const safeRefValue = (ref: React.RefObject<any>, value: string) => {
if (ref.current) {
return ref.current[value];
}
return null;
};
export const safeRefCall = (ref: React.RefObject<any>, method: string) => {
const func = safeRefValue(ref, method);
if (func && typeof func === 'function') {
return func;
}
return () => null;
};
|
533c6413b89b23e06644b03262c25ad4849e6279
|
TypeScript
|
CobraWing/decodificador
|
/src/main/utils/Signal.ts
| 3.453125
| 3
|
/*
* Copyright (C) 2017 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
/**
* Internally used container for a signal handler function bound to an object.
*
* @param <T> The signal payload type.
*/
class Slot<T> {
private func: (data: T) => void;
private context: Object | null;
public constructor(func: (data: T) => void, context: Object | null = null) {
this.func = func;
this.context = context;
}
public call(data: T) {
this.func.call(this.context, data);
}
public equals(func: (data: T) => void, context: Object | null = null): boolean {
return this.func === func && this.context === context;
}
}
/**
* Interface of the subscription object returned by [[Signal.subscribe]]().
*/
export interface Subscription {
/**
* Unsubscribes the subscribed observer.
*/
unsubscribe(): void;
}
/**
* Interface for the observer object to pass to the [[Signal.subscribe]]() method. Only the [[next]]() method is
* supported here. Error handling is not implemented and signals are never ending so there is also no support for
* the `complete()` method or the `closed` property.
*/
export interface Observer<T> {
next: (data: T) => void;
}
/**
* The observable interface implemented by the Signal class. See https://github.com/jhusain/observable-spec
* for details.
*/
export interface Observable<T> {
subscribe(observer: Observer<T> | ((value: T) => void)): Subscription;
}
/**
* A signal is some kind of high-performant event emitter. You can connect listener functions or methods to it which
* will then all be called when a new value is emitted. This class also rudimentary implements the [[Observable]]
* interface so a signal can be used as a faster alternative to Angular's event emitters and can cooperate to some
* degree with RxJS.
*
* @param <T> The signal payload type.
*/
export class Signal<T = void> implements Observable<T> {
/** The list of registered signal listeners (slots). Entries may be null if deleted. */
private slots: Array<Slot<T> | null> = [];
/**
* Connects the given listener function or method to the signal.
*
* @param func The listener function.
* @param context Optional context to bind the listener function to, making it a method.
*/
public connect(func: (data: T) => void, context: Object | null = null): void {
this.slots.push(new Slot(func, context));
}
/**
* Disconnects the given listener function or method from the signal. If the listener is connected multiple
* times then only the first listener is disconnected. If listener is not connected at all then this method
* does nothing.
*
* @param func The listener function to disconnect.
* @param context Optional binding context in case listener function is a method.
*/
public disconnect(callback: (data: T) => void, context: Object | null = null): void {
const slots = this.slots;
for (let i = slots.length - 1; i >= 0; --i) {
const slot = slots[i];
if (slot && slot.equals(callback, context)) {
slots[i] = null;
break;
}
}
}
/**
* Emits the signal with the given value.
*
* @param value The signal payload value to emit.
*/
public emit(value: T): void {
const slots = this.slots;
for (let i = 0, max = slots.length; i < max; ++i) {
const slot = slots[i];
if (slot) {
slot.call(value);
} else {
slots.splice(i, 1);
--i;
--max;
}
}
}
/**
* Subscribes the given observer to the signal. For compatibility to Angular the observer can also be
* a function. Returns a subscription object which can be used to unsubscribe the observer from the signal.
*
* @param observer The observer (or function) to subscribe.
* @return The subscription which can be used to unsubscribe the observer from the signal.
*/
public subscribe(observer: Observer<T> | ((value: T) => void)): Subscription {
let func: (value: T) => void;
let context: Object | null;
if (observer instanceof Function) {
func = observer;
context = null;
} else {
func = observer.next;
context = observer;
}
this.connect(func, context);
return {
unsubscribe: () => {
this.disconnect(func, context);
}
};
}
}
|
c9ee249abee930e72fbae476e8600b49117bb22e
|
TypeScript
|
abdoulayekeita/exmen
|
/gateway/src/main/webapp/app/shared/model/partener/type.model.ts
| 2.984375
| 3
|
export interface IType {
id?: number;
title?: string;
}
export class Type implements IType {
constructor(public id?: number, public title?: string) {}
}
|
310c1473f23dc78125cc479c43029dcb59fa780b
|
TypeScript
|
lingualogic/speech-framework
|
/src/bot/bot.ts
| 2.5625
| 3
|
/** @packageDocumentation
* Dialog API Wrapper fuer BotComponent.
*
* Letzte Aenderung: 01.06.2020
* Status: gelb
*
* @module bot
* @author SB
*/
// core
import { OnSpeechErrorFunc } from '@speech/core';
// base
import { Base } from '@speech/base';
// speak
import { SpeakInterface } from '@speech/speak';
// listen
import { ListenInterface } from '@speech/listen';
// action
import { ActionInterface } from '@speech/action';
// dialog
import {
OnDialogSetFunc,
OnDialogJsonFunc,
OnDialogParseFunc,
OnDialogStartFunc,
OnDialogStopFunc,
OnDialogStateSetFunc,
OnDialogActionFunc,
OnDialogActionStopFunc,
OnDialogSpeakFunc,
OnDialogSpeakStartFunc,
OnDialogSpeakStopFunc,
DialogStateContextInterface,
DialogDataInterface
} from '@speech/dialog';
// bot
import { BOT_TYPE_NAME } from './bot-const';
import { BotOptionInterface } from './bot-option.interface';
import { BotInterface } from './/bot.interface';
import { BotComponentInterface } from './component/bot-component.interface';
/** @export
* Dialog Klasse als API-Wrapper fuer die BotComponent
*/
export class Bot extends Base implements BotInterface {
// interne Dialog-Komponente
mBotComponent: BotComponentInterface = null;
/**
* Konstruktor fuer ereignisbasierte Initialisierung des Bots
*/
constructor( aOption?: BotOptionInterface ) {
super( aOption );
// eintragen der spezifischen Komponente
this.mBotComponent = this.mComponent as BotComponentInterface;
}
/**
* Rueckgabe des Default Buildernamens, der verwendet wird,
* wenn kein anderer Buildername uebergeben wurde.
*
* @returns {string} Rueckgabe des Default Buildernamens
*/
_getBuilderName(): string {
return BOT_TYPE_NAME;
}
// Event-Funktionen
addDialogSetEvent( aPluginName: string, aEventFunc: OnDialogSetFunc ): number {
return this.mBotComponent.addDialogSetEvent( aPluginName, aEventFunc );
}
addDialogJsonEvent( aPluginName: string, aEventFunc: OnDialogJsonFunc ): number {
return this.mBotComponent.addDialogJsonEvent( aPluginName, aEventFunc );
}
addDialogParseEvent( aPluginName: string, aEventFunc: OnDialogParseFunc ): number {
return this.mBotComponent.addDialogParseEvent( aPluginName, aEventFunc );
}
addDialogStartEvent( aPluginName: string, aEventFunc: OnDialogStartFunc ): number {
return this.mBotComponent.addDialogStartEvent( aPluginName, aEventFunc );
}
addDialogStopEvent( aPluginName: string, aEventFunc: OnDialogStopFunc ): number {
return this.mBotComponent.addDialogStopEvent( aPluginName, aEventFunc );
}
addDialogStateSetEvent( aPluginName: string, aEventFunc: OnDialogStateSetFunc ): number {
return this.mBotComponent.addDialogStateSetEvent( aPluginName, aEventFunc );
}
addDialogActionEvent( aPluginName: string, aEventFunc: OnDialogActionFunc ): number {
return this.mBotComponent.addDialogActionEvent( aPluginName, aEventFunc );
}
addDialogActionStopEvent( aPluginName: string, aEventFunc: OnDialogActionStopFunc ): number {
return this.mBotComponent.addDialogActionStopEvent( aPluginName, aEventFunc );
}
addDialogSpeakEvent( aPluginName: string, aEventFunc: OnDialogSpeakFunc ): number {
return this.mBotComponent.addDialogSpeakEvent( aPluginName, aEventFunc );
}
addDialogSpeakStartEvent( aPluginName: string, aEventFunc: OnDialogSpeakStartFunc ): number {
return this.mBotComponent.addDialogSpeakStartEvent( aPluginName, aEventFunc );
}
addDialogSpeakStopEvent( aPluginName: string, aEventFunc: OnDialogSpeakStopFunc ): number {
return this.mBotComponent.addDialogSpeakStopEvent( aPluginName, aEventFunc );
}
addErrorEvent( aPluginName: string, aEventFunc: OnSpeechErrorFunc ): number {
return this.mBotComponent.addErrorEvent( aPluginName, aEventFunc );
}
removeDialogSetEvent( aPluginName: string ): number {
return this.mBotComponent.removeDialogSetEvent( aPluginName );
}
removeDialogJsonEvent( aPluginName: string ): number {
return this.mBotComponent.removeDialogJsonEvent( aPluginName );
}
removeDialogParseEvent( aPluginName: string ): number {
return this.mBotComponent.removeDialogParseEvent( aPluginName );
}
removeDialogStartEvent( aPluginName ): number {
return this.mBotComponent.removeDialogStartEvent( aPluginName );
}
removeDialogStopEvent( aPluginName ): number {
return this.mBotComponent.removeDialogStopEvent( aPluginName );
}
removeDialogStateSetEvent( aPluginName: string ): number {
return this.mBotComponent.removeDialogStateSetEvent( aPluginName );
}
removeDialogActionEvent( aPluginName: string ): number {
return this.mBotComponent.removeDialogActionEvent( aPluginName );
}
removeDialogActionStopEvent( aPluginName: string ): number {
return this.mBotComponent.removeDialogActionStopEvent( aPluginName );
}
removeDialogSpeakEvent( aPluginName: string ): number {
return this.mBotComponent.removeDialogSpeakEvent( aPluginName );
}
removeDialogSpeakStartEvent( aPluginName: string ): number {
return this.mBotComponent.removeDialogSpeakStartEvent( aPluginName );
}
removeDialogSpeakStopEvent( aPluginName: string ): number {
return this.mBotComponent.removeDialogSpeakStopEvent( aPluginName );
}
removeErrorEvent( aPluginName: string ): number {
return this.mBotComponent.removeErrorEvent( aPluginName );
}
removeAllEvent( aPluginName: string ): number {
return this.mBotComponent.removeAllEvent( aPluginName );
}
// Speak-Funktionen
isSpeak(): boolean {
return this.mBotComponent.isSpeak();
}
setSpeakOn(): number {
return this.mBotComponent.setSpeakOn();
}
setSpeakOff(): number {
return this.mBotComponent.setSpeakOff();
}
getSpeak(): SpeakInterface {
return this.mBotComponent.getSpeak();
}
// Listen-Funktionen
isListen(): boolean {
return this.mBotComponent.isListen();
}
setListenOn(): number {
return this.mBotComponent.setListenOn();
}
setListenOff(): number {
return this.mBotComponent.setListenOff();
}
getListen(): ListenInterface {
return this.mBotComponent.getListen();
}
// Action-Funktionen
isAction(): boolean {
return this.mBotComponent.isAction();
}
setActionOn(): number {
return this.mBotComponent.setActionOn();
}
setActionOff(): number {
return this.mBotComponent.setActionOff();
}
getAction(): ActionInterface {
return this.mBotComponent.getAction();
}
// Json-Funktionen
transformJsonFile( aJsonFileName: string ): number {
return this.mBotComponent.transformJsonFile( aJsonFileName );
}
transformJsonData( aJsonData: DialogDataInterface[]): number {
return this.mBotComponent.transformJsonData( aJsonData );
}
// Parser-Funktionen
parseSpeechDefFile( aFileName: string ): number {
return this.mBotComponent.parseSpeechDefFile( aFileName );
}
parseSpeechDefData( aData: string ): number {
return this.mBotComponent.parseSpeechDefData( aData );
}
// Dialog-Funktionen
clearDialog(): number {
return this.mBotComponent.clearDialog();
}
setDialog( aDialogName: string ): number {
return this.mBotComponent.setDialog( aDialogName );
}
getDialog(): string {
return this.mBotComponent.getDialog();
}
toggleDialog(): number {
return this.mBotComponent.toggleDialog();
}
setDialogFilePath( aDialogFilePath: string ): number {
return this.mBotComponent.setDialogFilePath( aDialogFilePath );
}
getDialogFilePath(): string {
return this.mBotComponent.getDialogFilePath();
}
setDialogFileName( aDialogFileName: string ): number {
return this.mBotComponent.setDialogFileName( aDialogFileName );
}
getDialogFileName(): string {
return this.mBotComponent.getDialogFileName();
}
loadDialogFile( aDialogFileName: string ): number {
return this.mBotComponent.loadDialogFile( aDialogFileName );
}
writeDialogData( aDialogData: string ): number {
return this.mBotComponent.writeDialogData( aDialogData );
}
skipNextSpeak(): number {
return this.mBotComponent.skipNextSpeak();
}
// Zustands-Funktionen
setDialogState( aState: string, aContext?: DialogStateContextInterface ): number {
return this.mBotComponent.setDialogState( aState, aContext );
}
getDialogState(): string {
return this.mBotComponent.getDialogState();
}
setDialogStateContext( aContext: DialogStateContextInterface ): number {
return this.mBotComponent.setDialogStateContext( aContext );
}
// Kontext-Funktionen
clearContext(): number {
return this.mBotComponent.clearContext();
}
addContextElement( aElementName: string, aContextName: string ): number {
return this.mBotComponent.addContextElement( aElementName, aContextName );
}
removeContextElement( aElementName: string, aContextName: string ): number {
return this.mBotComponent.removeContextElement( aElementName, aContextName );
}
}
|
23b9548ed5b82ed4f6ce71f2d4540a7d5356ae7d
|
TypeScript
|
sweetmnstr/trade-cabinet-demo
|
/gateway-lead/src/modules/auth/auth.dto.ts
| 2.765625
| 3
|
import { ApiProperty } from '@nestjs/swagger';
import { IsEmail, IsUUID, Length } from 'class-validator';
import { ILoginDto, ISignupDto, IRefreshTokenDto, ITokenResponse } from 'trade-cabinet-types';
import { ToPhone } from '../../lib/decorators/transformers.decorator';
export class LoginDto implements ILoginDto {
@ApiProperty({ example: 'test@test.com', description: 'Should be valid email with @ and domain' })
@IsEmail()
email: string;
@ApiProperty({
minLength: 6,
maxLength: 18,
example: '123456',
description: 'There is no special validation, only min/max length',
})
@Length(6, 18)
password: string;
}
export class SignupDto extends LoginDto implements ISignupDto {
@ApiProperty({ example: 'Testname' })
@Length(1, 25)
firstName: string;
@ApiProperty({ example: 'Testlast' })
@Length(1, 25)
lastName: string;
@ApiProperty({ example: '+14158586273', description: 'Required to be in e164 format, check it before request' })
@ToPhone
@Length(1, 20)
phone: string;
}
export class RefreshTokenDto implements IRefreshTokenDto {
@ApiProperty()
@IsUUID()
refreshToken: string;
// @IsNotEmpty()
// fingerprint: string;
}
export class TokenResponse implements ITokenResponse {
@ApiProperty({
description: 'UUIDv4 user session, deletes 1st token after limit reached, jwt is alive anyway before expire',
example: '3a124fa4-9de4-4bd6-b90a-b54d7fe97afd',
})
refreshToken: string;
@ApiProperty({
description: "Bearer token (JWT) stores inside user's id and type (admin | user) and expire date",
example: 'xxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxx',
})
accessToken: string;
@ApiProperty({
description: 'Unix timestamp of refreshToken life, before this date you should use /refresh-token method',
example: 1601810548,
})
expiredAt: number;
}
|
ef43b41b8189b7ed6662e6aa7228c4829b6eef0a
|
TypeScript
|
ErliSoares/Koralium
|
/typescript-client/json/src/filterBuilder.ts
| 3.171875
| 3
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ParameterBuilder } from "./parameterBuilder";
function isString(val: any): val is string {
return typeof (val) === "string";
}
function isNumber(val: any): val is number {
return typeof (val) === "number";
}
function isBoolean(val: any): val is boolean {
return typeof (val) === 'boolean';
}
//Check if the value is a FieldQuery type
function isFieldQuery(val: any): val is FieldQuery {
return val.eq !== undefined ||
val.lt !== undefined ||
val.lte !== undefined ||
val.gt !== undefined ||
val.gte !== undefined ||
val.startsWith !== undefined ||
val.endsWith !== undefined ||
val.contains !== undefined;
}
function writeSingleValue(arr: Array<string>, parameters: ParameterBuilder, val: string | number | boolean | undefined, operation: (string: string) => string): void {
if (val !== undefined) {
if (isString(val)) {
const parameterName = parameters.getParameterName(val);
arr.push(operation(`@${parameterName}`));
}
if (isNumber(val)) {
arr.push(operation(`${val}`));
}
if (isBoolean(val)) {
arr.push(operation(`${val}`));
}
}
}
export function writeFilter(filter: {} | FieldQuery): FilterResult {
const parameters = new ParameterBuilder();
const result = writeFilterWithParameterBuilder(parameters, filter);
return new FilterResult(result, parameters.getParameters());
}
function writeSearchFilter(parameters: ParameterBuilder, value: SearchFilter): string {
if (value.queryString !== undefined) {
let output = "CONTAINS(";
if (value.fields !== undefined) {
output += `(${value.fields.join(', ')})`;
}
else{
output += "*";
}
output += ", ";
output += `@${parameters.getParameterName(value.queryString)}`;
output += ")";
return output;
}
return "";
}
export function writeFilterWithParameterBuilder(parameterBuilder: ParameterBuilder, filter: {} | FieldQuery): string {
let operations: Array<string> = [];
let andOperation = null;
let orOperation = null;
for (let [key, value] of Object.entries(filter)) {
if (isFieldQuery(value)) {
operations.push(writeFilterField(key, value, parameterBuilder));
}
if (key === "and") {
andOperation = writeFilterWithParameterBuilder(parameterBuilder, value);
}
if (key === "or") {
orOperation = writeFilterWithParameterBuilder(parameterBuilder, value);
}
if(key === "search") {
operations.push(writeSearchFilter(parameterBuilder, value));
}
}
let query = "";
operations = operations.filter(x => x !== "");
if(operations.length > 0) {
query = `(${operations.join(" AND ")})`;
}
if (andOperation != null) {
if(query !== "") {
query += " AND ";
}
query += andOperation;
}
if (orOperation != null) {
if(query !== "") {
query += " OR ";
}
query += orOperation;
}
return query;
}
function writeFilterField(fieldName: string, field: FieldQuery, parameters: ParameterBuilder): string {
const basicOperations: Array<string> = [];
writeSingleValue(basicOperations, parameters, field.eq, c => `${fieldName} = ${c}`);
writeSingleValue(basicOperations, parameters, field.gt, c => `${fieldName} > ${c}`);
writeSingleValue(basicOperations, parameters, field.gte, c => `${fieldName} >= ${c}`);
writeSingleValue(basicOperations, parameters, field.lt, c => `${fieldName} < ${c}`);
writeSingleValue(basicOperations, parameters, field.lte, c => `${fieldName} <= ${c}`);
//string specific
writeSingleValue(basicOperations, parameters, field.contains, c => `${fieldName} LIKE '%' + ${c} + '%'`);
writeSingleValue(basicOperations, parameters, field.endsWith, c => `${fieldName} LIKE '%' + ${c}`);
writeSingleValue(basicOperations, parameters, field.startsWith, c => `${fieldName} LIKE ${c} + '%'`);
let basicQuery = basicOperations.join(" AND ");
return basicQuery;
}
export class FilterResult {
filter: string;
parameters: {};
constructor(filter: string, parameters: {}) {
this.filter = filter;
this.parameters = parameters;
}
}
export class FieldQuery {
eq: string | number | boolean | undefined;
lt: string | number | undefined;
lte: string | number | undefined;
gt: string | number | undefined;
gte: string | number | undefined;
//String specific
startsWith: string | number | undefined;
endsWith: string | number | undefined;
contains: string | number | undefined;
}
export class SearchFilter {
queryString: string | undefined;
fields: Array<string> | undefined;
}
|
ef41b254cdc98e845f91d5bb394fe1501d85cf1b
|
TypeScript
|
KovalevichD/practice-js
|
/src/type-b/b8.mapLimit.ts
| 3.03125
| 3
|
/*
* Задача b8: mapLimit
* Есть массив url, есть функция fetch, которая возвращает промис
* Есть ограничение по количеству параллельно запущеных request'ов
* Нужно отправлять запросы ПАРАЛЕЛЛЬНО пачками, как только выполнились все N (переменная limit) запросов
* отправлять следующие N запросов
* Например, есть 12 url, отправляются 5, как только 5 запросов выполняются отправляем еще 5, затем 2
* Когда все запросы обработаны, функция возвращает массив с резульататами.
* Напишите тесты.
*/
/*
Примеры:
const urls = ['http://test1.ru',
'http://test2.ru',
'http://test3.ru',
'http://test4.ru',
'http://test5.ru',
'http://test6.ru',
'http://test7.ru',
'http://test8.ru',
'http://test9.ru'
];
const limit = 5; // количество одновременно запущенных запросов
mapLimit(urls, limit);
*/
|
f5070d7a358b7389c71d911efe9a11abd472ced7
|
TypeScript
|
Jonathan-Brito/mentoria-typescript
|
/src/respostas/desafio1.ts
| 3.984375
| 4
|
// Resposta 1
const funcionario = {
codigo: 10,
nome: 'João'
};
// Resposta 2
const funcionario2: {codigo: number, nome: string} = {
codigo: 10,
nome: 'joao'
}
// Respostas 3 e 4
interface Funcionario { // Já conhece interfaces? https://blog.logrocket.com/types-vs-interfaces-in-typescript/
codigo: number,
nome: string
};
const funcionarioObj = {} as Funcionario;
funcionarioObj.codigo = 10;
funcionarioObj.nome = 'João';
const funcionarioObj2: Funcionario = {
codigo: 10,
nome: 'João'
}
|
731b0bb7042724cb028c981e826b89fbecdb6f72
|
TypeScript
|
rzyns/type-plus
|
/src/Partial.spec.ts
| 2.765625
| 3
|
import { PartialExcept, PartialPick, assertType, PartialOmit } from '.';
test('make picked properties optional', () => {
type Foo = {
a: number,
b: number,
c: number,
}
const y: PartialPick<Foo, 'a'> = {} as any
y.a = undefined
assertType.noUndefined(y.b)
assertType.noUndefined(y.c)
})
test('make not specified properties optional', () => {
type Foo = {
a: number,
b: number,
c: number,
}
// tslint:disable-next-line: deprecation
const y: PartialExcept<Foo, 'a'> = {} as any
assertType.noUndefined(y.a)
y.b = undefined
y.c = undefined
})
test('make not specified properties optional', () => {
type Foo = {
a: number,
b: number,
c: number,
}
const y: PartialOmit<Foo, 'a'> = {} as any
assertType.noUndefined(y.a)
y.b = undefined
y.c = undefined
})
|
a36d2cc6f85de1af670de8ed643767526ed9e935
|
TypeScript
|
jrod-disco/gamejam-ld48
|
/src/screens/controller.ts
| 3.484375
| 3
|
type ScreenName = string;
//export type Name = string;
export type Screen = { name: ScreenName; ref: any };
export type SetScreenProps = {
name: string;
isAnimated: boolean;
onComplete?: () => void;
};
export interface SceenController {
setCurrentScreen: (props: SetScreenProps) => ScreenName;
getCurrentScreen: () => Screen;
addScreenToList: (name: ScreenName, ref: any) => void;
onViewScreen: (name: ScreenName) => void;
onBackFromScreen: (name: ScreenName) => void;
}
interface Props {
pos?: { x: number; y: number };
initialScreen?: ScreenName;
}
/**
* A very basic controller for screen layouts
*
* @returns Interface object containing methods that can be called on this module
*/
export const screenController = ({
initialScreen = '',
}: Props): SceenController => {
// Screen State
const screenState = {
list: {},
currentScreen: initialScreen,
prevScreen: initialScreen,
};
/**
* Set the current screen.
* Tracks screen state and triggers visibility changes on the affected layouts
*
* @returns the name of the previous screen
*/
const setCurrentScreen = (props: SetScreenProps): ScreenName => {
const { name, isAnimated } = props;
const onComplete = props.onComplete;
screenState.prevScreen = screenState.currentScreen;
screenState.currentScreen = name;
console.log(
`screen transition from ${screenState.prevScreen || 'BOOT'} to ${name}`
);
screenState.list[name]?.setVisibility({
isVisible: true,
isAnimated: true,
onCompleteCallback: () => {
// callback for when screen fade on is complete
onComplete && onComplete();
},
});
screenState.list[screenState.prevScreen]?.setVisibility({
isVisible: false,
isAnimated: true,
});
return screenState.prevScreen;
};
const getScreen = (screen: ScreenName): Screen => {
return { name: screen, ref: screenState.list[screen] };
};
/**
*
* @returns the name of the current screen
*/
const getCurrentScreen = (): Screen => getScreen(screenState.currentScreen);
/**
* Adds a screen to the list of screens maintained by the controller.
* This list is keyed on the screen name string which is used in other operations.
*
* @param name - a name to refer to this screen by
* @param ref - the actual screen object instance
*/
const addScreenToList = (name: ScreenName, ref: any): void => {
if (screenState.list[name]) {
console.warn(
`Duplicate screen attempt. ${name} already exists.`,
screenState.list[name]
);
} else {
screenState.list[name] = ref;
}
};
/**
* Called by any button which switches screens
* @example onViewScreen('mainMenu');
*
*/
const onViewScreen = (name: ScreenName): void => {
console.log('view screen', screenState);
setCurrentScreen({ name, isAnimated: true });
//
// fade out welcome text
screenState.list[screenState.prevScreen].setVisibility({
isVisible: false,
isAnimated: true,
});
// fade in help
screenState.list[name].setVisibility({
isVisible: true,
isAnimated: true,
});
};
/**
* Called by back button
* Usage: `onBackFromScreen(screenState.currentScreen);`
*
*/
const onBackFromScreen = (screen: string): void => {
setCurrentScreen(screenState.list[screenState.prevScreen]);
//
// fade in current screen
screenState.list[screen].setVisibility({
isVisible: true,
isAnimated: true,
});
// fade out previous screen
screenState.list[screenState.prevScreen].setVisibility({
isVisible: false,
isAnimated: true,
});
};
return {
setCurrentScreen,
getCurrentScreen,
addScreenToList,
onViewScreen,
onBackFromScreen,
};
};
|
d9891045b33e1c1418c1a8acb86ee9daa298bf6a
|
TypeScript
|
benwinding/react-admin-firebase
|
/tests/reference-document-parser.spec.ts
| 2.640625
| 3
|
import {
applyRefDocs,
RefDocFound,
REF_INDENTIFIER,
translateDocFromFirestore,
translateDocToFirestore,
} from '../src/misc';
import { FireStoreDocumentRef } from '../src/misc/firebase-models';
describe('reference-document-parser.spec', () => {
test('test translateDocToFirestore', () => {
const dataToCreate = {
name: 'Some guy',
items: [
{
user: 'dan',
friend: 'ref',
___REF_FULLPATH_friend: 'my/ref',
},
],
};
const result = translateDocToFirestore(dataToCreate);
expect(result.refdocs.length).toBe(1);
expect(result.refdocs[0].fieldDotsPath).toBe(
'items.0.___REF_FULLPATH_friend'
);
expect(result.refdocs[0].refPath).toBe('my/ref');
});
test('test translateDocFromFirestore', () => {
const refDocPath = 'fake/doc/path';
const dataFromDb = {
myrefdoc: makeFakeRefDoc(refDocPath),
};
const result = translateDocFromFirestore(dataFromDb);
expect(result.refdocs.length).toBe(1);
expect(result.refdocs[0].fieldPath).toBe('myrefdoc');
expect(result.refdocs[0].refDocPath).toBe(refDocPath);
});
describe('applyRefDocs', () => {
test('keeps existing fields', () => {
const doc = {
somefield: 'okay',
};
const result = applyRefDocs(doc, [makeRefDocFound('doc1', 'my/doc')]);
expect(result.somefield).toBe('okay');
});
test('adds refdoc field', () => {
const doc = {
somefield: 'okay',
};
const result = applyRefDocs(doc, [makeRefDocFound('doc1', 'my/doc')]);
expect(result[REF_INDENTIFIER + 'doc1']).toBe('my/doc');
});
});
});
function makeRefDocFound(fieldPath: string, refDocPath: string): RefDocFound {
return {
fieldPath,
refDocPath,
};
}
function makeFakeRefDoc(docPath: string): FireStoreDocumentRef {
return {
id: docPath.split('/').pop(),
firestore: {} as any,
parent: {} as any,
path: docPath,
} as any as FireStoreDocumentRef;
}
|