repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
jmfirth/design-test-harness
src/components/harness.ts
<reponame>jmfirth/design-test-harness import { createSubscriber } from '@jmfirth/lit-html-redux' import { TemplateResult, directive } from 'lit-html' import { html } from 'lit-html/lib/lit-extended' import { bindActionCreators } from 'redux' import { grid, horizontalRuler, information } from '.' import { Config, Grid } from '../config' import { harnessActions, State } from '../store' export const harness = createSubscriber( (state: State) => ({ config: state.settings.config, visible: state.harness.visible }), dispatch => ({ actions: bindActionCreators(harnessActions, dispatch) }) )(({ config, visible, actions }) => { return html` <div className=${['harness', !visible ? 'harness--hidden' : undefined] .filter(Boolean) .join(' ')}> <style type="text/css"> .harness { position: fixed; top: 0; bottom: 0; left: 0; right: 0; pointer-events: none; z-index: 99999999; } .harness--hidden { display: none; } </style> ${/*${information(config)}*/ ''} ${Config.is(config) && Grid.is(config.grid) && grid(config.breakpoints, config.grid)} ${horizontalRuler()} </div> ` })
jmfirth/design-test-harness
src/store.ts
<gh_stars>0 import * as t from 'io-ts' import * as redux from 'redux' import { Config } from './config' /* Harness */ export const HarnessState = t.interface({ visible: t.boolean }) export type HarnessState = t.TypeOf<typeof HarnessState> export const initialHarnessState: HarnessState = { visible: false } export const TOGGLE_VISIBILITY = 'Harness/TOGGLE_VISIBILITY' export const ToggleVisibilityAction = t.interface({ type: t.literal(TOGGLE_VISIBILITY) }) export interface ToggleVisibilityAction extends t.TypeOf<typeof ToggleVisibilityAction> {} export const harnessActions = { toggleVisibility: () => ({ type: TOGGLE_VISIBILITY } as ToggleVisibilityAction) } export const harnessReducer: redux.Reducer<HarnessState> = ( state: HarnessState = initialHarnessState, action: redux.AnyAction ) => { if (ToggleVisibilityAction.is(action)) { return { ...state, visible: !state.visible } } return state } /* Settings */ export const SettingsState = t.interface({ config: t.union([Config, t.undefined]) }) export interface SettingsState extends t.TypeOf<typeof SettingsState> {} export const initialSettingsState: SettingsState = { config: undefined } export const settingsActions = { setConfig(config: Config) { if (!Config.is(config)) { throw new Error('Invalid configuration object') } return { type: SET_CONFIG, config } } } const SET_CONFIG = 'Settings/SET_CONFIG' const SetConfigAction = t.interface({ type: t.literal(SET_CONFIG), config: Config }) interface SetConfigAction extends t.TypeOf<typeof SetConfigAction> {} const settingsReducer: redux.Reducer<SettingsState> = ( state: SettingsState = initialSettingsState, action: redux.AnyAction ) => { if (SetConfigAction.is(action)) { return { ...state, config: action.config } } return state } /* Root */ export interface State { harness: HarnessState settings: SettingsState } export const initialState: State = { harness: initialHarnessState, settings: initialSettingsState } export const rootReducer = redux.combineReducers<State>({ harness: harnessReducer, settings: settingsReducer }) declare global { interface Window { __REDUX_DEVTOOLS_EXTENSION__?: () => redux.GenericStoreEnhancer } } export function createStore() { return redux.createStore<State>( rootReducer, initialState, window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__() : undefined ) }
jmfirth/design-test-harness
src/shims.d.ts
<gh_stars>0 declare module 'hex-rgb' { type Vector4<T> = [T, T, T, T] interface RGBA { red: number green: number blue: number alpha: number } interface FormatTypeMap { array: Vector4<number> } type FormatTypes = keyof FormatTypeMap | undefined export interface Options<F extends FormatTypes = undefined> { format?: F } type ReturnTypeMap<F extends FormatTypes> = F extends keyof FormatTypeMap ? FormatTypeMap[F] : RGBA export default function hexRgb(hex: string): RGBA export default function hexRgb<F extends FormatTypes>( hex: string, options: Options<F> ): ReturnTypeMap<F> }
jmfirth/design-test-harness
src/colors.ts
<reponame>jmfirth/design-test-harness export const carnation = '#ff555f'
jmfirth/design-test-harness
webpack.config.ts
import * as webpack from 'webpack'; const config: webpack.Configuration = { mode: 'production', entry: './src/design-test-harness.ts', output: { path: __dirname + '/dist', filename: 'design-test-harness.min.js' }, resolve: { extensions: ['.js', '.ts'] }, module: { rules: [ { test: /.ts$/, use: [{ loader: 'ts-loader' }] } ] } } module.exports = config;
jmfirth/design-test-harness
src/components/index.ts
export * from './grid' export * from './harness' export * from './horizontal-ruler' export * from './information'
jmfirth/design-test-harness
src/design-test-harness.ts
<filename>src/design-test-harness.ts import { render } from 'lit-html' import { createPublisher } from '@jmfirth/lit-html-redux' import { harness } from './components/harness' import { Config } from './config' import { createStore, harnessActions, settingsActions } from './store' const store = createStore() function createContainer(): HTMLDivElement { const container = document.createElement('div') container.className = 'harness' document.body.appendChild(container) return container } function createTestHarness(config: Config): void { const container = createContainer() store.dispatch(settingsActions.setConfig(config)) const provider = createPublisher( publisher => render(publisher.publish(harness), container), store ) provider.mount() let clickTimer: number | null = null document.body.addEventListener('mousedown', (event: Event) => { if (clickTimer === null) { clickTimer = window.setTimeout(() => { clickTimer = null }, 500) } else { window.clearTimeout(clickTimer) clickTimer = null store.dispatch(harnessActions.toggleVisibility()) } }) } declare global { interface Window { testHarness(config?: Config): void } } window.testHarness = createTestHarness
jmfirth/design-test-harness
src/components/horizontal-ruler.ts
import { TemplateResult } from 'lit-html' import { html } from 'lit-html/lib/lit-extended' import * as colors from '../colors' import { rgba } from '../common' export const horizontalRuler = () => html` <style type="text/css"> .harness-horizontal-ruler { position: absolute; top: 0; bottom: 0; left: 0; right: 0; } .harness-horizontal-ruler__rule { height: 10vh; border-bottom: 1px solid ${rgba(colors.carnation, 0.5)}; } .harness-horizontal-ruler__rule:nth-child(odd) { border-bottom: 1px solid ${rgba(colors.carnation, 0.25)}; } </style> <div class="harness-horizontal-ruler"> <div class="harness-horizontal-ruler__rule"></div> <div class="harness-horizontal-ruler__rule"></div> <div class="harness-horizontal-ruler__rule"></div> <div class="harness-horizontal-ruler__rule"></div> <div class="harness-horizontal-ruler__rule"></div> <div class="harness-horizontal-ruler__rule"></div> <div class="harness-horizontal-ruler__rule"></div> <div class="harness-horizontal-ruler__rule"></div> <div class="harness-horizontal-ruler__rule"></div> </div> `
jmfirth/design-test-harness
src/common.ts
<reponame>jmfirth/design-test-harness import hexRgb from 'hex-rgb' export const rgba = (hex: string, alpha: number) => `rgba(${hexRgb(hex, { format: 'array' }) .slice(0, 3) .join(', ')}, ${alpha})`
jmfirth/design-test-harness
src/components/information.ts
import { TemplateResult } from 'lit-html' import { html } from 'lit-html/lib/lit-extended' import { Config } from '../config' export const information = (config: Config) => { const gridColumn = 1 const verticalPosition = 30 return html` <div class="harness-information"> <div class="harness-information__grid-column"> ${gridColumn} </div> <div class="harness-information__vertical-position"> ${verticalPosition} </div> </div> ` }
sportsreport2/nodeless-trakt-ts
index.d.ts
<reponame>sportsreport2/nodeless-trakt-ts<gh_stars>0 export type Status = | "ended" | "returning series" | "canceled" | "in production"; export type Type = "movie" | "show" | "episode" | "person" | "list"; export type ExtendedType = | "full" | "noseasons" | "episodes" | "full,episodes" | "metadata"; export type ListPrivacy = "private" | "friends" | "public"; export type IdType = "trakt" | "imdb" | "tmdb" | "tvdb" | "tvrage"; export type Hdr = "dolby_vision" | "hdr10" | "hdr10_plus" | "hlg"; export type MediaType = | "digital" | "bluray" | "hddvd" | "dvd" | "vcd" | "vhs" | "betamax" | "laserdisc"; export type ProgressLastActivity = "collected" | "watched"; export type SortHow = "asc" | "desc"; export type RatingsFilter = | "" | "/1" | "/2" | "/3" | "/4" | "/5" | "/6" | "/7" | "/8" | "/9" | "/10"; export type AudioChannels = | "1.0" | "2.0" | "2.1" | "3.0" | "3.1" | "4.0" | "4.1" | "5.0" | "5.1" | "5.1.2" | "5.1.4" | "6.1" | "7.1" | "7.1.2" | "7.1.4" | "9.1" | "10.1"; export type HistoryType = "movies" | "shows" | "seasons" | "episodes"; export type CommentSortBy = | "newest" | "oldest" | "likes" | "replies" | "highest" | "lowest" | "plays"; export type ListSortBy = | "popular" | "likes" | "comments" | "items" | "added" | "updated"; export type SortBy = | "rank" | "added" | "title" | "released" | "runtime" | "popularity" | "percentage" | "votes" | "my_rating" | "random"; export type Audio = | "lpcm" | "mp3" | "mp2" | "aac" | "ogg" | "ogg_opus" | "wma" | "flac" | "dts" | "dts_ma" | "dts_hr" | "dts_x" | "auro_3d" | "dolby_digital" | "dolby_digital_plus" | "dolby_digital_plus_atmos" | "dolby_atmos" | "dolby_truehd" | "dolby_prologic"; export type Resolution = | "uhd_4k" | "hd_1080p" | "hd_1080i" | "hd_720p" | "sd_480p" | "sd_480i" | "sd_576p" | "sd_576i"; export type Rating = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10; export type ListType = | "all" | "personal" | "official" | "watchlists" | "recommendations"; export type CommentType = "all" | "reviews" | "shouts"; export type PeriodType = "daily" | "weekly" | "monthly" | "yearly" | "all"; type SearchIdType = "trakt" | "imdb" | "tmdb" | "tvdb"; export interface PlaybackResponse extends GenericProgress { id?: number; paused_at?: string; type?: string; action?: string; sharing?: ShareSettings; } export interface DeviceCode { device_code?: string; user_code?: string; verification_url?: string; expires_in?: number; interval?: number; } export interface SyncShow { ids?: ShowIds; seasons?: SyncSeason[]; collected_at?: string; watched_at?: string; rated_at?: string; rating?: Rating; } export interface BaseEntity { title?: string; overview?: string; rating?: number; votes?: number; updated_at?: string; available_translations?: string[]; } export interface Friend { friends_at?: string; user?: User; } export interface Connections { facebook?: boolean; twitter?: boolean; tumblr?: boolean; } export interface EpisodeCheckinResponse extends BaseCheckinResponse { episode?: Episode; show?: Show; } export interface Account { timezone?: string; cover_image?: string; } export interface ListItemRank { rank?: number[]; } export interface TrendingMovie extends BaseTrendingEntity { movie?: Movie; } export interface SyncEpisode { season?: number; number?: number; ids?: EpisodeIds; collected_at?: string; watched_at?: string; rated_at?: string; rating?: Rating; media_type?: MediaType; resolution?: Resolution; hdr?: Hdr; audio?: Audio; audio_channels?: AudioChannels; "3d"?: boolean; } export interface CastMember { character?: string; movie?: Movie; show?: Show; person?: Person; } export interface ShareSettings { facebook?: boolean; twitter?: boolean; tumblr?: boolean; } export interface CalendarMovieEntry { released?: string; movie?: Movie; } export interface TraktError { message?: string; } export interface BaseIds { trakt?: number; imdb?: string; tmdb?: number; } export interface Person { name?: string; ids?: PersonIds; biography?: string; birthday?: string; death?: string; birthplace?: string; homepage?: string; } export interface SyncResponse { added?: SyncStats; existing?: SyncStats; deleted?: SyncStats; not_found?: SyncErrors; } export interface RatedShow extends BaseRatedEntity { show?: Show; } export interface LastActivities { all?: string; movies?: LastActivityMore; episodes?: LastActivityMore; shows?: LastActivity; seasons?: LastActivity; lists?: ListsLastActivity; } export interface LastActivity { rated_at?: string; watchlisted_at?: string; commented_at?: string; } export interface MovieTranslation extends Translation { tagline?: string; } export interface CheckinError { expires_at?: string; } export interface BaseShow { show?: Show; seasons?: BaseSeason[]; last_collected_at?: string; listed_at?: string; plays?: number; last_watched_at?: string; last_updated_at?: string; reset_at?: string; aired?: number; completed?: number; hidden_seasons?: Season[]; next_episode?: Episode; last_episode?: Episode; } export interface Show extends BaseEntity { year?: number; ids?: ShowIds; first_aired?: string; airs?: Airs; runtime?: number; certification?: string; network?: string; country?: string; trailer?: string; homepage?: string; status?: Status; language?: string; genres?: string[]; } export interface Genre { name?: string; slug?: string; } export interface SyncItems { movies?: SyncMovie[]; shows?: SyncShow[]; episodes?: SyncEpisode[]; people?: SyncPerson[]; ids?: number[]; } export interface Followed { approved_at?: string; user?: User; } export interface AccessTokenRefreshRequest { grant_type?: string; refresh_token?: string; client_id?: string; client_secret?: string; redirect_uri?: string; } export interface Follower { followed_at?: string; user?: User; } export interface ListIds { trakt?: number; slug?: string; } export interface SyncErrors { movies?: SyncMovie[]; shows?: SyncShow[]; seasons?: SyncSeason[]; episodes?: SyncEpisode[]; people?: SyncPerson[]; ids?: number[]; } export interface Crew { writing?: CrewMember[]; production?: CrewMember[]; directing?: CrewMember[]; "costume & make-up"?: CrewMember[]; art?: CrewMember[]; sound?: CrewMember[]; camera?: CrewMember[]; } export interface BaseTrendingEntity { watchers?: number; } export interface TrendingShow extends BaseTrendingEntity { show?: Show; } export interface ListsLastActivity { liked_at?: string; updated_at?: string; commented_at?: string; } export interface SyncSeason { number?: number; episodes?: SyncEpisode[]; collected_at?: string; watched_at?: string; rated_at?: string; rating?: Rating; } export interface SearchResult { type?: string; score?: number; movie?: Movie; show?: Show; episode?: Episode; person?: Person; list?: TraktList; } export interface TraktList { ids?: ListIds; name?: string; description?: string; privacy?: ListPrivacy; display_numbers?: boolean; allow_comments?: boolean; sort_by?: SortBy; sort_how?: SortHow; created_at?: string; updated_at?: string; item_count?: number; comment_count?: number; likes?: number; user?: User; } export interface TraktTrendingList { like_count: number; comment_count: number; list: TraktList; } export interface RatedSeason extends RatedShow { season?: Season; } export interface SyncPerson { ids?: PersonIds; name?: string; } export interface SyncStats { movies?: number; shows?: number; seasons?: number; episodes?: number; people?: number; } export interface TraktOAuthError { error?: string; error_description?: string; } export interface SyncMovie { ids?: MovieIds; collected_at?: string; watched_at?: string; rated_at?: string; rating?: Rating; media_type?: MediaType; resolution?: Resolution; hdr?: Hdr; audio?: Audio; audio_channels?: AudioChannels; "3d"?: boolean; } export interface Episode extends BaseEntity { season?: number; number?: number; ids?: EpisodeIds; number_abs?: number; first_aired?: string; comment_count?: number; runtime?: number; } export interface Settings { user?: User; account?: Account; connections?: Connections; sharing_text?: SharingText; } export interface Translation { language?: string; title?: string; overview?: string; } export interface ListReorderResponse { updated?: number; skipped_ids?: number[]; } export interface ScrobbleProgress extends GenericProgress { app_version?: string; app_date?: string; } export interface DeviceCodeAccessTokenRequest { code?: string; client_id?: string; client_secret?: string; } export interface PersonIds extends BaseIds { slug?: string; tvrage?: string; } export interface EpisodeCheckin extends BaseCheckin { show?: Show; episode?: SyncEpisode; } export interface Builder { show?: Show; episode?: SyncEpisode; sharing?: ShareSettings; message?: string; venue_id?: string; venue_name?: string; app_version?: string; app_date?: string; } export interface Ratings { rating?: number; votes?: number; distribution?: { [key: string]: number; }; } export interface CrewMember { job?: string; movie?: Movie; show?: Show; person?: Person; } export interface WatchlistedSeason { listed_at?: string; season?: Season; show?: Show; } export interface MovieIds extends BaseIds { slug?: string; } export interface MovieCheckin extends BaseCheckin { movie?: SyncMovie; } export interface Builder { movie?: SyncMovie; sharing?: ShareSettings; message?: string; venue_id?: string; venue_name?: string; app_version?: string; app_date?: string; } export interface Season { number?: number; ids?: SeasonIds; title?: string; overview?: string; network?: string; first_aired?: string; rating?: number; votes?: number; episode_count?: number; aired_episodes?: number; episodes?: Episode[]; } export interface LastActivityMore extends LastActivity { watched_at?: string; collected_at?: string; paused_at?: string; hidden_at?: string; } export interface Credits { cast?: CastMember[]; crew?: Crew; } export interface BaseCheckin { sharing?: ShareSettings; message?: string; venue_id?: string; venue_name?: string; app_version?: string; app_date?: string; } export interface ClientId { client_id?: string; } export interface BaseMovie { movie?: Movie; collected_at?: string; last_watched_at?: string; last_updated_at?: string; listed_at?: string; plays?: number; metadata?: Metadata; } export interface Comment { id?: number; parent_id?: number; created_at?: string; updated_at?: string; comment?: string; spoiler?: boolean; review?: boolean; replies?: number; likes?: number; user_rating?: number; user?: User; movie?: Movie; show?: Show; episode?: Episode; } export interface CommentListItem { type?: Type; movie?: Movie; show?: Show; season?: Season; episode?: Episode; list?: any; comment?: Comment; } export interface RatedMovie extends BaseRatedEntity { movie?: Movie; } export interface ListEntry { id?: number; rank?: number; listed_at?: string; type?: string; movie?: Movie; show?: Show; episode?: Episode; person?: Person; } export interface Movie extends BaseEntity { year?: number; ids?: MovieIds; certification?: string; tagline?: string; released?: string; runtime?: number; trailer?: string; homepage?: string; language?: string; genres?: string[]; } export interface Images { avatar?: ImageSizes; } export interface ImageSizes { full?: string; } export interface EpisodeIds extends BaseIds { tvdb?: number; tvrage?: number; } export interface Stats { watchers?: number; plays?: number; collectors?: number; comments?: number; lists?: number; votes?: number; collected_episodes?: number; } export interface MovieCheckinResponse extends BaseCheckinResponse { movie?: Movie; } export interface BaseEpisode { number?: number; collected_at?: string; plays?: number; last_watched_at?: string; completed?: boolean; metadata?: Metadata; } export interface UserSlug { ME?: UserSlug; userSlug?: string; } export interface BaseCheckinResponse { watched_at?: string; sharing?: ShareSettings; } export interface Metadata { media_type?: MediaType; resolution?: Resolution; hdr?: Hdr; audio?: Audio; audio_channels?: AudioChannels; "3d"?: boolean; } export interface BaseSeason { number?: number; episodes?: BaseEpisode[]; aired?: number; completed?: number; } export interface Airs { day?: string; time?: string; timezone?: string; } export interface RatedEpisode extends RatedShow { episode?: Episode; } export interface HistoryEntry { id?: number; watched_at?: string; action?: string; type?: string; episode?: Episode; show?: Show; movie?: Movie; } export interface AccessToken { access_token?: string; token_type?: string; expires_in?: number; refresh_token?: string; scope?: string; created_at?: number; } export interface User { username?: string; private?: boolean; name?: string; vip?: boolean; vip_ep?: boolean; ids?: UserIds; joined_at?: string; location?: string; about?: string; gender?: string; age?: number; images?: Images; } export interface UserIds { slug?: string; } export interface WatchlistedEpisode { listed_at?: string; episode?: Episode; show?: Show; } export interface AccessTokenRequest { grant_type?: string; code?: string; client_id?: string; client_secret?: string; redirect_uri?: string; } export interface SharingText { watching?: string; watched?: string; } export interface SeasonIds { tvdb?: number; tmdb?: number; trakt?: number; tvrage?: number; } export interface ShowIds extends BaseIds { slug?: string; tvdb?: number; tvrage?: number; } export interface GenericProgress { episode?: SyncEpisode; show?: SyncShow; movie?: SyncMovie; progress?: number; } export interface BaseRatedEntity { rated_at?: string; rating?: Rating; } export interface CalendarShowEntry { first_aired?: string; episode?: Episode; show?: Show; } export interface TraktSettings { client_id: string; client_secret: string; redirect_uri?: string; debug?: boolean; endpoint?: string; } export interface Sharing { twitter?: boolean; tumblr?: boolean; } export interface Extended { extended?: ExtendedType; } export interface Calendars extends Extended { start_date: string; days: string; } export interface CheckinBody { movie?: Movie; episode?: Episode; sharing?: Sharing; message?: string; venue_id?: string; venue_name?: string; app_version?: string; app_date?: string; } export interface ScrobbleBody { movie?: Movie; episode?: Episode; progress?: number; app_version?: string; app_date?: string; } export interface CommentBody extends Comment { movie?: Movie; show?: Show; season?: Season; episode?: Episode; list?: any; } export interface CommentQuery { comment_type?: CommentType; type?: "all" | "movies" | "shows" | "seasons" | "episodes" | "lists"; include_replies?: boolean; } export interface TypeQuery { type?: ListType; } export interface Id { id: string | number; } export interface PaginationQuery { page?: number | string; limit?: number | string; pagination?: boolean; } export interface PeriodQuery { period?: PeriodType; } export interface CommentSortQuery { sort?: CommentSortBy; } export interface ListSortQuery { sort?: ListSortBy; } export interface MovieQuery { type: "movie"; fields?: | "title" | "tagline" | "overview" | "people" | "translations" | "aliases"; } export interface ShowQuery { type: "show"; query: string years?: number fields?: "title" | "overview" | "people" | "translations" | "aliases"; } export interface EpisodeSearchQuery { type: "episode"; fields?: "title" | "overview"; } export interface PersonQuery { type: "person"; fields?: "name" | "biography"; } export interface ListQuery { type: "list"; fields?: "name" | "description"; } export interface SearchIdQuery { id_type: SearchIdType; type?: ListType; } export interface SeasonQuery { id: number season: number | string; } export interface EpisodeQuery { episode: number | string; } export interface Country { name: string; code: string; } export interface Language { name: string; code: string; } export interface PlayedMovie { watcher_count: number; play_count: number; collected_count: number; movie: Movie; } export interface AnticipatedMovie { list_count: number; movie: Movie; } export interface BoxOfficeMovie { revenue: number; movie: Movie; } export interface UpdatedMovie { updated_at: number; movie: Movie; } export interface Alias { title: string; country: string; } export interface PlayedShow { watcher_count: number; play_count: number; collector_count: number; collected_count: number; show: Show; } export interface AnticipatedShow { list_count: number; show: Show; } export interface BoxOfficeShow { revenue: number; show: Show; } export interface UpdatedShow { updated_at: number; show: Show; } export declare class Trakt { constructor(settings: TraktSettings, debug?: boolean); request: { calendars: { my: { shows(params?: Calendars): Object; new_shows(params?: Calendars): Object; premieres_shows(params?: Calendars): Object; movies(params?: Calendars): Object; dvd(params?: Calendars): Object; }; all: { shows(params?: Calendars): Object; new_shows(params?: Calendars): Object; premieres_shows(params?: Calendars): Object; movies(params?: Calendars): Object; dvd(params?: Calendars): Object; }; }; checkin: { add( params: CheckinBody ): Object; delete(): Object; }; certifications(params: { type: string }): Promise<any>; comments: { comment: { add(params: CommentBody): Object; get(params: Id): Object; update(params: Id & Comment): Object; remove(params: Id): Object; }; replies: { add(params: Id & Comment): Object; get(params: Id & PaginationQuery): Object; update(params: Id & Comment): Object; remove(params: Id): Object; }; item( params: Id & Extended ): Object; likes( params: Id & PaginationQuery ): Object; like: { add(params: Id): Object; remove(params: Id): Object; }; trending( params?: CommentQuery & Extended & PaginationQuery ): Object; recent( params?: CommentQuery & Extended & PaginationQuery ): Object; updates( params?: CommentQuery & Extended & PaginationQuery ): Object; }; countries(params: { type: "movies" | "shows" }): Object; genres(params: { type: "movies" | "shows" }): Object; languages(params: { type: "movies" | "shows" }): Object; lists: { trending(params?: PaginationQuery): Object; popular(params?: PaginationQuery): Object; }; movies: { trending(params?: PaginationQuery & Extended): Object; popular(params?: PaginationQuery & Extended): Object; played( params?: PeriodQuery & PaginationQuery & Extended ): Object; watched( params?: PeriodQuery & PaginationQuery & Extended ): Object; collected( params?: PeriodQuery & PaginationQuery & Extended ): Object; anticipated( params?: PaginationQuery & Extended ): Object; boxoffice(params?: Extended): Object; updates( params?: { start_date?: string } & PaginationQuery & Extended ): Object; summary(params: Id & Extended): Object; aliases(params: Id): Object; releases(params: Id & { country?: string }): Object; translations( params: Id & { language?: string } ): Object; comments( params: Id & CommentSortQuery & PaginationQuery ): Object; lists(params: Id & TypeQuery & ListSortQuery): Object; people(params: Id & Extended): Object; ratings(params: Id): Object; related(params: Id & Extended & PaginationQuery): Object; stats(params: Id): Object; watching(params: Id & Extended): Object; }; networks(): Object; people: { summary(params: Id & Extended): Object; shows(params: Id & Extended): Object; movies(params: Id & Extended): Object; lists(params: Id & TypeQuery & ListSortQuery): Object; }; recommendations: { movies: { get( params: Extended & { limit?: number | string; ignore_collected?: boolean; } ): Object; hide(params: Id): Object; }; shows: { get( params: Extended & { limit?: number | string; ignore_collected?: boolean; } ): Object; hide(params: Id): Object; }; }; scrobble: { start(params: ScrobbleBody): Object; pause(params: ScrobbleBody): Object; stop(params: ScrobbleBody): Object; }; search: { text( params: ( | MovieQuery | ShowQuery | EpisodeSearchQuery | PersonQuery | ListQuery ) & PaginationQuery & Extended ): Object; id( params: SearchIdQuery & PaginationQuery & Extended ): Object; }; shows: { trending(params?: PaginationQuery & Extended): Object; popular(params?: PaginationQuery & Extended): Object; played( params?: PeriodQuery & PaginationQuery & Extended ): Object; watched( params?: PeriodQuery & PaginationQuery & Extended ): Object; collected( params?: PeriodQuery & PaginationQuery & Extended ): Object; anticipated( params?: PaginationQuery & Extended ): Object; updates( params?: { start_date?: string } & PaginationQuery & Extended ): Object; summary(params: Id & Extended): Object; aliases(params: Id): Object; translations(params: Id & { language?: string }): Object; comments( params: Id & CommentSortQuery & PaginationQuery ): Object; lists(params: Id & TypeQuery & ListSortQuery): Object; progress: { collection: any; watched: any; }; people(params: Id & Extended): Object; ratings(params: Id): Object; related(params: Id & Extended & PaginationQuery): Object; stats(params: Id): Object; watching(params: Id & Extended): Object; next_episode(params: Id & Extended): Object; last_episode(params: Id & Extended): Object; }; seasons: { summary(params: Id & Extended): Object; season( params?: Id & SeasonQuery & Extended & { translations?: string } ): Object; comments( params: Id & SeasonQuery & CommentSortQuery & PaginationQuery ): Object; lists( params: Id & SeasonQuery & TypeQuery & ListSortQuery & PaginationQuery ): Object; people(params: Id & SeasonQuery & Extended): Object; ratings(params: Id & SeasonQuery): Object; watching(params: Id & SeasonQuery & Extended): Object; }; episodes: { summary( params: Id & SeasonQuery & EpisodeQuery & Extended ): Object; translations( params: Id & SeasonQuery & EpisodeQuery & { language?: string } ): Object; comments( params: Id & SeasonQuery & EpisodeQuery & CommentSortQuery & PaginationQuery ): Object; lists( params: Id & SeasonQuery & EpisodeQuery & TypeQuery & ListSortQuery & PaginationQuery ): Object; people( params: Id & SeasonQuery & EpisodeQuery & { extended?: "guest_stars" } ): Object; ratings(params: Id & SeasonQuery & EpisodeQuery): Object; stats(params: Id & SeasonQuery & EpisodeQuery): Object; watching( params: Id & SeasonQuery & EpisodeQuery & Extended ): Object; }; } calendars: { my: { shows(params?: Calendars): Promise<CalendarShowEntry[]>; new_shows(params?: Calendars): Promise<CalendarShowEntry[]>; premieres_shows(params?: Calendars): Promise<CalendarShowEntry[]>; movies(params?: Calendars): Promise<CalendarMovieEntry[]>; dvd(params?: Calendars): Promise<CalendarMovieEntry[]>; }; all: { shows(params?: Calendars): Promise<CalendarShowEntry[]>; new_shows(params?: Calendars): Promise<CalendarShowEntry[]>; premieres_shows(params?: Calendars): Promise<CalendarShowEntry[]>; movies(params?: Calendars): Promise<CalendarMovieEntry[]>; dvd(params?: Calendars): Promise<CalendarMovieEntry[]>; }; }; checkin: { add( params: CheckinBody ): Promise<MovieCheckinResponse | EpisodeCheckinResponse>; delete(): Promise<void>; }; certifications(params: { type: string }): Promise<any>; comments: { comment: { add(params: CommentBody): Promise<Comment>; get(params: Id): Promise<Comment>; update(params: Id & Comment): Promise<Comment>; remove(params: Id): Promise<void>; }; replies: { add(params: Id & Comment): Promise<Comment>; get(params: Id & PaginationQuery): Promise<Comment[]>; update(params: Id & Comment): Promise<Comment>; remove(params: Id): Promise<void>; }; item( params: Id & Extended ): Promise<Movie | Season | Show | TraktList | Person>; likes( params: Id & PaginationQuery ): Promise<{ liked_at: string; user: User }[]>; like: { add(params: Id): Promise<void>; remove(params: Id): Promise<void>; }; trending( params?: CommentQuery & Extended & PaginationQuery ): Promise<CommentListItem[]>; recent( params?: CommentQuery & Extended & PaginationQuery ): Promise<CommentListItem[]>; updates( params?: CommentQuery & Extended & PaginationQuery ): Promise<CommentListItem[]>; }; countries(params: { type: "movies" | "shows" }): Promise<Country[]>; genres(params: { type: "movies" | "shows" }): Promise<Genre[]>; languages(params: { type: "movies" | "shows" }): Promise<Language[]>; lists: { trending(params?: PaginationQuery): Promise<TraktTrendingList[]>; popular(params?: PaginationQuery): Promise<TraktTrendingList[]>; }; movies: { trending(params?: PaginationQuery & Extended): Promise<TrendingMovie[]>; popular(params?: PaginationQuery & Extended): Promise<Movie[]>; played( params?: PeriodQuery & PaginationQuery & Extended ): Promise<PlayedMovie[]>; watched( params?: PeriodQuery & PaginationQuery & Extended ): Promise<PlayedMovie[]>; collected( params?: PeriodQuery & PaginationQuery & Extended ): Promise<PlayedMovie[]>; anticipated( params?: PaginationQuery & Extended ): Promise<AnticipatedMovie[]>; boxoffice(params?: Extended): Promise<BoxOfficeMovie[]>; updates( params?: { start_date?: string } & PaginationQuery & Extended ): Promise<UpdatedMovie[]>; summary(params: Id & Extended): Promise<Movie>; aliases(params: Id): Promise<Alias[]>; releases(params: Id & { country?: string }): Promise<any>; translations( params: Id & { language?: string } ): Promise<MovieTranslation[]>; comments( params: Id & CommentSortQuery & PaginationQuery ): Promise<Comment[]>; lists(params: Id & TypeQuery & ListSortQuery): Promise<TraktList[]>; people(params: Id & Extended): Promise<Credits>; ratings(params: Id): Promise<Ratings>; related(params: Id & Extended & PaginationQuery): Promise<Movie[]>; stats(params: Id): Promise<Stats>; watching(params: Id & Extended): Promise<User[]>; }; networks(): Promise<{ name: string }[]>; people: { summary(params: Id & Extended): Promise<Person>; shows(params: Id & Extended): Promise<Credits>; movies(params: Id & Extended): Promise<Credits>; lists(params: Id & TypeQuery & ListSortQuery): Promise<TraktList[]>; }; recommendations: { movies: { get( params: Extended & { limit?: number | string; ignore_collected?: boolean; } ): Promise<Movie[]>; hide(params: Id): Promise<void>; }; shows: { get( params: Extended & { limit?: number | string; ignore_collected?: boolean; } ): Promise<Show[]>; hide(params: Id): Promise<void>; }; }; scrobble: { start(params: ScrobbleBody): Promise<PlaybackResponse>; pause(params: ScrobbleBody): Promise<PlaybackResponse>; stop(params: ScrobbleBody): Promise<PlaybackResponse>; }; search: { text( params: ( | MovieQuery | ShowQuery | EpisodeSearchQuery | PersonQuery | ListQuery ) & PaginationQuery & Extended ): Promise<SearchResult[]>; id( params: SearchIdQuery & PaginationQuery & Extended ): Promise<SearchResult[]>; }; shows: { trending(params?: PaginationQuery & Extended): Promise<TrendingShow[]>; popular(params?: PaginationQuery & Extended): Promise<Show[]>; played( params?: PeriodQuery & PaginationQuery & Extended ): Promise<PlayedShow[]>; watched( params?: PeriodQuery & PaginationQuery & Extended ): Promise<PlayedShow[]>; collected( params?: PeriodQuery & PaginationQuery & Extended ): Promise<PlayedShow[]>; anticipated( params?: PaginationQuery & Extended ): Promise<AnticipatedShow[]>; updates( params?: { start_date?: string } & PaginationQuery & Extended ): Promise<UpdatedShow[]>; summary(params: Id & Extended): Promise<Show>; aliases(params: Id): Promise<Alias[]>; translations(params: Id & { language?: string }): Promise<Translation[]>; comments( params: Id & CommentSortQuery & PaginationQuery ): Promise<Comment[]>; lists(params: Id & TypeQuery & ListSortQuery): Promise<TraktList[]>; progress: { collection: any; watched: any; }; people(params: Id & Extended): Promise<Credits>; ratings(params: Id): Promise<Ratings>; related(params: Id & Extended & PaginationQuery): Promise<Show[]>; stats(params: Id): Promise<Stats>; watching(params: Id & Extended): Promise<User[]>; next_episode(params: Id & Extended): Promise<Show>; last_episode(params: Id & Extended): Promise<Show>; }; seasons: { summary(params: Id & Extended): Promise<Season[]>; season( params?: Id & SeasonQuery & Extended & { translations?: string } ): Promise<Episode[]>; comments( params: Id & SeasonQuery & CommentSortQuery & PaginationQuery ): Promise<Comment[]>; lists( params: Id & SeasonQuery & TypeQuery & ListSortQuery & PaginationQuery ): Promise<TraktList[]>; people(params: Id & SeasonQuery & Extended): Promise<Credits>; ratings(params: Id & SeasonQuery): Promise<Ratings>; watching(params: Id & SeasonQuery & Extended): Promise<User[]>; }; episodes: { summary( params: Id & SeasonQuery & EpisodeQuery & Extended ): Promise<Episode>; translations( params: Id & SeasonQuery & EpisodeQuery & { language?: string } ): Promise<Translation[]>; comments( params: Id & SeasonQuery & EpisodeQuery & CommentSortQuery & PaginationQuery ): Promise<Comment[]>; lists( params: Id & SeasonQuery & EpisodeQuery & TypeQuery & ListSortQuery & PaginationQuery ): Promise<TraktList[]>; people( params: Id & SeasonQuery & EpisodeQuery & { extended?: "guest_stars" } ): Promise<Credits>; ratings(params: Id & SeasonQuery & EpisodeQuery): Promise<Ratings>; stats(params: Id & SeasonQuery & EpisodeQuery): Promise<Stats>; watching( params: Id & SeasonQuery & EpisodeQuery & Extended ): Promise<User[]>; }; sync: any; users: any; get_url(): string; exchange_code(code: string, state?: string): Promise<AccessToken>; get_codes(): Promise<DeviceCode>; poll_access(poll: DeviceCode): Promise<any>; refresh_token(): Promise<AccessToken>; import_token(token: AccessToken): Promise<AccessToken>; export_token(): { access_token: string; expires: number; refresh_token: string; }; }
sportsreport2/nodeless-trakt-ts
tests/index.test.ts
import { Trakt } from '../index'; import { expect } from 'chai'; describe('nodeless-trakt-ts', function () { it('movies.trending', async function () { const trakt = new Trakt({ client_id: "Your Trakt Client Id", client_secret: "Your Trakt Secret Id", }); const movies = await trakt.movies.trending({ page: 1, limit: 10}); expect(movies.length).equal(10, 'movie length not correct'); const keys = ['movie', 'watchers']; for (const m in movies[0]) { expect(keys.includes(m)).to.equal(true, `${m} not in interface TrendingMovie`); } }); });
forgleaner/eslint-config
test/tsx.ts
<reponame>forgleaner/eslint-config /** * tsx */ import { Component, Inject, Prop, Provide } from 'vue-property-decorator'; const str = "dasdasd what's insdas"; const str2 = `dasdasd what's insdas`; interface ITest { das: string; dd: number; } function buzz() { return 0; } const x = 1; const y = 2; const foregroundColor = 'transparent'; const highlightColor = 'lime'; const font = 'Arial'; /* Multiline C-style Comment */ const myLink = { img: 'btn.gif' }; const local = true; const initial = -1; const foo = { numbers: ['one', 'two', 'three', 'four', 'five', 'six'], data: { a: { id: 123, type: 'String', isAvailable: true }, b: { id: 456, type: 'Int' } }, // fBar : function (x,y); fOne: function (a, b, c, d, e, f, g, h) { const x = a + b + c + d + e + f + g + h; }, chainedCallSample: function (a, b, c, d, e, f) {}, callArgumentsSample: function () { this.fTwo('one', 'two', 'three', 'four'); this.fThree( { strA: 'a', strB: 'b', strC: 'c', strD: 'd' }, 'strE' ); [1, 2, 3].reduce(function (previousValue, currentValue) { return previousValue + currentValue; }, 10); }, /** * Function JSDoc. Long lines can be wrapped with 'Comments'/'Wrap at right margin' option * @param {string} a Parameter A description. * @param {string} b Parameter B description. Can extend beyond the right margin. */ fTwo: function (a, b, c, d) { return c; if (a == 'one' && (b == 'two' || c == 'three')) { return a + b + c + d; } if (a == 'one') { return 1; } else if (a == 'two') { return 2; } let number = -10; while (x < 0) { number = number + 1; } do { number = number + 1; } while (number < 10); return d; }, fThree: function ({ strA, strB, strC, strD }, strE) { const number = prompt('Enter a number:', '0'); switch (number) { case '0': alert('Zero'); break; case '1': alert('One'); break; } try { const s = 10; } catch (e) { alert('Failure: ' + e.message); } return strA + strB + strC + strD + strE; } };
cosine99/mattermost-webapp
components/common/show_below_reply.tsx
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import React from 'react'; import {Tooltip} from 'react-bootstrap'; import {FormattedMessage} from 'react-intl'; import {localizeMessage} from 'utils/utils.jsx'; import OverlayTrigger from 'components/overlay_trigger'; import ReplyIcon from 'components/widgets/icons/reply_icon'; import RecentDate from 'components/recent_date' import LocalDateTime from 'components/local_date_time'; type Props = { location: 'CENTER' | 'SEARCH'; handleCommentClick: React.EventHandler<React.MouseEvent>; searchStyle: string; commentCount: number; postId?: string; extraClass: string; lastReplyCreatedAt: number; } export default class ShowBelowReply extends React.PureComponent<Props> { public static defaultProps: Partial<Props> = { location: 'CENTER', searchStyle: '', commentCount: 0, extraClass: '', } public render(): JSX.Element { let commentCountSpan: JSX.Element | null = null; let iconStyle = 'post-menu__item post-menu__item--wide post-menu__item--comment'; let reply = 'reply'; if (this.props.commentCount > 1) { reply = 'replies'; } const dateString = ( <RecentDate value={this.props.lastReplyCreatedAt} weekday='short' month='short' day='2-digit' year='numeric' /> ); const localDateTime = ( <LocalDateTime eventTime={this.props.lastReplyCreatedAt} /> ); if (this.props.commentCount > 0) { iconStyle += ' post-menu__item--show'; commentCountSpan = ( <span className='post-menu__comment-count' style={{color: '#2389d7'}} > {`${this.props.commentCount} ${reply}`} </span> ); } else if (this.props.searchStyle !== '') { iconStyle = iconStyle + ' ' + this.props.searchStyle; } const tooltip = ( <Tooltip id='comment-icon-tooltip' className='hidden-xs' > <FormattedMessage id='post_info.comment_icon.tooltip.reply' defaultMessage='Reply' /> </Tooltip> ); return ( <OverlayTrigger delayShow={500} placement='top' overlay={tooltip} > <button id={`${this.props.location}_commentIcon_${this.props.postId}`} aria-label={localizeMessage('post_info.comment_icon.tooltip.reply', 'Reply').toLowerCase()} className={iconStyle + ' ' + this.props.extraClass} onClick={this.props.handleCommentClick} > <span className='align-items-center post-menu__comment-show-below-last-reply-at' > <ReplyIcon className='icon icon--small'/> {commentCountSpan} <span className='post-menu__comment-show-below-last-reply-at-text'>{'Last reply at:'}</span> <span className='post-menu__comment-show-below-last-reply-date'>{dateString}</span> <span className='post-menu__comment-show-below-last-reply-time'>{localDateTime}</span> </span> </button> </OverlayTrigger> ); } }
stepanLav/node_transaction_generator
src/case/CreateCustomToken.ts
<gh_stars>0 import { api } from "@sora-substrate/util"; import { AssetList } from "../database"; import { createKeyringThroughPair, makestring } from "../utils/usefullFunctions"; import { BaseConnection } from "../database/BaseConnection"; import { PolkaswapUser } from "../database/entity/PolkaswapUser"; import { LoadUser } from "../userInteraction/LoadUser"; class CreateCustomToken { public async execute(loadUser: LoadUser): Promise<void> { const database = BaseConnection.getInstance() return new Promise(async (finish, _reject) => { const totalSupply = '1000000000000000000000' console.time('Create token processing') while (loadUser.iterations > 0) { await createToken(99) console.timeLog('Create token processing', `iteration ${loadUser.iterations} was completed`) loadUser.iterations-=1 } console.log('finish') finish() async function createToken(amountOfTokens: number) { const userRepo = database.connection.getRepository(PolkaswapUser) const manager = database.connection.manager const customAssetArray: AssetList[] = [] const users = await userRepo .createQueryBuilder("user") .leftJoinAndSelect("user.balances", "balances") .leftJoinAndSelect("balances.asset", "asset_list") .where("user.has_custom_token = false") .limit(amountOfTokens) .getMany(); let buildExtr = users.map(user => { let symbol = makestring((Math.floor(Math.random() * 7) + 1), true) let tokenName = makestring((Math.floor(Math.random() * 33) + 1)) const seed = Uint8Array.from(user.private_key) const public_key = Uint8Array.from(user.public_key) let keyring = createKeyringThroughPair('ed25519', public_key, seed ) let customAsset = new AssetList() customAsset.token_owner = user.address customAsset.name = tokenName customAsset.symbol = symbol customAsset.is_pool_token = false customAssetArray.push(customAsset) user.has_custom_token = true let extr = api.api.tx.assets.register(symbol, tokenName, totalSupply, true) return api.submitExtrinsic(extr, keyring) }) await Promise.all(buildExtr) await new Promise((r) => setTimeout(r, 6000)) const tokenList = (await (api.api.rpc as any).assets.listAssetInfos()).toJSON() tokenList.forEach((token: { obj: object; }) => { customAssetArray.forEach(element => { if(element.name == (token as any).name){ if(element.symbol == (token as any).symbol){ element.token_address = (token as any).asset_id } } }); }); await manager.insert(AssetList, customAssetArray) let updateUser = users.map(update => { delete update.balances return manager.update(PolkaswapUser, update.user_id, update) }) await Promise.all(updateUser); } }) } } export default new CreateCustomToken()
stepanLav/node_transaction_generator
src/database/entity/Balances.ts
<filename>src/database/entity/Balances.ts import { Entity, Column, CreateDateColumn, PrimaryGeneratedColumn, ManyToOne, Index } from "typeorm"; import { PolkaswapUser } from "./PolkaswapUser"; import { AssetList } from "./AssetList"; @Entity() export class Balances { @Index() @PrimaryGeneratedColumn({type: "int"}) id: number; @Column({type: "text"}) balance: string; @CreateDateColumn() created_date: Date; @Index() @ManyToOne(() => PolkaswapUser, user => user.balances) user: PolkaswapUser; @Index() @ManyToOne(() => AssetList, token => token.asset_id) asset: AssetList; }
stepanLav/node_transaction_generator
src/database/BaseConnection.ts
import "reflect-metadata"; import { Connection, createConnection } from "typeorm"; export class BaseConnection { public connection: Connection private constructor() { } private static instance: BaseConnection; public static getInstance(): BaseConnection { if (!BaseConnection.instance) { BaseConnection.instance = new BaseConnection(); } return BaseConnection.instance; } public async createCon() { this.connection = await createConnection() } }
stepanLav/node_transaction_generator
src/case/CheckBalance.ts
<reponame>stepanLav/node_transaction_generator import { KnownAssets, KnownSymbols } from "@sora-substrate/util"; import { BaseConnection } from "../database/BaseConnection"; import { PolkaswapUser, Balances } from "../database"; import { LoadUser } from "../userInteraction/LoadUser"; import { In } from "typeorm"; class CheckBalance { public async execute(loadUser: LoadUser): Promise<void> { const database = BaseConnection.getInstance() return new Promise(async (finish, _reject) => { while (loadUser.iterations > 0) { await checkBalance() loadUser.iterations-=1 } async function checkBalance() { const dbConnection = database.connection const asset = KnownAssets.get(KnownSymbols.XOR) let users = await dbConnection.getRepository(PolkaswapUser) .createQueryBuilder("user") .leftJoinAndSelect("user.balances", "balances") .leftJoinAndSelect("balances.asset", "asset_list") .where("user.has_money = true") .limit(1000) .getMany(); let currentBalance = users.map(user => { return (loadUser.api.api.rpc as any).assets.freeBalance(user.address, asset.address) }) await Promise.all(currentBalance).then(values => { for (let i=0; i<values.length; i++) { const convertedValue = values[i].unwrap().balance.toString() const tokenBalance = users[i].balances.find(i => i.asset.token_address == asset.address) tokenBalance.balance = convertedValue if (convertedValue == 0){ users[i].has_money = false } } }) await dbConnection.manager.save(users) } console.log('finish') finish() }) } } export default new CheckBalance()
stepanLav/node_transaction_generator
src/database/index.ts
export * from './entity/AssetList' export * from './entity/Balances' export * from './entity/PolkaswapUser'
stepanLav/node_transaction_generator
src/database/entity/PolkaswapUser.ts
import { Entity, Column, CreateDateColumn, PrimaryGeneratedColumn, BeforeInsert, OneToMany, Index } from "typeorm"; import { Balances } from "./Balances"; @Entity() export class PolkaswapUser { @PrimaryGeneratedColumn({ type: "int" }) user_id: number; @Column({ type: "text" }) address: string; @Column({ type: "bytea", nullable: false }) public_key: Buffer; @Column({ type: "bytea", nullable: false }) private_key: Buffer; @Index() @Column({ type: "bool" }) has_money: boolean; @Index() @Column({ type: "bool" }) has_liquidity: boolean; @Index() @Column({ type: "bool" }) has_custom_token: boolean; @CreateDateColumn() created_date: Date; @OneToMany(() => Balances, balances => balances.user, { cascade: true, onUpdate: 'CASCADE' }) balances: Balances[]; db_user: Uint8Array; @BeforeInsert() beforeInsertActions() { this.has_money = false this.has_liquidity = false this.has_custom_token = false } }
stepanLav/node_transaction_generator
src/case/MintXorToUsers.ts
import { KnownAssets, KnownSymbols } from "@sora-substrate/util"; import { BaseConnection } from "../database/BaseConnection"; import { PolkaswapUser } from "../database/entity/PolkaswapUser"; import { LoadUser } from "../userInteraction/LoadUser"; import { createArrayOfTransactions, createKeyringFromMnemonic } from '../utils/usefullFunctions' import { AssetList, Balances } from "../database"; class MintXorToUsers { public async execute(loadUser: LoadUser): Promise<void> { const database = BaseConnection.getInstance() return new Promise(async (finish, _reject) => { const asset = KnownAssets.get(KnownSymbols.XOR) const amount = "100000000000000000000" console.time('Mint token processing') while (loadUser.iterations > 0) { loadUser.iterations-=1 await mintAssetToDBUser() console.timeLog('Mint token processing', `Was completed iteration ${loadUser.iterations}`) } console.log('finish') finish() async function mintAssetToDBUser() { const userRepo = database.connection.getRepository(PolkaswapUser) const users = await userRepo .createQueryBuilder("user") .leftJoinAndSelect("user.balances", "balances") .leftJoinAndSelect("balances.asset", "asset_list") .where("user.has_money = false") .limit(1000) .getMany(); const mnemonic = 'era actor pluck voice frost club gallery palm moment empower whale flame' const sudo = createKeyringFromMnemonic('sr25519', mnemonic) const faucetTxArray = createArrayOfTransactions( users, loadUser.api.api.tx.faucet.transfer, loadUser.api.api.tx.utility.batch, asset.address, 'address', amount ) for (let sendBatch of faucetTxArray) { await loadUser.api.submitExtrinsic(sendBatch, sudo) } const manager = database.connection.manager let assetElement = new AssetList() assetElement.is_pool_token = false assetElement.name = asset.name assetElement.symbol = asset.symbol assetElement.token_address = asset.address assetElement.token_owner = (await loadUser.api.api.query.assets.assetOwners(asset.address)).toString() await manager.save(assetElement) let balances: any[] = [] for (let user of users){ const balance = new Balances(); balance.balance = amount; balance.asset = assetElement; balance.user = user user.has_money = true; balances.push(balance); } let promises = users.map(update => { delete update.balances return manager.update(PolkaswapUser, update.user_id, update) }) await Promise.all(promises); await manager.insert(Balances, balances); } }) } } export default new MintXorToUsers()
stepanLav/node_transaction_generator
src/database/entity/AssetList.ts
<reponame>stepanLav/node_transaction_generator<filename>src/database/entity/AssetList.ts import { Entity, Column, CreateDateColumn, PrimaryColumn, UpdateDateColumn, OneToMany } from "typeorm"; import { Balances } from "./Balances"; @Entity() export class AssetList { @PrimaryColumn({type: "text"}) token_address: string; @Column({type: "text"}) symbol: string; @Column({type: "text"}) name: string; @Column({type: "text"}) token_owner: string; @Column({type: "bool"}) is_pool_token: boolean; @CreateDateColumn() created_date: Date; @OneToMany(() => Balances, balances => balances.user) asset_id: Balances[]; }
stepanLav/node_transaction_generator
src/case/CreateUsers.ts
<filename>src/case/CreateUsers.ts import { BaseConnection } from "../database/BaseConnection"; import { PolkaswapUser } from "../database/entity/PolkaswapUser"; import { LoadUser } from "../userInteraction/LoadUser"; import { encodeAddress } from '@polkadot/keyring' import { mnemonicGenerate, naclKeypairFromSeed, mnemonicToMiniSecret } from '@polkadot/util-crypto' class CreateUsers { public async execute(user: LoadUser): Promise<void> { const database = BaseConnection.getInstance() const crypto = require('get-random-values') return new Promise(async (finish, _reject) => { const userRepository = database.connection.getRepository(PolkaswapUser) console.time('User generation') while (user.iterations > 0) { const generatedByIteration = 1000 const users = await createUser(generatedByIteration) await userRepository.save(users) console.timeLog('User generation', `Was completed iteration ${user.iterations}\n${generatedByIteration} users was generated!`) user.iterations -= 1 } async function createUser(numberOfUsers: number): Promise<PolkaswapUser[]> { let users: PolkaswapUser[] = [] let promises = [] async function createU(): Promise<PolkaswapUser> { return new Promise<PolkaswapUser>(async (resolve) => { const db_user = new PolkaswapUser const array = new Uint8Array(32) crypto(array); const { publicKey, secretKey } = naclKeypairFromSeed(array) db_user.address = encodeAddress(publicKey, 69) db_user.private_key = Buffer.from(secretKey) db_user.public_key = Buffer.from(publicKey) resolve(db_user) }) } while (numberOfUsers > 0) { promises.push(createU()) numberOfUsers -= 1 } await Promise.all(promises).then(values => { for (let value of values) { users.push(value) } }) return users } await new Promise((r) => setTimeout(r, 3000)) console.log('finish') finish() }) } } export default new CreateUsers()
stepanLav/node_transaction_generator
src/utils/usefullFunctions.ts
<filename>src/utils/usefullFunctions.ts import { SubmittableExtrinsicFunction } from '@polkadot/api/promise/types'; import { KeypairType, Keypair } from '@polkadot/util-crypto/types' import { KeyringPair } from '@polkadot/keyring/types' import { Keyring } from '@polkadot/keyring' export function createArrayOfTransactions(slisedUserArray:any , extrinsic: SubmittableExtrinsicFunction, batch: any, ...params: any) { let faucetTxArray = [] let faucetTxOneBatch = [] for (let users of slisedUserArray) { params[1] = users.address const tx = extrinsic(...params) faucetTxOneBatch.push(tx) } faucetTxArray.push(batch(faucetTxOneBatch)) return faucetTxArray } export function createKeyringFromMnemonic(cryptoType: KeypairType, mnemonic: string): KeyringPair { const cast = new Keyring({ type: cryptoType }); const userName = 'test' return cast.addFromMnemonic(mnemonic, { name: userName }) } export function createKeyringThroughPair(cryptoType: KeypairType, public_key: Uint8Array, private_key: Uint8Array): KeyringPair { const cast = new Keyring({ type: cryptoType }); const keyPair = { publicKey: public_key, secretKey: private_key } as Keypair return cast.addFromPair(keyPair) } export function makestring(length: number, onlyLetters=false) { let result = ''; let characters: string characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ' if (onlyLetters) characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' const charactersLength = characters.length; for (let i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; }
stepanLav/node_transaction_generator
src/App.ts
<reponame>stepanLav/node_transaction_generator<filename>src/App.ts // import "reflect-metadata" import loadGenerator from './userInteraction/LoadUserGenerator' import scenario from './case/CreateUsers' import { LoadUser } from './userInteraction/LoadUser' import * as Parallel from 'async-parallel' import { BaseConnection } from './database/BaseConnection' import * as property from '../local.properties.json' const url = process.env.URL || property.DEV.url const userCount = 1 const userIterations = 100 class App { public async start(){ const database = BaseConnection.getInstance() await database.createCon() const users = await this.createUsers() await this.executeScenario(users) await this.close(users) } public async createUsers(): Promise<[LoadUser]>{ return await loadGenerator.generate(url, userCount, userIterations) } public async executeScenario(users: [LoadUser]){ await Parallel.each(users, async value => { await scenario.execute(value) }) } public async close(users: [LoadUser]): Promise<void>{ for (let user of users){ await user.closeConnection() console.log(`Connection from User: ${user.count} was closed`) } Promise.resolve() } } const app = new App() app.start()
stepanLav/node_transaction_generator
src/userInteraction/LoadUser.ts
<gh_stars>0 import { connection, Api } from '@sora-substrate/util' export class LoadUser { public api: Api public count: Number private connection: any constructor(public iterations: number){} public async create(url: string, created: any) { this.api = new Api() this.api.initialize() await connection.open(url) console.log(`Hey, i\'m here user, my url is: ${url}`) return created(this) } public async closeConnection(): Promise<void>{ return await this.connection.close() } }
stepanLav/node_transaction_generator
src/userInteraction/LoadUserGenerator.ts
<gh_stars>0 import { LoadUser } from './LoadUser' class LoadUserGenerator { public users: any = [] public async generate(url: string, count: number, iterations: number): Promise<[LoadUser]>{ while (count > 0) { await new Promise(async (resolve, _reject) =>{ const user = new LoadUser(iterations) user.count = count await user.create(url, resolve) }).then(user => { this.users.push(user) console.log(`User ${(user as any).count} was created`) }) count -= 1 } return this.users } } export default new LoadUserGenerator()
os33/qrcode-with-logos
types/index.d.ts
export interface Logo { src: string; logoRadius?: number; logoSize?: number; borderRadius?: number; borderColor?: string; borderSize?: number; bgColor?: string; crossOrigin?: string; } export interface NodeQrCodeOptions { margin?: number; color?: { dark?: string; light?: string; }; errorCorrectionLevel?: string; scale?: any; } export interface BaseOptions { content: string; width?: number; nodeQrCodeOptions?: NodeQrCodeOptions; logo?: Logo | string; canvas?: HTMLCanvasElement; image?: HTMLImageElement; download?: boolean | Function; downloadName?: string; } declare class IQrCodeWithLogo { constructor(option: BaseOptions) toCanvas(): Promise<any>; toImage(): Promise<any>; downloadImage(name: string): void; getCanvas(): Promise<HTMLCanvasElement> } export default IQrCodeWithLogo
os33/qrcode-with-logos
src/toImage.ts
/* * @Author: super * @Date: 2019-06-27 16:29:39 * @Last Modified by: super * @Last Modified time: 2019-06-27 16:46:46 */ import { BaseOptions } from "../types/index"; import { toCanvas } from "./toCanvas"; import { isFunction, isString } from "./utils"; import { Logo } from '../types/index' export const toImage = async function (options: BaseOptions) { const { canvas } = options if (options.logo) { if (isString(options.logo)) { options.logo = { src: options.logo } as Logo; } (options.logo as Logo).crossOrigin = "Anonymous"; } if (!this.ifCanvasDrawed) await toCanvas(options) const { image = new Image(), downloadName = "qr-code" } = options; let { download } = options; if (canvas.toDataURL()) image.src = canvas.toDataURL(); else { throw new Error('Can not get the canvas DataURL') } this.ifImageCreated = true if (download !== true && !isFunction(download)) { return; } download = download === true ? (start: Function) => start() : download; const startDownload: Function = () => { saveImage(image, downloadName); }; download && download(startDownload); return Promise.resolve(); }; export const saveImage = (image: HTMLImageElement, name: string): void => { const dataURL = image.src; const link = document.createElement("a"); link.download = name; link.href = dataURL; link.dispatchEvent(new MouseEvent("click")); };
os33/qrcode-with-logos
src/toCanvas.ts
/* * @Author: super * @Date: 2019-06-27 16:29:34 * @Last Modified by: super * @Last Modified time: 2019-06-27 16:47:22 */ import { renderQrCode } from "./draw-canvas"; import { BaseOptions } from "../types/index"; import { drawLogo } from "./draw-logo"; export const toCanvas = (options: BaseOptions): Promise<void> => { return renderQrCode(options).then(() => drawLogo(options)); };
os33/qrcode-with-logos
src/server.ts
/* * @Author: super * @Date: 2019-06-27 16:29:26 * @Last Modified by: super * @Last Modified time: 2019-07-01 15:51:26 */ import QrCodeWithLogo from "./index"; //@ts-ignore import Logo = require("./super.jpg"); let demo = new QrCodeWithLogo({ canvas: document.getElementById("canvas") as HTMLCanvasElement, content: "https://github.com/zxpsuper", width: 380, // download: true, image: document.getElementById("image") as HTMLImageElement, logo: { src: Logo } }) // demo.toCanvas() demo.toImage() demo.getCanvas().then(canvas => { console.log(canvas) canvas.toBlob(function(blob) { console.log(blob) }) })
os33/qrcode-with-logos
src/index.ts
/* * @Author: super * @Date: 2019-06-27 16:29:31 * @Last Modified by: suporka * @Last Modified time: 2020-03-04 12:24:50 */ import { toCanvas } from "./toCanvas"; import { toImage, saveImage } from "./toImage"; import { BaseOptions } from "../types/index"; const { version } = require('../package.json') class QrCodeWithLogo { static version: string = version option: BaseOptions; ifCanvasDrawed: boolean = false ifImageCreated: boolean = false private defaultOption: BaseOptions = { canvas: document.createElement("canvas"), image: new Image(), content: '' } constructor(option: BaseOptions) { this.option = Object.assign(this.defaultOption, option); } public toCanvas(): Promise<void> { return toCanvas.call(this, this.option).then(() => { this.ifCanvasDrawed = true return Promise.resolve() }) }; public toImage(): Promise<void> { return toImage.call(this, this.option); } public async downloadImage(name: string) { if (!this.ifImageCreated) await this.toImage() saveImage(this.option.image, name); } public async getCanvas(): Promise<HTMLCanvasElement> { if (!this.ifCanvasDrawed) await this.toCanvas() return this.option.canvas } } export default QrCodeWithLogo;
os33/qrcode-with-logos
src/draw-canvas.ts
/* * @Author: super * @Date: 2019-06-27 16:29:19 * @Last Modified by: super * @Last Modified time: 2019-06-27 17:40:58 */ import { BaseOptions, NodeQrCodeOptions } from "../types/index"; import { promisify } from "./utils"; // @ts-ignore // import QRCode from "qrcode" const QRCode = require("qrcode") const toCanvas = promisify(QRCode.toCanvas); export const renderQrCode = ({ canvas, content, width = 0, nodeQrCodeOptions = {} }: BaseOptions) => { // 容错率,默认对内容少的二维码采用高容错率,内容多的二维码采用低容错率 // according to the content length to choose different errorCorrectionLevel nodeQrCodeOptions.errorCorrectionLevel = nodeQrCodeOptions.errorCorrectionLevel || getErrorCorrectionLevel(content); return getOriginWidth(content, nodeQrCodeOptions).then((_width: number) => { // 得到原始比例后还原至设定值,再放大4倍以获取高清图 // Restore to the set value according to the original ratio, and then zoom in 4 times to get the HD image. nodeQrCodeOptions.scale = width === 0 ? undefined : (width / _width) * 4; // @ts-ignore return toCanvas(canvas, content, nodeQrCodeOptions); }); }; // 得到原QrCode的大小,以便缩放得到正确的QrCode大小 // Get the size of the original QrCode const getOriginWidth = ( content: string, nodeQrCodeOption: NodeQrCodeOptions ) => { const _canvas = document.createElement("canvas"); // @ts-ignore return toCanvas(_canvas, content, nodeQrCodeOption).then(() => _canvas.width); }; // 对于内容少的QrCode,增大容错率 // Increase the fault tolerance for QrCode with less content const getErrorCorrectionLevel = (content: string): string => { if (content.length > 36) { return "M"; } else if (content.length > 16) { return "Q"; } else { return "H"; } };
os33/qrcode-with-logos
src/draw-logo.ts
<reponame>os33/qrcode-with-logos /* * @Author: super * @Date: 2019-06-26 18:01:57 * @Last Modified by: suporka * @Last Modified time: 2020-03-04 12:23:09 */ import { BaseOptions } from "../types/index"; import { isString } from "./utils"; import { Logo } from '../types/index' export const drawLogo = ({ canvas, logo }: BaseOptions): Promise<void> => { if (!logo) return Promise.resolve(); if (logo === '') return Promise.resolve(); const canvasWidth = canvas.width; if (isString(logo)) { logo = { src: logo } as Logo; } const { logoSize = 0.15, borderColor = "#ffffff", bgColor = borderColor || "#ffffff", borderSize = 0.05, crossOrigin, borderRadius = 8, logoRadius = 0 } = logo as Logo; let logoSrc = typeof logo === "string" ? logo : logo.src; let logoWidth = canvasWidth * logoSize; let logoXY = (canvasWidth * (1 - logoSize)) / 2; let logoBgWidth = canvasWidth * (logoSize + borderSize); let logoBgXY = (canvasWidth * (1 - logoSize - borderSize)) / 2; const ctx = canvas.getContext("2d"); // logo 底色, draw logo background color canvasRoundRect(ctx)( logoBgXY, logoBgXY, logoBgWidth, logoBgWidth, borderRadius ); ctx.fillStyle = bgColor; ctx.fill(); // logo const image = new Image(); image.setAttribute("crossOrigin", crossOrigin || "anonymous"); image.src = logoSrc; // 使用image绘制可以避免某些跨域情况 // Use image drawing to avoid some cross-domain situations const drawLogoWithImage = (image: HTMLImageElement) => { ctx.drawImage(image, logoXY, logoXY, logoWidth, logoWidth); }; // 使用canvas绘制以获得更多的功能 // Use canvas to draw more features, such as borderRadius const drawLogoWithCanvas = (image: HTMLImageElement) => { const canvasImage = document.createElement("canvas"); canvasImage.width = logoXY + logoWidth; canvasImage.height = logoXY + logoWidth; canvasImage .getContext("2d") .drawImage(image, logoXY, logoXY, logoWidth, logoWidth); canvasRoundRect(ctx)(logoXY, logoXY, logoWidth, logoWidth, logoRadius); ctx.fillStyle = ctx.createPattern(canvasImage, "no-repeat"); ctx.fill(); }; // 将 logo绘制到 canvas上 // Draw the logo on the canvas return new Promise((resolve) => { image.onload = () => { logoRadius ? drawLogoWithCanvas(image) : drawLogoWithImage(image); resolve(); }; }); }; // draw radius const canvasRoundRect = (ctx: CanvasRenderingContext2D) => ( x: number, y: number, w: number, h: number, r: number ) => { const minSize = Math.min(w, h); if (r > minSize / 2) { r = minSize / 2; } ctx.beginPath(); ctx.moveTo(x + r, y); ctx.arcTo(x + w, y, x + w, y + h, r); ctx.arcTo(x + w, y + h, x, y + h, r); ctx.arcTo(x, y + h, x, y, r); ctx.arcTo(x, y, x + w, y, r); ctx.closePath(); return ctx; };
jasona/XtermBlazor
XtermBlazor/scripts/XtermBlazor.ts
import { Terminal, ITerminalOptions } from 'xterm' declare var DotNet: any class XtermBlazor { private readonly _ASSEMBLY_NAME = 'XtermBlazor' private readonly _terminals = new Map<string, Terminal>() registerTerminal(id: string, ref: HTMLElement, options: ITerminalOptions) { // Setup the XTerm terminal const terminal = new Terminal(options) // Create Listeners terminal.onBinary(async (data: string) => { await DotNet.invokeMethodAsync(this._ASSEMBLY_NAME, 'OnBinary', id, data) }) terminal.onCursorMove(async () => { await DotNet.invokeMethodAsync(this._ASSEMBLY_NAME, 'OnCursorMove', id) }) terminal.onData(async (data: string) => { await DotNet.invokeMethodAsync(this._ASSEMBLY_NAME, 'OnData', id, data) }) terminal.onKey(async (event: { key: string, domEvent: KeyboardEvent }) => { await DotNet.invokeMethodAsync(this._ASSEMBLY_NAME, 'OnKey', id, event) }) terminal.onLineFeed(async () => { await DotNet.invokeMethodAsync(this._ASSEMBLY_NAME, 'OnLineFeed', id) }) terminal.onScroll(async (newPosition: number) => { await DotNet.invokeMethodAsync(this._ASSEMBLY_NAME, 'OnScroll', id, newPosition) }) terminal.onSelectionChange(async () => { await DotNet.invokeMethodAsync(this._ASSEMBLY_NAME, 'OnSelectionChange', id) }) terminal.onRender(async (event: { start: number, end: number }) => { await DotNet.invokeMethodAsync(this._ASSEMBLY_NAME, 'OnRender', id, event) }) terminal.onResize(async (event: { cols: number, rows: number }) => { const newEvent = { columns: event.cols, rows: event.rows } // Change cols to columns await DotNet.invokeMethodAsync(this._ASSEMBLY_NAME, 'OnResize', id, newEvent) }) terminal.onTitleChange(async (title: string) => { await DotNet.invokeMethodAsync(this._ASSEMBLY_NAME, 'OnTitleChange', id, title) }) terminal.onBell(async () => { await DotNet.invokeMethodAsync(this._ASSEMBLY_NAME, 'OnBell', id) }) terminal.open(ref) this._terminals.set(id, terminal) } disposeTerminal(id: string) { this.getTerminal(id).dispose() this._terminals.delete(id) } // Functions getRows = (id: string) => this.getTerminal(id).rows getCols = (id: string) => this.getTerminal(id).cols blur = (id: string) => this.getTerminal(id).blur() focus = (id: string) => this.getTerminal(id).focus() resize = (id: string, columns: number, rows: number) => this.getTerminal(id).resize(columns, rows) hasSelection = (id: string) => this.getTerminal(id).hasSelection() getSelection = (id: string) => this.getTerminal(id).getSelection() getSelectionPosition = (id: string) => this.getTerminal(id).getSelectionPosition() clearSelection = (id: string) => this.getTerminal(id).clearSelection() select = (id: string, column: number, row: number, length: number) => this.getTerminal(id).select(column, row, length) selectAll = (id: string) => this.getTerminal(id).selectAll() selectLines = (id: string, start: number, end: number) => this.getTerminal(id).selectLines(start, end) scrollLines = (id: string, amount: number) => this.getTerminal(id).scrollLines(amount) scrollPages = (id: string, pageCount: number) => this.getTerminal(id).scrollPages(pageCount) scrollToTop = (id: string) => this.getTerminal(id).scrollToTop() scrollToBottom = (id: string) => this.getTerminal(id).scrollToBottom() scrollToLine = (id: string, line: number) => this.getTerminal(id).scrollToLine(line) clear = (id: string) => this.getTerminal(id).clear() write = (id: string, data: string) => this.getTerminal(id).write(data) writeln = (id: string, data: string) => this.getTerminal(id).writeln(data) paste = (id: string, data: string) => this.getTerminal(id).paste(data) refresh = (id: string, start: number, end: number) => this.getTerminal(id).refresh(start, end) reset = (id: string) => this.getTerminal(id).reset() getTerminal(id: string): Terminal { const terminal = this._terminals.get(id) if (!terminal) { throw new Error('Fail to get terminal by reference id') } return terminal } } declare global { interface Window { XtermBlazor: XtermBlazor } } window.XtermBlazor = new XtermBlazor()
practicajs/practica
src/code-templates/services/order-service/test/global-teardown.ts
<reponame>practicajs/practica import isCI from "is-ci"; import dockerCompose from "docker-compose"; import OrderRepository from "../data-access/order-repository"; module.exports = async () => { if (isCI) { // ️️️✅ Best Practice: Leave the DB up in dev environment dockerCompose.down(); } else { // ✅ Best Practice: Clean the database occasionally if (Math.ceil(Math.random() * 10) === 10) { await new OrderRepository().cleanup(); } } };
practicajs/practica
src/code-templates/libraries/message-queue-client/message-queue-client.ts
import { EventEmitter } from "events"; import { errorHandler, } from "../../libraries/error-handling/error-handling"; import { FakeMessageQueueProvider } from "./fake-message-queue-provider"; import amqplib from "amqplib"; // This is a simplistic client for a popular message queue product - RabbitMQ // It's generic in order to be used by any service in the organization class MessageQueueClient extends EventEmitter { private isReady: boolean; private messageQueueProvider: any; private connection: any; private channel: any constructor(customMessageQueueProvider?) { super(); this.isReady = false; // To facilitate testing, the client allows working with a fake MQ provider // It can get one in the constructor here or even change by environment variables if (customMessageQueueProvider) { this.messageQueueProvider = customMessageQueueProvider; } else if (process.env.MESSAGE_QUEUE_PROVIDER === "real") { this.messageQueueProvider = amqplib; } else { this.messageQueueProvider = new FakeMessageQueueProvider(); } } async connect() { const connectionProperties = { protocol: "amqp", hostname: "localhost", port: 5672, username: "rabbitmq", password: "<PASSWORD>", // This is a demo app, no security considerations. This is the password for the local dev server locale: "en_US", frameMax: 0, heartbeat: 0, vhost: "/", }; this.connection = await this.messageQueueProvider.connect( connectionProperties ); this.channel = await this.connection.createChannel(); } async close() { if (this.connection) { await this.connection.close(); } return; } async sendMessage(queueName, message) { if (!this.channel) { await this.connect(); } await this.channel.assertQueue(queueName); const sendResponse = await this.channel.sendToQueue( queueName, Buffer.from(JSON.stringify(message)) ); return sendResponse; } async consume(queueName, onMessageCallback) { if (!this.channel) { await this.connect(); } this.channel.assertQueue(queueName); await this.channel.consume(queueName, async (theNewMessage) => { //Not awaiting because some MQ client implementation get back to fetch messages again only after handling a message onMessageCallback(theNewMessage.content.toString()) .then(() => { this.channel.ack(theNewMessage); }) .catch((error) => { this.channel.nack(theNewMessage); error.isTrusted = true; //Since it's related to a single message, there is no reason to let the process crash errorHandler.handleError(error); }); }); return; } } export default MessageQueueClient;
practicajs/practica
src/code-templates/libraries/error-handling/error-handling.ts
<filename>src/code-templates/libraries/error-handling/error-handling.ts import * as logger from "../../libraries/logger/logger"; // This file simulates real-world error handler that makes this component observable const errorHandler = { handleError: async (errorToHandle) => { try { logger.error(errorToHandle); metricsExporter.fireMetric("error", { errorName: errorToHandle.name || "generic-error", }); // A common best practice is to crash when an unknown error (non-trusted) is being thrown decideWhetherToCrash(errorToHandle); } catch (e) { // Continue the code flow if failed to handle the error console.log(`handleError threw an error ${e}`); } }, }; const decideWhetherToCrash = (error) => { if (!error.isTrusted) { process.exit(); } }; class AppError extends Error { constructor(readonly name: string, readonly message: string, public readonly HTTPStatus, public readonly isTrusted = true) { super(message); } } // This simulates a typical monitoring solution that allow firing custom metrics when // like Prometheus, DataDog, CloudWatch, etc const metricsExporter = { fireMetric: async (name, labels) => { console.log("In real production code I will really fire metrics"); }, }; export { errorHandler, metricsExporter, AppError };
practicajs/practica
src/code-generator/entry-points/non-interactive-cli.tsx
import { factorDefaultOptions, } from "../generation-logic/generation-options"; import { generateApp } from "../generation-logic/generate-service"; export function handleNonInteractiveCommand(options: any) { const generationOptions = factorDefaultOptions({ installDependencies: options.installDependencies, overrideIfExists: options.overrideIfExists, targetDirectory: process.cwd(), }); generateApp(generationOptions); //TODO: Make this async, show progress bar and nice message in the end }
practicajs/practica
src/code-templates/services/order-service/test/global-setup.ts
<reponame>practicajs/practica<gh_stars>10-100 import isPortReachable from "is-port-reachable"; import path from "path"; import dockerCompose from "docker-compose"; import { execSync } from "child_process"; module.exports = async () => { console.time("global-setup"); // ️️️✅ Best Practice: Speed up during development, if already live then do nothing const isDBReachable = await isPortReachable(54310); if (!isDBReachable) { // ️️️✅ Best Practice: Start the infrastructure within a test hook - No failures occur because the DB is down await dockerCompose.upAll({ cwd: path.join(__dirname), log: true, }); await dockerCompose.exec( "database", ["sh", "-c", "until pg_isready ; do sleep 1; done"], { cwd: path.join(__dirname), } ); // ️️️✅ Best Practice: Use npm script for data seeding and migrations execSync("npm run db:migrate"); // ✅ Best Practice: Seed only metadata and not test record, read "Dealing with data" section for further information execSync("npm run db:seed"); } // 👍🏼 We're ready console.timeEnd("global-setup"); };
jeffzh4ng/Data-Structures-and-Algorithms
src/algorithms/sort/heap-sort.ts
<gh_stars>100-1000 /** * Swap elements at idx1 and idx2 in arr. * @param arr - array containing two elements to swap * @param idx1 - index of first element * @param idx2 - index of second element */ const swap = (arr: number[], idx1: number, idx2: number): void => { const temp = arr[idx2] arr[idx2] = arr[idx1] arr[idx1] = temp } /** * Heapifies the heap or sub-heap, putting the largest element at rootIdx. * @param arr - array containing numbers to heapify * @param heapSize - size of heap * @param rootIdx - root of the heap or sub-heap to heapify */ const heapify = (arr: number[], heapSize: number, rootIdx: number): void => { let maxIdx = rootIdx // assume element at rootIdx is the largest const leftChild = 2 * rootIdx + 1 const rightChild = 2 * rootIdx + 2 // if left child is larger than element at maxIdx if (leftChild < heapSize && arr[leftChild] > arr[maxIdx]) { maxIdx = leftChild } // if right child is larger than element at maxIdx if (rightChild < heapSize && arr[rightChild] > arr[maxIdx]) { maxIdx = rightChild } // if maxIdx was changed if (maxIdx != rootIdx) { swap(arr, rootIdx, maxIdx) heapify(arr, heapSize, maxIdx) // heapify the affected subtree } } /** * Sort an array of numbers in-place and in ascending order using heap sort. * * Time complexity: O(n*log(n)) * * Space complexity: O(log(n)) for recursion stack in heapify * * @param arr - array of numbers to sort */ const heapSort = (arr: number[]): void => { const heapSize = arr.length /** * Build max binary heap by rearranging array. * - We want to heapify nodes with children, which are nodes at the second to last level of the heap. * - The index of the last node on the second to last level is given by floor(heapSize/2) - 1. * - To heapify the entire array, we start at the second to last level and work upwards. */ const startIdx = Math.floor(heapSize / 2) - 1 for (let i = startIdx; i >= 0; i--) { heapify(arr, heapSize, i) } for (let i = heapSize - 1; i > 0; i--) { swap(arr, 0, i) // remove largest element from heap and put it at the back of the array heapify(arr, i, 0) // new heap contains elements from 0 to i - 1, inclusive } } export default heapSort
jeffzh4ng/Data-Structures-and-Algorithms
test/data-structures/sequences/deque.test.ts
<filename>test/data-structures/sequences/deque.test.ts import { Deque } from '../../../src/data-structures/sequences/queue' describe('Deque', () => { let deque: Deque<number> beforeEach(() => { deque = new Deque() }) describe('empty deque', () => { it('returns null when pop() is called on empty stack', () => { expect(deque.popFront()).toBe(null) expect(deque.popBack()).toBe(null) }) it('returns null when peek() is called on empty stack', () => { expect(deque.peekFront()).toBe(null) expect(deque.peekBack()).toBe(null) }) }) it('is empty', () => { expect(deque.isEmpty()).toBe(true) }) describe('enqueues', () => { it('pushes front', () => { deque.pushFront(1) expect(deque.size()).toBe(1) deque.pushFront(2) expect(deque.size()).toBe(2) deque.pushFront(3) expect(deque.size()).toBe(3) }) it('pushes back', () => { deque.pushBack(1) expect(deque.size()).toBe(1) deque.pushBack(2) expect(deque.size()).toBe(2) deque.pushBack(3) expect(deque.size()).toBe(3) }) }) describe('dequeues', () => { it('pops front', () => { deque.pushBack(1) deque.pushBack(2) deque.pushBack(3) const val1 = deque.popFront() expect(val1).toBe(1) expect(deque.size()).toBe(2) const val2 = deque.popFront() expect(val2).toBe(2) expect(deque.size()).toBe(1) const val3 = deque.popFront() expect(val3).toBe(3) expect(deque.size()).toBe(0) }) it('pops back', () => { deque.pushBack(1) deque.pushBack(2) deque.pushBack(3) const val1 = deque.popBack() expect(val1).toBe(3) expect(deque.size()).toBe(2) const val2 = deque.popBack() expect(val2).toBe(2) expect(deque.size()).toBe(1) const val3 = deque.popBack() expect(val3).toBe(1) expect(deque.size()).toBe(0) }) }) it('finds out if list contains element', () => { expect(deque.contains(1)).toBe(false) deque.pushBack(1) deque.pushBack(2) deque.pushBack(3) expect(deque.contains(1)).toBe(true) expect(deque.contains(3)).toBe(true) expect(deque.contains(8)).toBe(false) }) it('peeks', () => { deque.pushBack(1) expect(deque.peekFront()).toBe(1) expect(deque.peekBack()).toBe(1) deque.pushBack(2) expect(deque.peekFront()).toBe(1) expect(deque.peekBack()).toBe(2) }) it('clears the list', () => { deque.pushBack(1) deque.pushBack(2) deque.pushBack(3) deque.pushBack(4) deque.clear() expect(deque.isEmpty()).toBe(true) deque.pushBack(1) deque.clear() expect(deque.isEmpty()).toBe(true) deque.clear() expect(deque.isEmpty()).toBe(true) }) it('is iterable', () => { const nums = [1, 2, 3] for (const n of nums) { deque.pushBack(n) } let i = 0 for (const n of deque) { expect(n).toBe(nums[i]) i += 1 } }) }) describe('Queue - complex object', () => { class Hero { heroId: number hunger: number health: number constructor(id: number) { this.heroId = id this.hunger = 100 this.health = 100 } } const sameHeroF = (a: Hero, b: Hero) => a.heroId === b.heroId let queue: Deque<Hero> beforeAll(() => { const knight = new Hero(123) const archer = new Hero(456) const mage = new Hero(789) queue = new Deque(sameHeroF) queue.pushBack(knight) queue.pushBack(archer) queue.pushBack(mage) }) it('checks if queue contains hero', () => { const knight = new Hero(123) const mage = new Hero(789) expect(queue.contains(knight)).toBe(true) expect(queue.contains(mage)).toBe(true) expect(queue.contains(new Hero(246))).toBe(false) }) })
jeffzh4ng/Data-Structures-and-Algorithms
test/algorithms/sort/test-cases.ts
<gh_stars>100-1000 interface TestCases { [key: string]: number[] } const testCases: TestCases = { 'empty array': [], 'array of length 1': [9], 'array with an even number of elements': [7, 9, 5, 2, 1, 3], 'array with an odd number of elements': [-5, -13, -3, 0, 6, 2, 8], 'array of increasing elements': [-5, -2, 0, 2, 1, 10], 'array of decreasing elements': [121, 32, 15, 8, -1, -32], 'array with a repeating element': [1, 1, 1, 1, 1], 'array with duplicates': [-5, 5, -5, -10, 5, -5], 'array of floats': [-45.2, -3.1415, 89.0, 34.21, -12.7], } export default testCases
jeffzh4ng/Data-Structures-and-Algorithms
test/algorithms/sort/topological-sort.test.ts
<reponame>jeffzh4ng/Data-Structures-and-Algorithms import { GraphNode } from '../../../src/algorithms/graphs/graph-node' import { topologicalSortDepthFirst } from '../../../src/algorithms/sort/topological-sort-dfs' import { topologicalSortKahn } from '../../../src/algorithms/sort/topological-sort-kahn' describe('Topological Sort DFS', () => { test('Basic graph', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const graph = new Map([ [a, [b]], [b, [c]], [c, []], ]) expect(topologicalSortDepthFirst(graph)).toEqual(['a', 'b', 'c']) }) test('Graph with dependencies', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const d = new GraphNode('d') const e = new GraphNode('e') // a d // v ^ // c -- // ^ v // b e const graph = new Map([ [a, [b]], [b, [c]], [c, [d, e]], [d, []], [e, []], ]) expect(topologicalSortDepthFirst(graph)).toEqual(['a', 'b', 'c', 'e', 'd']) }) }) describe('Topological Sort DFS', () => { test('Basic graph', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const graph = new Map([ [a, [b]], [b, [c]], [c, []], ]) expect(topologicalSortDepthFirst(graph)).toEqual(['a', 'b', 'c']) }) test('Graph with dependencies', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const d = new GraphNode('d') const e = new GraphNode('e') // a d // v ^ // c -- // ^ v // b e const graph = new Map([ [a, [b]], [b, [c]], [c, [d, e]], [d, []], [e, []], ]) expect(topologicalSortDepthFirst(graph)).toEqual(['a', 'b', 'c', 'e', 'd']) }) }) describe('Topological Sort Kahn', () => { test('Basic graph', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const graph = new Map([ [a, [b]], [b, [c]], [c, []], ]) expect(topologicalSortKahn(graph)).toEqual(['a', 'b', 'c']) }) test('Graph with dependencies', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const d = new GraphNode('d') const e = new GraphNode('e') // a d // v ^ // c -- // ^ v // b e const graph = new Map([ [a, [b]], [b, [c]], [c, [d, e]], [d, []], [e, []], ]) expect(topologicalSortKahn(graph)).toEqual(['a', 'b', 'c', 'd', 'e']) }) })
jeffzh4ng/Data-Structures-and-Algorithms
test/data-structures/heaps/lazy-min-binomial-heap.test.ts
<filename>test/data-structures/heaps/lazy-min-binomial-heap.test.ts import LazyMinBinomialHeap from '../../../src/data-structures/priority-queues/mergeable-heaps/lazy-min-binomial-heap' describe('MinBinomialHeap', () => { let heap: LazyMinBinomialHeap<number> beforeEach(() => { heap = new LazyMinBinomialHeap(Number.MIN_SAFE_INTEGER) }) describe('Empty heap', () => { it('is empty', () => { expect(heap.size).toBe(0) expect(heap.isEmpty()).toBe(true) }) it('dequeue() returns null', () => { expect(heap.dequeue()).toBe(null) }) it('peek() returns null', () => { expect(heap.peek()).toBe(null) }) }) describe('Insertion and deletion', () => { it('inserts numbers properly', () => { heap.enqueue(8) expect(heap.size).toBe(1) heap.enqueue(26) expect(heap.size).toBe(2) heap.enqueue(72) expect(heap.size).toBe(3) heap.enqueue(42) }) it('deletes a specific node', () => { const node = heap.enqueue(8) heap.enqueue(3) heap.deleteNode(node) expect(heap.size).toBe(1) expect(heap.head).toBeTruthy() expect(heap.head!.value).toBe(3) }) it('deletes numbers properly', () => { heap.enqueue(8) heap.enqueue(26) heap.enqueue(72) expect(heap.size).toBe(3) heap.dequeue() expect(heap.size).toBe(2) heap.dequeue() expect(heap.size).toBe(1) heap.dequeue() expect(heap.size).toBe(0) }) }) it('maintains the heap invariant', () => { const values = [8, 32, 72, 26, 16, 48, 5, 11, 17, 93, 500, 603, 401, 325, -321] for (const v of values) { heap.enqueue(v) } const sortedValues = [...values].sort((a, b) => a - b) for (const v of sortedValues) { const node = heap.dequeue() if (!node) throw new Error() expect(node.value).toBe(v) } }) describe('Reading', () => { it('peeks', () => { heap.enqueue(-4) heap.enqueue(-5) heap.enqueue(-6) heap.enqueue(-7) heap.enqueue(-8) heap.enqueue(-9) heap.enqueue(-10) expect(heap.peek()!.value).toBe(-10) }) }) describe('Updating', () => { it('unions properly', () => { const heapA = new LazyMinBinomialHeap(Number.MIN_SAFE_INTEGER) const heapB = new LazyMinBinomialHeap(Number.MIN_SAFE_INTEGER) const valuesA = [8, 32, 72, 26, 16, 48, 5, 11] const valuesB = [17, 93, 500, 603, 401, 325, -321] for (const a of valuesA) { heapA.enqueue(a) } for (const b of valuesB) { heapB.enqueue(b) } const unionedHeap = heapA.union(heapB) expect(unionedHeap.size).toBe(heapA.size + heapB.size) const sortedValues = [...valuesA, ...valuesB].sort((a, b) => a - b) for (const v of sortedValues) { const node = unionedHeap.dequeue() if (!node) throw new Error() expect(node.value).toBe(v) } }) it('unions with empty heaps', () => { const heapA = new LazyMinBinomialHeap(Number.MIN_SAFE_INTEGER) const heapB = new LazyMinBinomialHeap(Number.MIN_SAFE_INTEGER) const valuesA = [8, 32, 72, 26, 16, 48, 5, 11] for (const a of valuesA) { heapA.enqueue(a) } const unionedHeap = heapA.union(heapB) expect(unionedHeap.size).toBe(heapA.size + heapB.size) const sortedValues = [...valuesA].sort((a, b) => a - b) for (const v of sortedValues) { const node = unionedHeap.dequeue() if (!node) throw new Error() expect(node.value).toBe(v) } }) it('decreases keys properly', () => { const values = [8, 32, 72, 26, 16, 48, 5, 11] for (const v of values) { heap.enqueue(v) } const node = heap.enqueue(100) heap.dequeue() expect(heap.decreaseKey(node, 105)).toBe(false) expect(heap.decreaseKey(node, -3)).toBe(true) }) }) })
jeffzh4ng/Data-Structures-and-Algorithms
src/algorithms/graphs/shortest-paths/dijkstras-shortest-path.ts
import { MinBinaryHeap } from '../../../data-structures/priority-queues' import { GraphNode, PrevVertices, ShortestDistances, WeightedGraph } from '../graph-node' /** * Perform Dijkstra's shortest path algorithm. * Find the shortest path between two vertices in a directed graph with positive weights. * * Time complexity: O[(V+E)logV] * Space complexity: O(V+E) * * @param {WeightedGraph<T>} graph * @param {GraphNode<T>} source * @param {GraphNode<T>} target * @return {[Array<<T>>, number]} */ export const shortestPath = <T>( graph: WeightedGraph<T>, source: GraphNode<T>, target: GraphNode<T> ): [Array<T>, number] => { const [dist, prev] = dijkstra(graph, source) const shortestPath = new Array<T>() for (let at = target; at !== null; at = prev.get(at)!) { shortestPath.push(at.val) } return [shortestPath.reverse(), dist.get(target)!] } const dijkstra = <T>( graph: WeightedGraph<T>, source: GraphNode<T> ): [ShortestDistances<T>, PrevVertices<T>] => { const visited = new Set<GraphNode<T>>() const dist: ShortestDistances<T> = new Map() const prev: PrevVertices<T> = new Map() for (const node of graph.keys()) { dist.set(node, Number.POSITIVE_INFINITY) prev.set(node, null) } dist.set(source, 0) // dist[source] needs to be 0, not infinity const pq = new MinBinaryHeap<[GraphNode<T>, number]>([], (a, b) => a[1] - b[1]) pq.add([source, 0]) while (!pq.isEmpty()) { const [u, uDist] = pq.poll()! if (!u) throw new Error('This will never happen') const uDistStale = uDist > dist.get(u)! if (uDistStale) continue visited.add(u) const neighborsOfU = graph.get(u)! for (const [v, weight] of neighborsOfU) { if (visited.has(v)) continue const altDistance = uDist + weight if (altDistance < dist.get(v)!) { dist.set(v, altDistance) prev.set(v, u) pq.add([v, altDistance]) } } } return [dist, prev] }
jeffzh4ng/Data-Structures-and-Algorithms
src/algorithms/sort/bucket-sort.ts
<filename>src/algorithms/sort/bucket-sort.ts /** * Sort an array of positive numbers in-place and in ascending order using bucket sort. * Individual buckets are sorted using the JS sort function. * @param arr - array of positive numbers to sort * @param n - number of buckets */ const bucketSortPositives = (arr: number[], n: number): void => { // create empty buckets const buckets: number[][] = [] for (let i = 0; i < n; i++) { buckets[i] = [] } // put array elements in buckets const max = Math.max(...arr) for (const num of arr) { let bucketIdx = Math.floor((n * num) / max) // determine bucket index bucketIdx = bucketIdx >= n ? n - 1 : bucketIdx // ensure bucket index is a valid array index buckets[bucketIdx].push(num) } // sort each bucket and put sorted elements into arr let arrIdx = 0 for (const bucket of buckets) { bucket.sort((a, b) => a - b) for (const element of bucket) { arr[arrIdx] = element arrIdx++ } } } /** * Sort an array of numbers in-place and in ascending order using bucket sort. * * Note that the traditional bucket sort algorithm does not work on negative numbers. * Thus, the below algorithm is modified such that any negative numbers in the array are converted * to positive numbers and sorted separately from the original positive numbers. * * Time complexity: * - O(n + k) average * - O(n^2) worst case * - where n is the number of array elements and k is the number of buckets * * Space complexity: O(n*k) * * @param arr - array of numbers to sort * @param posBuckets - (Optional) number of buckets to use when sorting positive array elements * @param negBuckets - (Optional) number of buckets to use when sorting negative array elements */ const bucketSort = (arr: number[], posBuckets = arr.length, negBuckets = arr.length): void => { if (arr.length === 0) return // raise error if number of specified buckets is 0 or less if (posBuckets <= 0 || negBuckets <= 0) { console.error('Number of buckets must be greater than zero') return } // separate positive from negative numbers const positiveNums: number[] = [] const negativeNums: number[] = [] for (const num of arr) { if (num >= 0) { positiveNums.push(num) } else { negativeNums.push(-1 * num) // convert negative numbers to positive } } // sort both arrays bucketSortPositives(positiveNums, posBuckets) bucketSortPositives(negativeNums, negBuckets) // put sorted values back into input arr let arrIdx = 0 for (let i = negativeNums.length - 1; i >= 0; i--) { arr[arrIdx] = -1 * negativeNums[i] arrIdx++ } for (let i = 0; i < positiveNums.length; i++) { arr[arrIdx] = positiveNums[i] arrIdx++ } } export default bucketSort
jeffzh4ng/Data-Structures-and-Algorithms
test/algorithms/sort/quick-sort.test.ts
<reponame>jeffzh4ng/Data-Structures-and-Algorithms<filename>test/algorithms/sort/quick-sort.test.ts import quickSort from '../../../src/algorithms/sort/quick-sort' import testCases from './test-cases' describe('quickSort', () => { for (const [description, inputArray] of Object.entries(testCases)) { it(`correctly sorts ${description}`, () => { const soln = [...inputArray] soln.sort((a, b) => a - b) // sort the copy inplace using native JS function quickSort(inputArray) //sort the original inplace using mergeSort expect(inputArray).toEqual(soln) }) } it('correctly sorts a subarray', () => { const array = [100, 39, -4, 11, 5, -87, -2, 6, 0, 7] const soln1 = [100, 39, -87, -4, -2, 0, 5, 6, 7, 11] const soln2 = [39, 100, -87, -4, -2, 0, 5, 6, 7, 11] quickSort(array, 2) expect(array).toEqual(soln1) quickSort(array, undefined, 1) expect(array).toEqual(soln2) }) describe('index error', () => { console.error = jest.fn() const array = [1, 2, 3] beforeEach(() => { jest.clearAllMocks() }) it('is raised when left or right indices are not integers', () => { quickSort(array, 0.1, 2) quickSort(array, 0, 1.1) expect(console.error).toHaveBeenCalledTimes(2) }) }) })
jeffzh4ng/Data-Structures-and-Algorithms
src/algorithms/graphs/shortest-paths/floyd-warshall-shortest-path.ts
<gh_stars>100-1000 import { GraphNode, WeightedGraph } from '../graph-node' type U = GraphNode<number> type V = GraphNode<number> type Weight = number type DP = Array<Array<number>> type Next = Array<Array<GraphNode<number> | null>> export const shortestPath = ( next: Next, source: GraphNode<number>, target: GraphNode<number> ): Array<number> => { if (next[source.val][target.val] === null) return [] const path = [] while (source !== target) { path.push(source.val) const nextNode = next[source.val][target.val] if (nextNode === null) return [] source = nextNode } path.push(source.val) // source is now target return path } export const floydWarshall = (graph: WeightedGraph<number>): [DP, Next] => { const V = graph.size const dp: Array<Array<number>> = new Array(V) .fill(0) .map(() => new Array<number>(V).fill(Infinity)) const next: Array<Array<GraphNode<number> | null>> = new Array(V) .fill(0) .map(() => new Array<GraphNode<number> | null>(V).fill(null)) // initialize dp matrix const edgeList: Array<[U, V, Weight]> = [] for (const [v, vEdges] of graph.entries()) { for (const edge of vEdges) { edgeList.push([v, edge[0], edge[1]]) } } for (const edge of edgeList) { const [u, v, weight] = edge dp[u.val][v.val] = weight next[u.val][v.val] = v } for (const v of graph.keys()) { dp[v.val][v.val] = 0 next[v.val][v.val] = v } // build the shorest distances for (let k = 0; k < dp.length; k++) { for (let i = 0; i < dp.length; i++) { for (let j = 0; j < dp.length; j++) { if (dp[i][k] + dp[k][j] < dp[i][j]) { dp[i][j] = dp[i][k] + dp[k][j] next[i][j] = next[i][k] } } } } // detect and propagate negative cycle for (let k = 0; k < dp.length; k++) { for (let i = 0; i < dp.length; i++) { for (let j = 0; j < dp.length; j++) { if (dp[i][k] + dp[k][j] < dp[i][j]) { dp[i][j] = -Infinity next[i][j] = null } } } } return [dp, next] }
jeffzh4ng/Data-Structures-and-Algorithms
src/algorithms/graphs/graph-node.ts
<reponame>jeffzh4ng/Data-Structures-and-Algorithms export class GraphNode<T> { val: T constructor(val: T) { this.val = val } } type EdgeList<T> = Map<GraphNode<T>, number> export type WeightedGraph<T> = Map<GraphNode<T>, EdgeList<T>> export type ShortestDistances<T> = Map<GraphNode<T>, number> export type PrevVertices<T> = Map<GraphNode<T>, GraphNode<T> | null>
jeffzh4ng/Data-Structures-and-Algorithms
test/algorithms/sort/counting-sort.test.ts
<reponame>jeffzh4ng/Data-Structures-and-Algorithms import countingSort from '../../../src/algorithms/sort/counting-sort' import testCases from './test-cases' describe('countingSort', () => { console.error = jest.fn() beforeEach(() => { jest.clearAllMocks() }) for (const [description, inputArray] of Object.entries(testCases)) { if (description === 'array of floats') { it(`raises error for ${description}`, () => { countingSort(inputArray) expect(console.error).toHaveBeenCalledTimes(1) }) continue } it(`correctly sorts ${description}`, () => { const soln = [...inputArray] soln.sort((a, b) => a - b) // sort the copy in-place using native JS function countingSort(inputArray) expect(inputArray).toEqual(soln) }) } })
jeffzh4ng/Data-Structures-and-Algorithms
src/algorithms/sort/quick-sort.ts
<filename>src/algorithms/sort/quick-sort.ts /** * Returns a random integer between min and max. * @param min - lower bound (returned int will be greater than or equal to min) * @param max - upper bound (returned int will be less than max) */ const getRandomInt = (min: number, max: number): number => { min = Math.ceil(min) max = Math.floor(max) return Math.floor(Math.random() * (max - min) + min) } /** * Swap elements at idx1 and idx2 in arr. * @param arr - array containing at least two elements to swap * @param idx1 - index of first element * @param idx2 - index of second element */ const swap = (arr: number[], idx1: number, idx2: number): void => { const temp = arr[idx2] arr[idx2] = arr[idx1] arr[idx1] = temp } /** * Partition subarray around a random pivot and return the final pivot position. * @param arr - array of numbers to be sorted * @param left - index of left bound of subarray * @param right - index of right bound of subarray */ const partition = (arr: number[], left: number, right: number): number => { const pivotIdx = getRandomInt(left, right + 1) // pick a random pivot const pivotVal = arr[pivotIdx] swap(arr, left, pivotIdx) // partition so that elements less than pivot value are grouped together on the left let i = left + 1 for (let j = left + 1; j <= right; j++) { if (arr[j] < pivotVal) { swap(arr, i, j) i++ } } swap(arr, left, i - 1) return i - 1 // return final position of pivot } /** * Sort an array of numbers in-place and in ascending order. * Partitioning is done by choosing a random element as the pivot. * * Time complexity: O(n*log(n)) on average, where n is the number of elements to sort * * Space complexity: O(log(n)) for recursion stack * * @param arr - array of numbers to be sorted * @param left - Optional: index of left bound * @param right - Optional: index of right bound */ const quickSort = (arr: number[], left = 0, right = arr.length - 1): void => { // check that indices are intergers if (!Number.isInteger(left) || !Number.isInteger(right)) { console.error('Index Error: Left and right indices must be integers.') return } // implement quick sort algorithm if (left >= right) return const pivot = partition(arr, left, right) quickSort(arr, left, pivot - 1) quickSort(arr, pivot + 1, right) } export default quickSort
jeffzh4ng/Data-Structures-and-Algorithms
src/algorithms/search/breadth-first-search.ts
import { Queue } from '../../data-structures/sequences/queue' import { GraphNode } from '../graphs/graph-node' /** * Perform a breadth-first search through a directed graph. * * Time complexity: O(V+E) * Space complexity: O(V) * * @param {GraphNode<T>} root * @param {Map<GraphNode<T>, Array<GraphNode<T>>} graph * @return {Array<GraphNode<T>>} */ export const bfs = <T>(root: GraphNode<T>, graph: Map<GraphNode<T>, Array<GraphNode<T>>>) => { const output: Array<T> = new Array() const q: Queue<GraphNode<T>> = new Queue() const visited = new Set<GraphNode<T>>() q.enqueue(root) visited.add(root) // loop while q is not empty while (!q.isEmpty()) { let size = q.size() // iterate for every element in the q while (size-- > 0) { const node = q.dequeue() if (!node) throw new Error('Node shouldnt be null.') output.push(node.val) if (graph.has(node)) { const children = graph.get(node) if (!children) throw new Error('Children shouldnt be null.') for (const child of children) { if (!visited.has(child)) { q.enqueue(child) visited.add(child!) } } } } } return output }
jeffzh4ng/Data-Structures-and-Algorithms
test/data-structures/trees/avl-tree.test.ts
import AVLTree from '../../../src/data-structures/trees/avl-tree' import AVLTreeNode from '../../../src/data-structures/trees/avl-tree/avl-tree-node' describe('AVL Tree', () => { let tree: AVLTree<number> beforeEach(() => { tree = new AVLTree() }) describe('Inspection', () => { it('size()', () => { expect(tree.size()).toBe(0) }) it('isEmpty()', () => { expect(tree.isEmpty()).toBe(true) tree.insert(8) expect(tree.isEmpty()).toBe(false) }) it('height()', () => { // Tree should look like: // 10 // 5 15 // 2 12 21 // No tree expect(tree.height()).toBe(0) // Layer One tree.insert(10) expect(tree.height()).toBe(1) // Layer Two tree.insert(5) expect(tree.height()).toBe(2) tree.insert(15) expect(tree.height()).toBe(2) // Layer Three tree.insert(2) expect(tree.height()).toBe(3) tree.insert(7) expect(tree.height()).toBe(3) tree.insert(12) expect(tree.height()).toBe(3) tree.insert(21) expect(tree.height()).toBe(3) // Layer 4 tree.insert(1) expect(tree.height()).toBe(4) }) }) describe('Searching', () => { const treeB = new AVLTree<number>() const a = new AVLTreeNode(5, null) const b = new AVLTreeNode(4, a) const c = new AVLTreeNode(3, b) const d = new AVLTreeNode(2, c) const e = new AVLTreeNode(1, d) const f = new AVLTreeNode(6, a) const g = new AVLTreeNode(7, f) const h = new AVLTreeNode(8, g) a.left = b b.left = c c.left = d d.left = e a.right = f f.right = g g.right = h treeB.root = a it('find()', () => { expect(treeB.find(5)).toBe(a) expect(treeB.find(4)).toBe(b) expect(treeB.find(3)).toBe(c) expect(treeB.find(2)).toBe(d) expect(treeB.find(1)).toBe(e) expect(treeB.find(6)).toBe(f) expect(treeB.find(7)).toBe(g) expect(treeB.find(8)).toBe(h) }) it('findMin()', () => { expect(treeB.findMin()).toBe(e) }) it('findMax()', () => { expect(treeB.findMax()).toBe(h) }) it('findSucessor()', () => { expect(treeB.findSucessor(a)).toBe(f) expect(treeB.findSucessor(e)).toBe(d) expect(treeB.findSucessor(f)).toBe(g) const treeC = new AVLTree<number>() const m = new AVLTreeNode(5, null) const n = new AVLTreeNode(3, m) const o = new AVLTreeNode(2, n) const p = new AVLTreeNode(1, o) const q = new AVLTreeNode(4, n) m.left = n n.left = o o.left = p n.right = q treeC.root = m expect(treeC.findSucessor(q)).toBe(m) }) it('findPredecessor()', () => { expect(treeB.findPredecessor(a)).toBe(b) expect(treeB.findPredecessor(e)).toBe(null) expect(treeB.findPredecessor(f)).toBe(a) }) }) describe('Insertion/Deletion', () => { describe('rotations after insertion', () => { describe('left heavy', () => { it('left left simple case', () => { // 5 3 // 3 -> 1 5 // 1 tree.insert(5) expect(tree.height()).toBe(1) tree.insert(3) expect(tree.height()).toBe(2) tree.insert(1) expect(tree.height()).toBe(2) const three = tree.find(3) const one = tree.find(1) const five = tree.find(5) if (!three || !one || !five) throw new Error() expect(three.balanceFactor).toBe(0) expect(three.height).toBe(2) expect(one.balanceFactor).toBe(0) expect(one.height).toBe(1) expect(five.balanceFactor).toBe(0) expect(five.height).toBe(1) }) it('left left advanced case', () => { // Before: // 10 // 5 15 // 4 8 12 21 // 2 // 1 // After: // 10 // 5 15 // 2 8 12 21 // 1 4 // Layer One tree.insert(10) expect(tree.height()).toBe(1) // Layer Two tree.insert(5) tree.insert(15) expect(tree.height()).toBe(2) // Layer Three tree.insert(4) tree.insert(8) tree.insert(12) tree.insert(21) expect(tree.height()).toBe(3) // Layer 4 tree.insert(2) expect(tree.height()).toBe(4) tree.insert(1) expect(tree.height()).toBe(4) const two = tree.find(2) const one = tree.find(1) const four = tree.find(4) if (!two || !one || !four) throw new Error() expect(two.balanceFactor).toBe(0) expect(two.height).toBe(2) expect(one.balanceFactor).toBe(0) expect(one.height).toBe(1) expect(four.balanceFactor).toBe(0) expect(four.height).toBe(1) }) it('left right case', () => { // 5 5 4 // 3 -> 4 -> 3 5 // 4 3 tree.insert(5) expect(tree.height()).toBe(1) tree.insert(3) expect(tree.height()).toBe(2) tree.insert(4) expect(tree.height()).toBe(2) const four = tree.find(4) const three = tree.find(3) const five = tree.find(5) if (!three || !four || !five) throw new Error() expect(four.balanceFactor).toBe(0) expect(four.height).toBe(2) expect(three.balanceFactor).toBe(0) expect(three.height).toBe(1) expect(five.balanceFactor).toBe(0) expect(five.height).toBe(1) }) describe('right heavy', () => { it('right right case', () => { // 5 7 // 7 -> 5 8 // 8 tree.insert(5) expect(tree.height()).toBe(1) tree.insert(7) expect(tree.height()).toBe(2) tree.insert(8) expect(tree.height()).toBe(2) const seven = tree.find(7) const five = tree.find(8) const eight = tree.find(5) if (!seven || !five || !eight) throw new Error() expect(seven.balanceFactor).toBe(0) expect(seven.height).toBe(2) expect(five.balanceFactor).toBe(0) expect(five.height).toBe(1) expect(eight.balanceFactor).toBe(0) expect(eight.height).toBe(1) }) it('right left case', () => { // 5 5 6 // 7 -> 6 -> 5 7 // 6 7 tree.insert(5) expect(tree.height()).toBe(1) tree.insert(7) expect(tree.height()).toBe(2) tree.insert(6) expect(tree.height()).toBe(2) const six = tree.find(6) const five = tree.find(5) const seven = tree.find(7) if (!six || !five || !seven) throw new Error() expect(six.balanceFactor).toBe(0) expect(six.height).toBe(2) expect(five.balanceFactor).toBe(0) expect(five.height).toBe(1) expect(seven.balanceFactor).toBe(0) expect(seven.height).toBe(1) }) }) }) }) it('insert()', () => { tree.insert(5) expect(tree.size()).toBe(1) tree.insert(3) expect(tree.size()).toBe(2) tree.insert(2) expect(tree.size()).toBe(3) tree.insert(6) expect(tree.size()).toBe(4) tree.insert(9) expect(tree.size()).toBe(5) tree.insert(4) expect(tree.size()).toBe(6) }) describe('removal', () => { beforeEach(() => { // Before: // 10 // 5 15 // 4 8 12 21 // 2 // 1 // After: // 10 // 5 15 // 2 8 12 21 // 1 4 // Layer One tree.insert(10) // Layer Two tree.insert(5) tree.insert(15) // Layer Three tree.insert(4) tree.insert(8) tree.insert(12) tree.insert(21) // Layer 4 tree.insert(2) tree.insert(1) }) it('removes node with no children', () => { const four = tree.find(4) const two = tree.find(2) if (!four || !two) throw new Error() expect(two.balanceFactor).toBe(0) tree.remove(four) expect(tree.find(4)).toBe(null) expect(two.right).toBe(null) expect(two.balanceFactor).toBe(1) }) it('removes node with 1 left child', () => { const four = tree.find(4) const two = tree.find(2) if (!four || !two) throw new Error() expect(two.balanceFactor).toBe(0) tree.remove(four) expect(tree.find(4)).toBe(null) expect(two.right).toBe(null) expect(two.balanceFactor).toBe(1) // new part tree.remove(two) expect(tree.find(2)).toBe(null) const one = tree.find(1) if (!one) throw new Error() expect(one.balanceFactor).toBe(0) }) it('removes node with two children', () => { // Before: // 10 // 5 15 // 4 8 12 21 // 2 // 1 // After: // 10 // 5 15 // 2 8 12 21 // 1 4 6 // Layer One tree.insert(10) // Layer Two tree.insert(5) tree.insert(15) // Layer Three tree.insert(4) tree.insert(8) tree.insert(12) tree.insert(21) // Layer 4 tree.insert(2) tree.insert(1) tree.insert(6) const five = tree.find(5) if (!five) throw new Error() // 10 // XX 15 // 2 8 12 21 // 1 4 6 // 10 // 6 15 // 2 8 12 21 // 1 4 tree.remove(five) expect(tree.find(5)).toBe(null) const six = tree.find(6) if (!six || !six.right) throw new Error() expect(six.right.value).toBe(8) }) }) }) describe('Traversals', () => { const treeB = new AVLTree<number>() const a = new AVLTreeNode(5, null) const b = new AVLTreeNode(4, a) const c = new AVLTreeNode(3, b) const d = new AVLTreeNode(2, c) const e = new AVLTreeNode(1, d) const f = new AVLTreeNode(6, a) const g = new AVLTreeNode(7, f) const h = new AVLTreeNode(8, g) a.left = b b.left = c c.left = d d.left = e a.right = f f.right = g g.right = h treeB.root = a it('inorder()', () => { const inorderNumbers = [1, 2, 3, 4, 5, 6, 7, 8] let i = 0 for (const n of treeB.inorderTraversal()) { expect(n).toBe(inorderNumbers[i]) i += 1 } }) it('preorder()', () => { // Tree should look like: // 10 // 5 15 // 2 7 12 21 // // Layer One tree.insert(10) // Layer Two tree.insert(5) tree.insert(15) // Layer Three tree.insert(2) tree.insert(7) tree.insert(12) tree.insert(21) const preorderNumbers = [10, 5, 2, 7, 15, 12, 21] let i = 0 for (const n of tree.preorderTraversal()) { expect(n).toBe(preorderNumbers[i]) i += 1 } }) it('postorder()', () => { // Tree should look like: // 10 // 5 15 // 2 7 12 21 // Layer One tree.insert(10) // Layer Two tree.insert(5) tree.insert(15) // Layer Three tree.insert(2) tree.insert(7) tree.insert(12) tree.insert(21) const postorderNumbers = [2, 7, 5, 12, 21, 15, 10] let i = 0 for (const n of tree.postorderTraversal()) { expect(n).toBe(postorderNumbers[i]) i += 1 } }) }) })
jeffzh4ng/Data-Structures-and-Algorithms
test/data-structures/trees/b-tree.test.ts
import BTree from '../../../src/data-structures/trees/b-tree/b-tree' describe('AVL Tree', () => { let tree: BTree<number> beforeEach(() => { tree = new BTree(2) }) describe('inspection', () => { it('isEmpty()', () => { expect(tree.size()).toBe(0) expect(tree.isEmpty()).toBe(true) expect(tree.height()).toBe(0) }) }) describe('search', () => { it('find()', () => { tree.insert(10) tree.insert(5) tree.insert(2) // 2, 5, 10 if (tree.root === null) throw new Error() tree.insert(18) // 2, 5, 10 5 5 // -> 2 10 -> 2 10, 18 if (!tree.root.children) throw new Error() tree.insert(17) // 5 // 2 10, 17, 18 tree.insert(3) tree.insert(4) // 5 // 2, 3, 4 10, 17, 18 tree.insert(15) // 5 5, 17 // 2, 3, 4 10, 17, 18 --> split bc [10, 17, 18] is full --> 2, 3, 4 10, 18 // then insert 15 // 5, 17 // 2, 3, 4 10,15 18 tree.insert(12) // 5, 17 // 2, 3, 4 10,12,15 18 // 5, 17 // 2, 3, 4 10,12,15 18 tree.insert(13) // 5, 17 5, 12, 17 // 2, 3, 4 10,12,15 18 -> 2, 3, 4 10, 13,15 18 tree.insert(1) // 12 12 // 5, 12, 17 5, 17 3,5, 17 // 2 3 4 10 13,15 18 -> 2 3 4 10 13,15 18 --> 1,2 4 10 13,15 18 expect(tree.find(12)).toEqual([tree.root, 0]) expect(tree.find(5)).toEqual([tree.root.children[0], 1]) expect(tree.find(4)).toEqual([tree.root.children[0].children[1], 0]) expect(tree.find(6)).toEqual(null) }) }) describe('insertion', () => { it('insert()', () => { tree.insert(10) tree.insert(5) tree.insert(2) // 2, 5, 10 if (tree.root === null) throw new Error() expect(tree.root.values).toEqual([2, 5, 10]) tree.insert(18) // 2, 5, 10 5 5 // -> 2 10 -> 2 10, 18 expect(tree.root.values).toEqual([5]) if (!tree.root.children) throw new Error() expect(tree.root.children[0].values).toEqual([2]) expect(tree.root.children[1].values).toEqual([10, 18]) tree.insert(17) // 5 // 2 10, 17, 18 expect(tree.root.values).toEqual([5]) expect(tree.root.children[0].values).toEqual([2]) expect(tree.root.children[1].values).toEqual([10, 17, 18]) tree.insert(3) tree.insert(4) // 5 // 2, 3, 4 10, 17, 18 expect(tree.root.values).toEqual([5]) expect(tree.root.children[0].values).toEqual([2, 3, 4]) expect(tree.root.children[1].values).toEqual([10, 17, 18]) tree.insert(15) // 5 5, 17 // 2, 3, 4 10, 17, 18 --> split bc [10, 17, 18] is full --> 2, 3, 4 10, 18 // then insert 15 // 5, 17 // 2, 3, 4 10,15 18 expect(tree.root.values).toEqual([5, 17]) expect(tree.root.children[0].values).toEqual([2, 3, 4]) expect(tree.root.children[1].values).toEqual([10, 15]) expect(tree.root.children[2].values).toEqual([18]) tree.insert(12) // 5, 17 // 2, 3, 4 10,12,15 18 expect(tree.root.values).toEqual([5, 17]) expect(tree.root.children[0].values).toEqual([2, 3, 4]) expect(tree.root.children[1].values).toEqual([10, 12, 15]) expect(tree.root.children[2].values).toEqual([18]) // 5, 17 // 2, 3, 4 10,12,15 18 tree.insert(13) // 5, 17 5, 12, 17 // 2, 3, 4 10,12,15 18 -> 2, 3, 4 10, 13,15 18 expect(tree.root.values).toEqual([5, 12, 17]) expect(tree.root.children[0].values).toEqual([2, 3, 4]) expect(tree.root.children[1].values).toEqual([10]) expect(tree.root.children[2].values).toEqual([13, 15]) expect(tree.root.children[3].values).toEqual([18]) tree.insert(1) // 12 12 // 5, 12, 17 5, 17 3,5, 17 // 2 3 4 10 13,15 18 -> 2 3 4 10 13,15 18 --> 1,2 4 10 13,15 18 expect(tree.root.values).toEqual([12]) expect(tree.root.children[0].values).toEqual([3, 5]) expect(tree.root.children[1].values).toEqual([17]) expect(tree.root.children[0].children[0].values).toEqual([1, 2]) expect(tree.root.children[0].children[1].values).toEqual([4]) expect(tree.root.children[0].children[2].values).toEqual([10]) expect(tree.root.children[1].children[0].values).toEqual([13, 15]) expect(tree.root.children[1].children[1].values).toEqual([18]) }) }) describe('deletion', () => { it('remove()', () => { tree.insert(10) tree.insert(5) tree.insert(2) // 2, 5, 10 if (tree.root === null) throw new Error() tree.insert(18) // 2, 5, 10 5 5 // -> 2 10 -> 2 10, 18 if (!tree.root.children) throw new Error() tree.insert(17) // 5 // 2 10, 17, 18 tree.insert(3) tree.insert(4) // 5 // 2, 3, 4 10, 17, 18 tree.insert(15) // 5 5, 17 // 2, 3, 4 10, 17, 18 --> split bc [10, 17, 18] is full --> 2, 3, 4 10, 18 // then insert 15 // 5, 17 // 2, 3, 4 10,15 18 tree.insert(12) // 5, 17 // 2, 3, 4 10,12,15 18 // 5, 17 // 2, 3, 4 10,12,15 18 tree.insert(13) // 5, 17 5, 12, 17 // 2, 3, 4 10,12,15 18 -> 2, 3, 4 10, 13,15 18 tree.insert(1) // 12 12 // 5, 12, 17 5, 17 3,5, 17 // 2 3 4 10 13,15 18 -> 2 3 4 10 13,15 18 --> 1,2 4 10 13,15 18 tree.insert(6) tree.insert(7) expect(tree.root.children[0].children[2].values).toEqual([6, 7, 10]) // 12 // 3, 5 17 // 1,2 4 6,7,10 13,15 18 tree.remove(7) // 12 // 3--5 17 // 1,2 4 6,10 13,15 18 expect(tree.root.children[0].children[2].values).toEqual([6, 10]) }) }) })
jeffzh4ng/Data-Structures-and-Algorithms
test/algorithms/sort/bucket-sort.test.ts
<gh_stars>100-1000 import bucketSort from '../../../src/algorithms/sort/bucket-sort' import testCases from './test-cases' describe('bucketSort', () => { console.error = jest.fn() beforeEach(() => { jest.clearAllMocks() }) for (const [description, inputArray] of Object.entries(testCases)) { it(`correctly sorts ${description}`, () => { const soln = [...inputArray] soln.sort((a, b) => a - b) // sort the copy inplace using native JS function bucketSort(inputArray) //sort the original inplace using bucketSort expect(inputArray).toEqual(soln) }) } it('correctly sorts when only posBuckets is specified', () => { const array = [5, 3, 4, 1, 2] const soln = [...array].sort((a, b) => a - b) bucketSort(array, 1) expect(array).toEqual(soln) }) it('correctly sorts when only negBuckets is specified', () => { const array = [-5, -3, -4, -1, -2] const soln = [...array].sort((a, b) => a - b) bucketSort(array, undefined, 1) expect(array).toEqual(soln) }) it('correctly sorts when both posBuckets and negBuckets are specified', () => { const array = [-5, -3, 7, -4, -1, -2, 9, 0] const soln = [...array].sort((a, b) => a - b) bucketSort(array, 5, 3) expect(array).toEqual(soln) }) it('raises error when number of specified buckets <= 0', () => { const array = [1, 2, 3] bucketSort(array, 0, 1) expect(console.error).toHaveBeenCalledTimes(1) }) })
jeffzh4ng/Data-Structures-and-Algorithms
src/algorithms/sort/topological-sort-dfs.ts
import LinkedList from '../../data-structures/sequences/linked-list' import { GraphNode } from '../graphs/graph-node' /** * Perform a topological sort through a directed graph using the depth first technique. * * Time complexity: O(V+E) * Space complexity: O(V) (recursion and output) * * @param startNode - The node to begin the search at * @return {Array<GraphNode<T>>} */ export const topologicalSortDepthFirst = <T>( graph: Map<GraphNode<T>, Array<GraphNode<T>>> ): Array<T> => { const output = new LinkedList<T>() const visited = new Set<GraphNode<T>>() // for every node in the graph, perform a dfs, where the dfs adds the nodes to the output in the correct order for (const node of graph.keys()) { if (!visited.has(node)) dfs(node, graph, visited, output) } return Array.from(output) } const dfs = <T>( root: GraphNode<T>, graph: Map<GraphNode<T>, Array<GraphNode<T>>>, visited: Set<GraphNode<T>>, output: LinkedList<T> ): void => { visited.add(root) const children = graph.get(root) if (children) { for (const child of children) { dfs(child, graph, visited, output) } } output.addFront(root.val) }
jeffzh4ng/Data-Structures-and-Algorithms
test/data-structures/sequences/queue.test.ts
<gh_stars>100-1000 import { Queue } from '../../../src/data-structures/sequences/queue' describe('Queue', () => { let queue: Queue<number> beforeEach(() => { queue = new Queue() }) describe('empty queue', () => { it('returns null when pop() is called on empty stack', () => { expect(queue.dequeue()).toBe(null) }) it('returns null when peek() is called on empty stack', () => { expect(queue.peekFront()).toBe(null) expect(queue.peekBack()).toBe(null) }) }) it('is empty', () => { expect(queue.isEmpty()).toBe(true) }) it('enqueues', () => { queue.enqueue(1) expect(queue.size()).toBe(1) queue.enqueue(2) expect(queue.size()).toBe(2) queue.enqueue(3) expect(queue.size()).toBe(3) }) it('dequeues', () => { queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) const val1 = queue.dequeue() expect(val1).toBe(1) expect(queue.size()).toBe(2) const val2 = queue.dequeue() expect(val2).toBe(2) expect(queue.size()).toBe(1) const val3 = queue.dequeue() expect(val3).toBe(3) expect(queue.size()).toBe(0) }) it('finds out if list contains element', () => { expect(queue.contains(1)).toBe(false) queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) expect(queue.contains(1)).toBe(true) expect(queue.contains(3)).toBe(true) expect(queue.contains(8)).toBe(false) }) it('peeks', () => { queue.enqueue(1) expect(queue.peekFront()).toBe(1) expect(queue.peekBack()).toBe(1) queue.enqueue(2) expect(queue.peekFront()).toBe(1) expect(queue.peekBack()).toBe(2) }) it('clears the list', () => { queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) queue.enqueue(4) queue.clear() expect(queue.isEmpty()).toBe(true) queue.enqueue(1) queue.clear() expect(queue.isEmpty()).toBe(true) queue.clear() expect(queue.isEmpty()).toBe(true) }) it('is iterable', () => { const nums = [1, 2, 3] for (const n of nums) { queue.enqueue(n) } let i = 2 for (const n of queue) { expect(n).toBe(nums[i]) i -= 1 } }) }) describe('Queue - complex object', () => { class Hero { heroId: number hunger: number health: number constructor(id: number) { this.heroId = id this.hunger = 100 this.health = 100 } } const sameHeroF = (a: Hero, b: Hero) => a.heroId === b.heroId let queue: Queue<Hero> beforeAll(() => { const knight = new Hero(123) const archer = new Hero(456) const mage = new Hero(789) queue = new Queue(sameHeroF) queue.enqueue(knight) queue.enqueue(archer) queue.enqueue(mage) }) it('checks if queue contains hero', () => { const knight = new Hero(123) const mage = new Hero(789) expect(queue.contains(knight)).toBe(true) expect(queue.contains(mage)).toBe(true) expect(queue.contains(new Hero(246))).toBe(false) }) })
jeffzh4ng/Data-Structures-and-Algorithms
test/algorithms/graph/shortest-paths/floyd-warshall-shortest-path.test.ts
<gh_stars>100-1000 import { GraphNode, WeightedGraph } from '../../../../src/algorithms/graphs/graph-node' import { floydWarshall, shortestPath, } from '../../../../src/algorithms/graphs/shortest-paths/floyd-warshall-shortest-path' describe('Floyd Warshall', () => { test('Basic graph', () => { const zero = new GraphNode(0) const one = new GraphNode(1) const two = new GraphNode(2) const zerosNeighbors: Map<GraphNode<number>, number> = new Map([ [one, 5], [two, 1], ]) const onesNeighbors: Map<GraphNode<number>, number> = new Map() const twoNeighbors: Map<GraphNode<number>, number> = new Map([[one, 1]]) const graph: WeightedGraph<number> = new Map([ [zero, zerosNeighbors], [one, onesNeighbors], [two, twoNeighbors], ]) const expectedDP = [ [0, 2, 1], [Infinity, 0, Infinity], [Infinity, 1, 0], ] const [dist, _] = floydWarshall(graph) for (let i = 0; i < dist.length; i++) { for (let j = 0; j < dist.length; j++) { expect(dist[i][j]).toEqual(expectedDP[i][j]) } } }) test('Basic Graph with Cycle', () => { const zero = new GraphNode(0) const one = new GraphNode(1) const two = new GraphNode(2) const zerosNeighbors: Map<GraphNode<number>, number> = new Map([ [one, 5], [two, 1], ]) const onesNeighbors: Map<GraphNode<number>, number> = new Map([[zero, 3]]) const twosNeighbors: Map<GraphNode<number>, number> = new Map([[one, 1]]) const graph: WeightedGraph<number> = new Map([ [zero, zerosNeighbors], [one, onesNeighbors], [two, twosNeighbors], ]) const expectedDP = [ [0, 2, 1], [3, 0, 4], [4, 1, 0], ] const [dist, _] = floydWarshall(graph) for (let i = 0; i < dist.length; i++) { for (let j = 0; j < dist.length; j++) { expect(dist[i][j]).toEqual(expectedDP[i][j]) } } }) test('Basic path', () => { const zero = new GraphNode(0) const one = new GraphNode(1) const two = new GraphNode(2) const zerosNeighbors: Map<GraphNode<number>, number> = new Map([ [one, 5], [two, 1], ]) const onesNeighbors: Map<GraphNode<number>, number> = new Map() const twoNeighbors: Map<GraphNode<number>, number> = new Map([[one, 1]]) const graph: WeightedGraph<number> = new Map([ [zero, zerosNeighbors], [one, onesNeighbors], [two, twoNeighbors], ]) const [_, next] = floydWarshall(graph) expect(shortestPath(next, zero, one)).toEqual([0, 2, 1]) expect(shortestPath(next, zero, two)).toEqual([0, 2]) expect(shortestPath(next, one, zero)).toEqual([]) expect(shortestPath(next, one, two)).toEqual([]) expect(shortestPath(next, two, zero)).toEqual([]) expect(shortestPath(next, two, one)).toEqual([2, 1]) }) test('Basic path with cycle', () => { const zero = new GraphNode(0) const one = new GraphNode(1) const two = new GraphNode(2) const zerosNeighbors: Map<GraphNode<number>, number> = new Map([ [one, 5], [two, 1], ]) const onesNeighbors: Map<GraphNode<number>, number> = new Map([[zero, 3]]) const twoNeighbors: Map<GraphNode<number>, number> = new Map([[one, 1]]) const graph: WeightedGraph<number> = new Map([ [zero, zerosNeighbors], [one, onesNeighbors], [two, twoNeighbors], ]) const [_, next] = floydWarshall(graph) expect(shortestPath(next, zero, one)).toEqual([0, 2, 1]) expect(shortestPath(next, zero, two)).toEqual([0, 2]) expect(shortestPath(next, one, zero)).toEqual([1, 0]) expect(shortestPath(next, one, two)).toEqual([1, 0, 2]) expect(shortestPath(next, two, zero)).toEqual([2, 1, 0]) expect(shortestPath(next, two, one)).toEqual([2, 1]) }) })
jeffzh4ng/Data-Structures-and-Algorithms
test/data-structures/trees/binary-search-tree.test.ts
<filename>test/data-structures/trees/binary-search-tree.test.ts<gh_stars>100-1000 import BinarySearchTree from '../../../src/data-structures/trees/binary-search-tree' import TreeNode from '../../../src/data-structures/trees/binary-search-tree/tree-node' describe('Binary Search Tree', () => { let tree: BinarySearchTree<number> beforeEach(() => { tree = new BinarySearchTree() }) describe('Inspection', () => { it('size()', () => { expect(tree.size()).toBe(0) }) it('isEmpty()', () => { expect(tree.isEmpty()).toBe(true) tree.insert(8) expect(tree.isEmpty()).toBe(false) }) it('height()', () => { // Tree should look like: // 10 // 5 15 // 2 12 21 // 1 // No tree expect(tree.height()).toBe(0) // Layer One tree.insert(10) expect(tree.height()).toBe(1) // Layer Two tree.insert(5) expect(tree.height()).toBe(2) tree.insert(15) expect(tree.height()).toBe(2) // Layer Three tree.insert(2) expect(tree.height()).toBe(3) tree.insert(12) expect(tree.height()).toBe(3) tree.insert(21) expect(tree.height()).toBe(3) // Layer 4 tree.insert(1) expect(tree.height()).toBe(4) }) }) describe('Searching', () => { const treeB = new BinarySearchTree<number>() const a = new TreeNode(5, null) const b = new TreeNode(4, a) const c = new TreeNode(3, b) const d = new TreeNode(2, c) const e = new TreeNode(1, d) const f = new TreeNode(6, a) const g = new TreeNode(7, f) const h = new TreeNode(8, g) a.left = b b.left = c c.left = d d.left = e a.right = f f.right = g g.right = h treeB.root = a it('find()', () => { expect(treeB.find(5)).toBe(a) expect(treeB.find(4)).toBe(b) expect(treeB.find(3)).toBe(c) expect(treeB.find(2)).toBe(d) expect(treeB.find(1)).toBe(e) expect(treeB.find(6)).toBe(f) expect(treeB.find(7)).toBe(g) expect(treeB.find(8)).toBe(h) }) it('findMin()', () => { expect(treeB.findMin()).toBe(e) }) it('findMax()', () => { expect(treeB.findMax()).toBe(h) }) it('findSucessor()', () => { expect(treeB.findSucessor(a)).toBe(f) expect(treeB.findSucessor(e)).toBe(d) expect(treeB.findSucessor(f)).toBe(g) const treeC = new BinarySearchTree<number>() const m = new TreeNode(5, null) const n = new TreeNode(3, m) const o = new TreeNode(2, n) const p = new TreeNode(1, o) const q = new TreeNode(4, n) m.left = n n.left = o o.left = p n.right = q treeC.root = m expect(treeC.findSucessor(q)).toBe(m) }) it('findPredecessor()', () => { expect(treeB.findPredecessor(a)).toBe(b) expect(treeB.findPredecessor(e)).toBe(null) expect(treeB.findPredecessor(f)).toBe(a) }) }) describe('Insertion/Deletion', () => { it('insert()', () => { tree.insert(5) expect(tree.size()).toBe(1) tree.insert(3) expect(tree.size()).toBe(2) tree.insert(2) expect(tree.size()).toBe(3) tree.insert(6) expect(tree.size()).toBe(4) tree.insert(9) expect(tree.size()).toBe(5) tree.insert(4) expect(tree.size()).toBe(6) }) it('remove()', () => { tree.remove(tree.insert(3)) expect(tree.size()).toBe(0) expect(tree.find(3)).toBe(null) tree.insert(5) tree.insert(8) tree.remove(tree.insert(3)) expect(tree.size()).toBe(2) expect(tree.find(3)).toBe(null) }) it('remove() node with left child', () => { const a = new TreeNode(5, null) const b = new TreeNode(3, null) a.left = b tree.root = a tree.remove(a) expect(tree.find(5)).toBe(null) }) it('remove() node with two children', () => { const a = new TreeNode(5, null) const b = new TreeNode(3, null) const c = new TreeNode(8, null) a.left = b a.right = c tree.root = a tree.remove(a) expect(tree.find(5)).toBe(null) }) it('remove() node with two children and successor is not immediate right child', () => { const a = new TreeNode(5, null) const b = new TreeNode(3, null) const c = new TreeNode(8, null) const d = new TreeNode(7, null) a.left = b a.right = c c.left = d tree.root = a tree.remove(a) expect(tree.find(5)).toBe(null) }) }) describe('Traversals', () => { const treeB = new BinarySearchTree<number>() const a = new TreeNode(5, null) const b = new TreeNode(4, a) const c = new TreeNode(3, b) const d = new TreeNode(2, c) const e = new TreeNode(1, d) const f = new TreeNode(6, a) const g = new TreeNode(7, f) const h = new TreeNode(8, g) a.left = b b.left = c c.left = d d.left = e a.right = f f.right = g g.right = h treeB.root = a it('inorder()', () => { for (const _ of tree.inorderTraversal()) { throw new Error() } const inorderNumbers = [1, 2, 3, 4, 5, 6, 7, 8] let i = 0 for (const n of treeB.inorderTraversal()) { expect(n).toBe(inorderNumbers[i]) i += 1 } }) it('preorder()', () => { for (const _ of tree.preorderTraversal()) { throw new Error() } // Tree should look like: // 10 // 5 15 // 2 12 21 // 1 // Layer One tree.insert(10) // Layer Two tree.insert(5) tree.insert(15) // Layer Three tree.insert(2) tree.insert(12) tree.insert(21) // Layer 4 tree.insert(1) const preorderNumbers = [10, 5, 2, 1, 15, 12, 21] let i = 0 for (const n of tree.preorderTraversal()) { expect(n).toBe(preorderNumbers[i]) i += 1 } }) it('postorder()', () => { for (const _ of tree.postorderTraversal()) { throw new Error() } // Tree should look like: // 10 // 5 15 // 2 12 21 // 1 // Layer One tree.insert(10) // Layer Two tree.insert(5) tree.insert(15) // Layer Three tree.insert(2) tree.insert(12) tree.insert(21) // Layer 4 tree.insert(1) const postorderNumbers = [1, 2, 5, 12, 21, 15, 10] let i = 0 for (const n of tree.postorderTraversal()) { expect(n).toBe(postorderNumbers[i]) i += 1 } }) }) })
jeffzh4ng/Data-Structures-and-Algorithms
src/algorithms/sort/counting-sort.ts
<gh_stars>100-1000 /** * Sort an array of integers in-place and in ascending order using counting sort. * * Time complexity: O(n + k), where n is the number of elements in arr * and k is the range of numbers in arr. * * Space complexity: O(n + k) * * @param arr - array of integers to sort */ const countingSort = (arr: number[]): void => { if (arr.length == 0) { return } // check that arr elements are integers for (let idx = 0; idx < arr.length; idx++) { if (!Number.isInteger(arr[idx])) { console.error(`arr[${idx}] is not an integer`) return } } // implementation of counting sort below const max = Math.max(...arr) // find largest integer in arr const min = Math.min(...arr) // find smallest integer in arr const range = max - min + 1 // calculate range of possible numbers const counts: number[] = new Array(range).fill(0) // contains counts for each number in arr const sortedArr: number[] = new Array(arr.length) // final sorted array // get counts of each number in arr for (const num of arr) { counts[num - min]++ } // modify counts array such that each element is the sum of previous counts for (let i = 1; i < counts.length; i++) { counts[i] += counts[i - 1] } // fill in sortedArr using the indices stored in the counts array // traversing arr in reverse keeps the sort stable for (let i = arr.length - 1; i >= 0; i--) { const sortedIndex = counts[arr[i] - min] - 1 counts[arr[i] - min]-- sortedArr[sortedIndex] = arr[i] } // copy elements of sortedArr to input array for (let i = 0; i < arr.length; i++) { arr[i] = sortedArr[i] } } export default countingSort
jeffzh4ng/Data-Structures-and-Algorithms
test/algorithms/graph/shortest-paths/dijkstras-shortest-path.test.ts
import { GraphNode, WeightedGraph } from '../../../../src/algorithms/graphs/graph-node' import { shortestPath } from '../../../../src/algorithms/graphs/shortest-paths/dijkstras-shortest-path' describe('Dijksras Shortest Path', () => { test('Basic Graph', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const aNeighbors: Map<GraphNode<string>, number> = new Map([ [b, 5], [c, 1], ]) const bNeighbors: Map<GraphNode<string>, number> = new Map() const cNeighbors: Map<GraphNode<string>, number> = new Map([[b, 1]]) const graph: WeightedGraph<string> = new Map([ [a, aNeighbors], [b, bNeighbors], [c, cNeighbors], ]) const [path, cost] = shortestPath(graph, a, b) expect(path).toEqual(['a', 'c', 'b']) expect(cost).toBe(2) }) test('Basic Graph with Cycle', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const aNeighbors: Map<GraphNode<string>, number> = new Map([ [b, 5], [c, 1], ]) const bNeighbors: Map<GraphNode<string>, number> = new Map([[a, 4]]) const cNeighbors: Map<GraphNode<string>, number> = new Map([[b, 1]]) const graph: WeightedGraph<string> = new Map([ [a, aNeighbors], [b, bNeighbors], [c, cNeighbors], ]) const [path, cost] = shortestPath(graph, a, b) expect(path).toEqual(['a', 'c', 'b']) expect(cost).toBe(2) }) })
jeffzh4ng/Data-Structures-and-Algorithms
test/algorithms/search/breadth-first-search.test.ts
import { GraphNode } from '../../../src/algorithms/graphs/graph-node' import { bfs } from '../../../src/algorithms/search/breadth-first-search' describe('Breadth First Search', () => { test('Basic search', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const graph = new Map([ [a, [b]], [b, [c]], ]) expect(bfs(a, graph)).toEqual(['a', 'b', 'c']) }) test('Graph with node with two parents', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const d = new GraphNode('d') const e = new GraphNode('e') // e -----\ // / v // a->b->c->d const graph = new Map([ [a, [b, e]], [b, [c]], [c, [d]], [d, []], [e, [d]], ]) // o: [a, b, e ] // q: c, d expect(bfs(a, graph)).toEqual(['a', 'b', 'e', 'c', 'd']) }) test('Graph with loner node', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const graph = new Map([ [a, [b]], [c, []], ]) expect(bfs(a, graph)).toEqual(['a', 'b']) }) test('Cyclic graph', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const graph = new Map([ [a, [b]], [b, [c]], [c, [a]], ]) expect(bfs(a, graph)).toEqual(['a', 'b', 'c']) }) })
jeffzh4ng/Data-Structures-and-Algorithms
src/data-structures/priority-queues/min-binary-heap.ts
<filename>src/data-structures/priority-queues/min-binary-heap.ts import * as utils from '../utils' /******************************************************************************* * A min binary heap implements the Priority Queue ADT. It has constant access * to the min element of the heap, with logarithmic insertions and deletions. * * add(element) - O(logn) * poll() - O(logn) * peek() - O(1) * * For more info, refer to https://en.wikipedia.org/wiki/Binary_heap ******************************************************************************/ class MinBinaryHeap<T> { // a dynamic array to hold our elements private heap: T[] private compare: utils.CompareFunction<T> constructor(elements?: Iterable<T>, compareFunction?: utils.CompareFunction<T>) { this.heap = [] this.compare = compareFunction || utils.defaultCompare // if the client provides elements, heapify them if (elements) { this.heap = Array.from(elements) this.heapify() } } // Even though we are looping through n/2 elements and calling sink which is O(logn), // this method is still bounded by O(n), not O(nlogn). The reason being is because // we start at the second last row of the tree. Not sinking the last row of the tree // already removes half the work. // See more info on Floyd's heap construction here: https://en.wikipedia.org/wiki/Heapsort#Variations private heapify(): void { if (this.heap.length === 0) return let i = Math.max(0, Math.floor(this.size() / 2) - 1) for (; i >= 0; i--) { this.sink(i) } } /***************************************************************************** INSPECTION *****************************************************************************/ /** * Returns the size of the heap - O(1) * @returns {number} */ size(): number { return this.heap.length } /** * Returns true if the heap is empty, false otherwise - O(1) * @returns {boolean} */ isEmpty(): boolean { return this.size() == 0 } /***************************************************************************** INSERTION/DELETION *****************************************************************************/ /** * Adds an element to the heap, while maintaing the heap invariant - O(log(n)) * @param {T} element * @returns {void} */ add(element: T): void { this.heap.push(element) const indexOfLastElement = this.size() - 1 this.swim(indexOfLastElement) } /** * Removes and returns top most element of heap - O(log(n)) * @returns {T} */ poll(): T | null { if (this.isEmpty()) return null return this.removeAt(0) // O(log(n)) } /** * Removes element if it exists. Returns true if success, false otherwise - O(n) * @param {T} element * @returns {boolean} */ remove(element: T): boolean { // O(n), linear scan to find elementIndex const elementIndex = this.heap.findIndex((h: T) => this.compare(element, h) === 0) if (elementIndex === -1) return false this.removeAt(elementIndex) // O(log(n)) return true } /** * Clears the heap - O(1) * @returns {void} */ clear(): void { this.heap.length = 0 } /***************************************************************************** ACCESSING *****************************************************************************/ /** * Peeks at the top most element in the heap - O(1) * @returns {T} */ peek(): T | null { if (this.isEmpty()) return null return this.heap[0] } /***************************************************************************** SEARCHING *****************************************************************************/ /** * Returns true if element is in heap, false otherwise - O(n) * @param {T} element * @returns {boolean} */ contains(element: T): boolean { return this.heap.includes(element) } /***************************************************************************** HELPERS *****************************************************************************/ /** * Sinks element with index k until heap invariant is satisfied - O(log(n)) * O(log(n)) because in the worst case we sink the element down the entire * height of the tree * @param {number} k * @returns {void} */ private sink(k: number): void { // eslint-disable-next-line while (true) { // get index of children const leftChildIndex = this.getLeftChildIndex(k) const rightChildIndex = this.getRightChildIndex(k) // find the smallest child let smallestIndex = leftChildIndex const rightChildIsSmallerThanLeft = rightChildIndex < this.size() && this.less(rightChildIndex, leftChildIndex) if (rightChildIsSmallerThanLeft) smallestIndex = rightChildIndex // if the children indices are out of bounds or the current element is // less than than the child, stop looping and break const indexOutOfBounds = leftChildIndex >= this.size() const elementIsLessThanChild = this.less(k, smallestIndex) if (indexOutOfBounds || elementIsLessThanChild) break // otherwise swae this.swap(smallestIndex, k) // O(1) k = smallestIndex // set k to child index, and we repeat loop } } /** * Swims an element with index k until heap invariant is satisfied - O(log(n)) * O(log(n)) because in the worst case we swim the element up the entire tree * @param {number} k * @returns {void} */ private swim(k: number): void { let parentIndex = this.getParentIndex(k) // as long as k is positive and this.heap[k] < this.heap[parentIndex] while (k > 0 && this.less(k, parentIndex)) { this.swap(parentIndex, k) k = parentIndex parentIndex = this.getParentIndex(k) } } // O(1) private swap(i: number, j: number): void { const temp = this.heap[i] this.heap[i] = this.heap[j] this.heap[j] = temp } /** * Removes element at provided index by swapping it with last element, and * heapifying the swapped element by sinking/swimming it - O(log(n)). * * O(log(n)) because in worst case we swink/swim element throughout the entire tree * @param {number} indexToRemove * @returns {T} */ private removeAt(indexToRemove: number): T { const indexOfLastElement = this.size() - 1 // save the removed element so we can return it after heapifying const removedElement = this.heap[indexToRemove] // swap the removed element with the last element this.swap(indexToRemove, indexOfLastElement) // delete the removed element! this.heap.pop() if (this.heap.length === 0) return removedElement // if last element is being removed, no need to heapify (sink/swim) const lastElementIsBeingRemoved = indexToRemove === indexOfLastElement - 1 if (lastElementIsBeingRemoved) return removedElement // try sinking const indexToBeHeapified = indexToRemove const elementToBeHeapified = this.heap[indexToBeHeapified] this.sink(indexToBeHeapified) // if sinking did not work try swimming if (this.heap[indexToBeHeapified] === elementToBeHeapified) { this.swim(indexToBeHeapified) } // return saved value from before return removedElement } // O(1) private getLeftChildIndex(parentIndex: number): number { return parentIndex * 2 + 1 } // O(1) private getRightChildIndex(parentIndex: number): number { return parentIndex * 2 + 2 } // O(1) private getParentIndex(childIndex: number): number { return Math.floor((childIndex - 1) / 2) } /** * Returns true if a is less than b, false otherwise * @param {number} a * @param {number} b */ private less(a: number, b: number) { return this.compare(this.heap[a], this.heap[b]) < 0 } } export default MinBinaryHeap
jeffzh4ng/Data-Structures-and-Algorithms
src/algorithms/search/binary-search.ts
export type Item = number | string /** * Iteratively search an array of sorted items for a target item and returns its index. * * Time complexity: * - for an array of numbers: O(log(n)), * - for an array of strings: O(m*log(n)), * - where n is the number of array elements and m is the average string length. * * Space complexity: O(1) * * @param arr - Sorted array of numbers or strings to be searched * @param target - Number or string to be searched for * @return index of target in array (or -1 if target is not found) */ export const binarySearchIterative = (arr: Item[], target: Item): number => { let lo = 0 let hi = arr.length - 1 let mid while (lo <= hi) { mid = Math.floor((lo + hi) / 2) if (arr[mid] > target) { hi = mid - 1 } else if (arr[mid] < target) { lo = mid + 1 } else { return mid } } return -1 } /** * Recursively search an array of sorted items for a target item and returns its index. * * Time complexity: * - for an array of numbers: O(log(n)), * - for an array of strings: O(m*log(n)), * - where n is the number of array elements and m is the average string length. * * Space complexity: O(log(n)) * * @param arr - Sorted array of numbers or strings to be searched * @param target - Number or string to be searched for * @return index of target in array (or -1 if target is not found) */ export const binarySearchRecursive = (arr: Item[], target: Item): number => { const search = (arr: Item[], target: Item, lo: number, hi: number): number => { if (lo > hi) return -1 const mid = Math.floor((lo + hi) / 2) if (arr[mid] > target) { return search(arr, target, lo, mid - 1) } else if (arr[mid] < target) { return search(arr, target, mid + 1, hi) } else { return mid } } return search(arr, target, 0, arr.length - 1) }
jeffzh4ng/Data-Structures-and-Algorithms
test/algorithms/search/depth-first-search.test.ts
import { GraphNode } from '../../../src/algorithms/graphs/graph-node' import { dfs } from '../../../src/algorithms/search/depth-first-search' describe('Depth First Search', () => { test('Basic depth first search', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const graph = new Map([ [a, [b]], [b, [c]], [c, []], ]) expect(dfs(a, graph)).toEqual(['a', 'b', 'c']) }) test('Graph with node with two parents', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const d = new GraphNode('d') const e = new GraphNode('e') const graph = new Map([ [a, [b, e]], [b, [c]], [c, [d]], [d, []], [e, [d]], ]) // e -----\ // / v // a->b->c->d expect(dfs(a, graph)).toEqual(['a', 'b', 'c', 'd', 'e']) }) test('Graph with loner node', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const graph = new Map([ [a, [b]], [b, []], [c, []], ]) expect(dfs(a, graph)).toEqual(['a', 'b']) }) test('Cyclic graph', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const graph = new Map([ [a, [b]], [b, [c]], [c, [a]], ]) expect(dfs(a, graph)).toEqual(['a', 'b', 'c']) }) })
jeffzh4ng/Data-Structures-and-Algorithms
test/algorithms/graph/shortest-paths/bellman-ford-shortest-path.test.ts
import { GraphNode, WeightedGraph } from '../../../../src/algorithms/graphs/graph-node' import { shortestPath } from '../../../../src/algorithms/graphs/shortest-paths/bellman-ford-shortest-path' describe('Bellman-Ford Shortest Path', () => { test('Basic Graph', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const aNeighbors: Map<GraphNode<string>, number> = new Map([ [b, 5], [c, 1], ]) const bNeighbors: Map<GraphNode<string>, number> = new Map() const cNeighbors: Map<GraphNode<string>, number> = new Map([[b, 1]]) const graph: WeightedGraph<string> = new Map([ [a, aNeighbors], [b, bNeighbors], [c, cNeighbors], ]) const [path, cost] = shortestPath(graph, a, b) expect(path).toEqual(['a', 'c', 'b']) expect(cost).toBe(2) }) test('Basic Graph with Cycle', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const aNeighbors: Map<GraphNode<string>, number> = new Map([ [b, 5], [c, 1], ]) const bNeighbors: Map<GraphNode<string>, number> = new Map([[a, 4]]) const cNeighbors: Map<GraphNode<string>, number> = new Map([[b, 1]]) const graph: WeightedGraph<string> = new Map([ [a, aNeighbors], [b, bNeighbors], [c, cNeighbors], ]) const [path, cost] = shortestPath(graph, a, b) expect(path).toEqual(['a', 'c', 'b']) expect(cost).toBe(2) }) test('Basic Graph with Negative-Weighted Cycle', () => { const a = new GraphNode('a') const b = new GraphNode('b') const c = new GraphNode('c') const d = new GraphNode('d') const aNeighbors: Map<GraphNode<string>, number> = new Map([[b, 2]]) const bNeighbors: Map<GraphNode<string>, number> = new Map([ [c, -1], [d, 1], ]) const cNeighbors: Map<GraphNode<string>, number> = new Map([[a, -2]]) const dNeighbors: Map<GraphNode<string>, number> = new Map([]) const graph: WeightedGraph<string> = new Map([ [a, aNeighbors], [b, bNeighbors], [c, cNeighbors], [d, dNeighbors], ]) expect(() => { shortestPath(graph, a, b) }).toThrow() }) })
jeffzh4ng/Data-Structures-and-Algorithms
test/data-structures/sequences/stack.test.ts
import Stack from '../../../src/data-structures/sequences/stack' describe('Stack', () => { let stack: Stack<number> beforeEach(() => { stack = new Stack() }) describe('empty stack', () => { it('returns null when pop() is called on empty stack', () => { expect(stack.pop()).toBe(null) }) it('returns null when peek() is called on empty stack', () => { expect(stack.peek()).toBe(null) }) }) it('is empty', () => { expect(stack.isEmpty()).toBe(true) }) it('pushes', () => { stack.push(1) expect(stack.size()).toBe(1) stack.push(2) expect(stack.size()).toBe(2) stack.push(3) expect(stack.size()).toBe(3) }) it('finds out if list contains element', () => { expect(stack.contains(1)).toBe(false) stack.push(1) stack.push(2) stack.push(3) expect(stack.contains(1)).toBe(true) expect(stack.contains(3)).toBe(true) expect(stack.contains(8)).toBe(false) }) it('pops', () => { stack.push(1) stack.push(2) stack.push(3) stack.pop() expect(stack.size()).toBe(2) stack.pop() expect(stack.size()).toBe(1) stack.pop() expect(stack.size()).toBe(0) }) it('peeks', () => { stack.push(1) expect(stack.peek()).toBe(1) stack.push(2) expect(stack.peek()).toBe(2) }) it('clears the stack', () => { stack.push(1) stack.push(2) stack.push(3) stack.push(4) stack.clear() expect(stack.isEmpty()).toBe(true) stack.push(1) stack.clear() expect(stack.isEmpty()).toBe(true) stack.clear() expect(stack.isEmpty()).toBe(true) }) it('is iterable', () => { const nums = [1, 2, 3] for (const n of nums) { stack.push(n) } let i = 0 for (const n of stack) { expect(n).toBe(nums[i]) i += 1 } }) }) describe('Stack - complex object', () => { class Hero { heroId: number hunger: number health: number constructor(id: number) { this.heroId = id this.hunger = 100 this.health = 100 } } const sameHeroF = (a: Hero, b: Hero) => a.heroId === b.heroId let stack: Stack<Hero> beforeAll(() => { const knight = new Hero(123) const archer = new Hero(456) const mage = new Hero(789) stack = new Stack(sameHeroF) stack.push(knight) stack.push(archer) stack.push(mage) }) it('checks if stack contains hero', () => { const knight = new Hero(123) const mage = new Hero(789) expect(stack.contains(knight)).toBe(true) expect(stack.contains(mage)).toBe(true) expect(stack.contains(new Hero(246))).toBe(false) }) })
jeffzh4ng/Data-Structures-and-Algorithms
test/data-structures/sequences/circular-buffer.test.ts
import CircularBuffer from '../../../src/data-structures/sequences/circular-buffer' describe('Circular Buffer', () => { let buffer: CircularBuffer<number> beforeEach(() => { buffer = new CircularBuffer(4) }) describe('empty', () => { it('returns null when dequeue is called on empty buffer', () => { expect(buffer.dequeue()).toBe(null) }) it('returns null when peek() is called on empty buffer', () => { expect(buffer.peekFront()).toBe(null) expect(buffer.peekBack()).toBe(null) }) it('is empty', () => { expect(buffer.isEmpty()).toBe(true) }) }) describe('insertion/deletion', () => { it('enqueues', () => { buffer.enqueue(1) expect(buffer.size()).toBe(1) buffer.enqueue(2) expect(buffer.size()).toBe(2) buffer.enqueue(3) expect(buffer.size()).toBe(3) }) it('dequeues', () => { buffer.enqueue(1) buffer.enqueue(2) buffer.enqueue(3) buffer.dequeue() expect(buffer.size()).toBe(2) buffer.dequeue() expect(buffer.size()).toBe(1) buffer.dequeue() expect(buffer.size()).toBe(0) }) it('overwrites', () => { buffer.enqueue(1) buffer.enqueue(2) buffer.enqueue(3) buffer.enqueue(4) buffer.enqueue(5) expect(buffer.contains(1)).toBe(false) expect(buffer.peekFront()).toBe(2) expect(buffer.peekBack()).toBe(5) }) it('clears the buffer', () => { buffer.enqueue(1) buffer.enqueue(2) buffer.enqueue(3) buffer.enqueue(4) buffer.clear() expect(buffer.isEmpty()).toBe(true) buffer.enqueue(1) buffer.clear() expect(buffer.isEmpty()).toBe(true) buffer.clear() expect(buffer.isEmpty()).toBe(true) }) }) describe('Accessing', () => { it('peeks', () => { buffer.enqueue(1) expect(buffer.peekFront()).toBe(1) expect(buffer.peekBack()).toBe(1) buffer.enqueue(2) expect(buffer.peekFront()).toBe(1) expect(buffer.peekBack()).toBe(2) }) it('peeks back', () => { buffer.enqueue(1) buffer.enqueue(2) buffer.enqueue(3) buffer.enqueue(4) expect(buffer.peekBack()).toBe(4) }) }) describe('searching', () => { it('finds out if buffer contains element', () => { expect(buffer.contains(1)).toBe(false) buffer.enqueue(1) buffer.enqueue(2) buffer.enqueue(3) expect(buffer.contains(1)).toBe(true) expect(buffer.contains(3)).toBe(true) expect(buffer.contains(8)).toBe(false) }) }) }) describe('Circular Buffer - complex object', () => { class Hero { heroId: number hunger: number health: number constructor(id: number) { this.heroId = id this.hunger = 100 this.health = 100 } } const sameHeroF = (a: Hero, b: Hero) => a.heroId === b.heroId let buffer: CircularBuffer<Hero> beforeAll(() => { const knight = new Hero(123) const archer = new Hero(456) const mage = new Hero(789) buffer = new CircularBuffer(3, sameHeroF) buffer.enqueue(knight) buffer.enqueue(archer) buffer.enqueue(mage) }) it('checks if queue contains hero', () => { const knight = new Hero(123) const mage = new Hero(789) expect(buffer.contains(knight)).toBe(true) expect(buffer.contains(mage)).toBe(true) expect(buffer.contains(new Hero(246))).toBe(false) }) })
jeffzh4ng/Data-Structures-and-Algorithms
src/algorithms/graphs/shortest-paths/bellman-ford-shortest-path.ts
<gh_stars>100-1000 import { GraphNode, PrevVertices, ShortestDistances, WeightedGraph } from '../graph-node' /** * Perform Bellman-Ford shortest path algorithm. * Find the shortest path between two vertices in a directed graph with positive weights. * * Time complexity: O[VE] * Space complexity: O(V+E) * * @param {WeightedGraph<T>} graph * @param {GraphNode<T>} source * @param {GraphNode<T>} target * @return {[Array<<T>>, number]} */ export const shortestPath = <T>( graph: WeightedGraph<T>, source: GraphNode<T>, target: GraphNode<T> ): [Array<T>, number] => { const [dist, prev] = bellmanFord(graph, source) const shortestPath = new Array<T>() for (let at = target; at !== null; at = prev.get(at)!) { shortestPath.push(at.val) } return [shortestPath.reverse(), dist.get(target)!] } const bellmanFord = <T>( graph: WeightedGraph<T>, source: GraphNode<T> ): [ShortestDistances<T>, PrevVertices<T>] => { const dist: ShortestDistances<T> = new Map() const prev: PrevVertices<T> = new Map() // step 1. initialize for (const node of graph.keys()) { dist.set(node, Number.POSITIVE_INFINITY) prev.set(node, null) } dist.set(source, 0) // dist[source] needs to be 0, not infinity // build edge list const edgeList: Array<[GraphNode<T>, GraphNode<T>, number]> = [] for (const [v, vEdges] of graph.entries()) { for (const edge of vEdges) { edgeList.push([v, edge[0], edge[1]]) } } // step 2. relax edges V-1 time const V = graph.size for (let i = 0; i < V - 1; i++) { for (const edge of edgeList) { const [u, v, weight] = edge if (dist.get(u)! + weight < dist.get(v)!) { dist.set(v, dist.get(u)! + weight) prev.set(v, u) } } } // step 3. check for negative cycles for (const edge of edgeList) { const [u, v, weight] = edge if (dist.get(u)! + weight < dist.get(v)!) { throw new Error('Negative-weighted cycle found in graph.') } } return [dist, prev] }
jeffzh4ng/Data-Structures-and-Algorithms
src/algorithms/sort/merge-sort.ts
/** * Helper function to merge left half and right half of a subarray. * The sorted left half is arr[left : mid+1]. * The sorted right half is arr[mid+1 : right+1]. * Merging occurs in-place such that arr[left : right+1] will be sorted after function is executed. * * @param arr - array of numbers to be sorted * @param left - starting index of left half * @param mid - ending index of left half * @param right - ending index of right half */ const merge = (arr: number[], left: number, mid: number, right: number): void => { const leftArr = arr.slice(left, mid + 1) // copy of left half const rightArr = arr.slice(mid + 1, right + 1) // copy of right half let i = 0 // starting index of leftArr let j = 0 // starting index of rightArr let k = left // starting index of merged subarray (i.e. arr[left:right+1]) while (i < leftArr.length && j < rightArr.length) { if (leftArr[i] < rightArr[j]) { arr[k] = leftArr[i] i++ } else { arr[k] = rightArr[j] j++ } k++ } // if not all elements of leftArr have been traversed, copy the remaining elements while (i < leftArr.length) { arr[k] = leftArr[i] i++ k++ } // else if not all elements of rightArr have been traversed, copy remaining elements while (j < rightArr.length) { arr[k] = rightArr[j] j++ k++ } } /** * Sort an array of numbers in-place and in ascending order using top-down merge sort. * A subarray of arr can be sorted by specifying its left and right bounds. * * Time complexity: O(n*log(n)), where n is the number of elements to sort * * Space complexity: O(n) * * @param arr - array of numbers to sort * @param left - Optional: index of left bound * @param right - Optional: index of right bound */ const mergeSort = (arr: number[], left = 0, right = arr.length - 1): void => { // immediately return if array is empty if (arr.length === 0) return // check that indices are integers if (!Number.isInteger(left) || !Number.isInteger(right)) { console.error('Index Error: Left and right indices must be integers.') return } // implement merge sort algorithm if (left >= right) return const mid = Math.floor((left + right) / 2) // find middle index of current subarray mergeSort(arr, left, mid) // sort left half mergeSort(arr, mid + 1, right) // sort right half merge(arr, left, mid, right) // merge left and right halves } export default mergeSort
jeffzh4ng/Data-Structures-and-Algorithms
test/algorithms/search/binary-search.test.ts
<filename>test/algorithms/search/binary-search.test.ts import { binarySearchIterative, binarySearchRecursive, Item, } from '../../../src/algorithms/search/binary-search' describe('binarySearch', () => { type BinarySearch = (arr: Item[], target: Item) => number const runTest = (binarySearch: BinarySearch) => { it('does not find target in an empty array', () => { const array: number[] = [] expect(binarySearch(array, 1)).toBe(-1) }) describe('array with odd number of elements', () => { const arrayNums: number[] = [2, 5, 8.1, 9, 30.234, 42, 121] it('does not find target', () => { expect(binarySearch(arrayNums, 1)).toBe(-1) // nonexistent target less than min element expect(binarySearch(arrayNums, 121.2)).toBe(-1) // nonexistent target greater than max element expect(binarySearch(arrayNums, 5.1)).toBe(-1) // nonexistent target between min and max elements }) it('finds target when it exists in array', () => { expect(binarySearch(arrayNums, 5)).toBe(1) }) }) describe('array with even number of elements', () => { const arrayNums: number[] = [2, 5, 8.1, 30.234, 42, 121] it('finds target when it exists in array', () => { expect(binarySearch(arrayNums, 30.234)).toBe(3) }) }) describe('array of strings', () => { const arrayStrs: string[] = [ 'reappear', 'rearrange', 'redo', 'regroup', 'remake', 'replay', 'rewrite', ] it('finds word when it exists in array', () => { expect(binarySearch(arrayStrs, 'replay')).toBe(5) }) it('does not find word when it is not in array', () => { expect(binarySearch(arrayStrs, '')).toBe(-1) expect(binarySearch(arrayStrs, 'rewrote')).toBe(-1) expect(binarySearch(arrayStrs, 'rearranged')).toBe(-1) }) }) } describe('iterative method', () => runTest(binarySearchIterative)) describe('recursive method', () => runTest(binarySearchRecursive)) })
jeffzh4ng/Data-Structures-and-Algorithms
test/algorithms/sort/heap-sort.test.ts
import heapSort from '../../../src/algorithms/sort/heap-sort' import testCases from './test-cases' describe('heapSort', () => { for (const [description, inputArray] of Object.entries(testCases)) { it(`correctly sorts ${description}`, () => { const soln = [...inputArray] soln.sort((a, b) => a - b) // sort the copy inplace using native JS function heapSort(inputArray) //sort the original inplace expect(inputArray).toEqual(soln) }) } })
jeffzh4ng/Data-Structures-and-Algorithms
src/algorithms/search/depth-first-search.ts
import { GraphNode } from '../graphs/graph-node' /** * Perform a depth-first search through a directed graph. * * Time complexity: O(V+E) * Space complexity: O(V) * * @param {GraphNode<T>} startNode * @param {Map<GraphNode<T>, Array<GraphNode<T>>} graph * @return {Array<GraphNode<T>>} */ export const dfs = <T>(startNode: GraphNode<T>, graph: Map<GraphNode<T>, Array<GraphNode<T>>>) => { const output: Array<T> = new Array() const visited = new Set<GraphNode<T>>() recurse(startNode, graph, visited, output) return output } const recurse = <T>( root: GraphNode<T>, graph: Map<GraphNode<T>, Array<GraphNode<T>>>, visited: Set<GraphNode<T>>, output: Array<T> ): void => { output.push(root.val) visited.add(root) const children = graph.get(root) if (!children) throw new Error('Children shouldnt be null') // loop through children of root and recurse for (const child of children) { if (!visited.has(child)) recurse(child, graph, visited, output) } }
jeffzh4ng/Data-Structures-and-Algorithms
src/algorithms/sort/topological-sort-kahn.ts
import { Queue } from '../../data-structures/sequences/queue' import { GraphNode } from '../graphs/graph-node' /** * Perform a topological sort on a directed graph using Kahn's algorithm. * * Time complexity: O(V+E) * Space complexity: O(V) * * @param {Map<GraphNode<T>, Array<GraphNode<T>>} graph * @return {Array<GraphNode<T>>} */ export const topologicalSortKahn = <T>(graph: Map<GraphNode<T>, Array<GraphNode<T>>>) => { const inDegree: Map<GraphNode<T>, number> = new Map() // initialize inDegree map for (const node of graph.keys()) { inDegree.set(node, 0) } // calculate in degree's for each node for (const children of graph.values()) { for (const child of children) { inDegree.set(child, inDegree.get(child)! + 1) } } // build the sources queue which contains node with inDegree of 0 aka sources const sources = new Queue<GraphNode<T>>() for (const [node, _] of graph.entries()) { if (inDegree.get(node) === 0) sources.enqueue(node) } // loop while sources is not empty const output: Array<T> = [] while (!sources.isEmpty()) { const node = sources.dequeue() if (!node) throw new Error('Node must not be null') // push current node to output output.push(node.val) const children = graph.get(node) if (!children) throw new Error('Children must not be null') // for every child of the node, remove 1 from their inDegree becauase we visited one of their parents for (const child of children) { inDegree.set(child, inDegree.get(child)! - 1) // if that child is now a source, add it to the sources q if (inDegree.get(child) === 0) sources.enqueue(child) } } return output }
stephanbaker/hello-gatsby
src/templates/docPage.tsx
import React from "react" import { Link, graphql } from "gatsby" import Layout from "../components/Layout" import rehypeReact from "rehype-react" import ClickCounter from "../components/ClickCounter" export const query = graphql` query($path: String!) { markdownRemark(frontmatter: { path: { eq: $path } }) { htmlAst frontmatter { title date } } } ` interface DocPageTemplateProps { data: { markdownRemark: { htmlAst: string, frontmatter: { title: string, date: string } } }, pageContext: { title: string, previous: { frontmatter: { title: string, path: string } }, next: { frontmatter: { title: string, path: string } } } } export default class DocPageTemplate extends React.Component<DocPageTemplateProps, {}> { renderComponent = new rehypeReact({ createElement: React.createElement, components: { "click-counter": ClickCounter, }, }).Compiler render = () => { const { markdownRemark } = this.props.data const { frontmatter, htmlAst } = markdownRemark const { previous, next } = this.props.pageContext return ( <Layout> <h1>{frontmatter.title}</h1> {this.renderComponent(htmlAst)} <div className="pagination" style={{ width: "100%" }}> {previous && ( <Link style={{ float: "left", }} to={previous.frontmatter.path} > Prev: {previous.frontmatter.title} </Link> )} {next && ( <Link style={{ float: "right", }} to={next.frontmatter.path} > Next: {next.frontmatter.title} </Link> )} </div> </Layout> ) } }
stephanbaker/hello-gatsby
src/pages/docs.tsx
<reponame>stephanbaker/hello-gatsby import React from "react" import { Link, graphql } from "gatsby" import Layout from "../components/Layout" import Menu from "../components/Menu" export const query = graphql` query DocsMenuQuery { site { siteMetadata { sectionsOverride } } allMarkdownRemark(sort: {order: ASC, fields: [frontmatter___weight, frontmatter___title]}, filter: {fileAbsolutePath: {regex: "/.*/content/docs/"}}) { sections: group(field: frontmatter___section) { title: fieldValue nodes { frontmatter { title weight path section } } } } } ` interface Node { frontmatter: { title: string, weight: number, path: string, section: string } } interface Section { title: string nodes: Node[] } interface DocsPageProps { data: { site: { siteMetadata: { sectionsOverride: string[] } }, allMarkdownRemark: { sections: Section[] } } } export default class DocsPage extends React.Component<DocsPageProps, {}> { render = () => { const { site, allMarkdownRemark } = this.props.data; const { sections } = allMarkdownRemark; const { siteMetadata } = site; const { sectionsOverride } = siteMetadata; return ( <Layout> <h1>The Documentation</h1> <p>This is the index of the documentation we have created.</p> <p> Not interested? <Link to="/">Go back to the homepage</Link> </p> <Menu sections={sections} sectionsOverride={sectionsOverride} /> </Layout> ) } }
stephanbaker/hello-gatsby
src/components/SiteContent.tsx
<filename>src/components/SiteContent.tsx import React from "react" interface SiteContentProps { children: any } export default class SiteContent extends React.Component { render = () => { return ( <main> <div style={{ margin: '0 auto 0 auto', maxWidth: 960, padding: `1.45rem 1.0875rem`, }}> {this.props.children} </div> </main > ) } }
stephanbaker/hello-gatsby
src/components/SiteFooter.tsx
<filename>src/components/SiteFooter.tsx import React from "react" export default class SiteFooter extends React.Component { render = () => { return ( <footer style={{ margin: `0 auto 0 auto`, maxWidth: 960, padding: `1.45rem 1.0875rem`, textDecoration: 'none', }}> © {new Date().getFullYear()}, Built with&nbsp; <a href="https://www.gatsbyjs.org">Gatsby</a> </footer> ) } }
stephanbaker/hello-gatsby
src/pages/posts.tsx
<reponame>stephanbaker/hello-gatsby import React from "react" import { Link, graphql } from "gatsby" import Layout from "../components/Layout" import BlogIndex from "../components/BlogIndex" export const query = graphql` query PostsQuery { allMarkdownRemark( filter: {fileAbsolutePath: {regex: "/.*\\/content\\/posts/"}} sort: {order: DESC, fields: [frontmatter___date]} ) { edges { node { frontmatter { title path date } } } } } ` interface Edge { node: { frontmatter: { title: string, path: string, date: string } } } interface BlogPageProps { data: { allMarkdownRemark: { edges: Edge[] } } } export default class BlogPage extends React.Component<BlogPageProps, {}> { render = () => { return ( <Layout> <h1>The Blog</h1> <p>Check out what I've been talking about</p> <p>Not interested? <Link to="/">Go back to the homepage</Link></p> <BlogIndex data={this.props.data} /> </Layout> ) } }
stephanbaker/hello-gatsby
src/components/ClickCounter.tsx
<filename>src/components/ClickCounter.tsx import React from "react" const buttonStyle = { backgroundColor: "rebeccapurple", border: "none", color: "white", padding: "15px 32px", textAlign: "center" as "center", textDecoration: "none", display: "inline-block", fontSize: "16px", margin: "4px 2px", cursor: "pointer" } interface ClickCounterState { value: number } export default class ClickCounter extends React.Component<{}, ClickCounterState> { constructor(props) { super(props); this.state = { value: 0 }; } handleClick = () => { this.setState({ value: this.state.value + 1 }); } render = () => { return <button style={buttonStyle} onClick={this.handleClick}>Clicked: {this.state.value} times.</button> } }
stephanbaker/hello-gatsby
src/pages/index.tsx
import React from "react" import { Link } from "gatsby" import Layout from "../components/Layout" import Image from "../components/Image" export default class IndexPage extends React.Component { render = () => { return ( <Layout> <h1>This is a Gatsby Site!</h1> <p>This project is just a playground where I'm learning Gatsby.</p> <p>Let's see what this thing can do!</p> <div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}> <Image /> </div> <h2>What about content like blog posts?</h2> <p>Rather than tell you, why don't I just show you by taking you to <Link to="/posts/">the blog</Link></p> <h2>What about documentation?</h2> <p>We have that covered as well, so go ahead and <Link to="/docs/">check out the docs</Link></p> </Layout> ) } }
stephanbaker/hello-gatsby
src/components/Layout.tsx
<gh_stars>0 /** * Layout component that queries for data * with Gatsby's StaticQuery component * * See: https://www.gatsbyjs.org/docs/static-query/ */ import * as React from "react"; import { graphql, useStaticQuery } from "gatsby" import SiteFooter from "./SiteFooter" import SiteHeader from "./SiteHeader" import SiteContent from "./SiteContent" import "./Layout.css" interface LayoutProps { children: any } interface LayoutData { site: { siteMetadata: { title: string; } } } const Layout: React.SFC<LayoutProps> = ({ children }) => { const data: LayoutData = useStaticQuery(graphql` query SiteTitleQuery { site { siteMetadata { title } } } `) return ( <div> <SiteHeader siteTitle={data.site.siteMetadata.title} /> <SiteContent>{children}</SiteContent> <SiteFooter /> </div> ) } export default Layout;
stephanbaker/hello-gatsby
src/components/BlogIndex.tsx
<reponame>stephanbaker/hello-gatsby import React from "react" import { Link } from "gatsby" interface Edge { node: { frontmatter: { title: string, path: string } } } interface BlogIndexProps { data: { allMarkdownRemark: { edges: Edge[] } } } // const BlogIndex = ({data}) => { export default class BlogIndex extends React.Component<BlogIndexProps, {}> { render = () => { const { edges } = this.props.data ? this.props.data.allMarkdownRemark : null return ( <ul> {edges.map(edge => { const { frontmatter } = edge.node return ( <li key={frontmatter.path}> <Link to={frontmatter.path}>{frontmatter.title}</Link> </li> ) })} </ul> ) } }
stephanbaker/hello-gatsby
src/components/Menu.tsx
import React from "react" interface Node { frontmatter: { title: string, path: string } } interface Section { title: string, nodes: Node[] } interface MenuProps { sections: Section[], sectionsOverride: string[] } export default class Menu extends React.Component<MenuProps, {}> { getSections = (sections: Section[]) => { return ( <ul> {sections && sections.length > 0 && sections.map((section, sectionIndex) => <li key={`section-${sectionIndex}`}> {section.title} <ul> {section.nodes && section.nodes.length > 0 && section.nodes.map((node, nodeIndex) => <li key={`section-${sectionIndex}-node-${nodeIndex}`}> <a href={node.frontmatter.path}>{node.frontmatter.title}</a> </li> ) } </ul> </li> ) } </ul> ) } render = () => { if (!this.props.sectionsOverride || !Array.isArray(this.props.sectionsOverride)) { return this.getSections(this.props.sections) } const sectionMap = {} if (this.props.sections) { this.props.sections.forEach(section => { if (section.title && section.title.length > 0) { sectionMap[section.title] = section } }); } const reordered = [] this.props.sectionsOverride.forEach(sectionName => { const matched = sectionMap[sectionName] if (matched) { reordered.push(matched) } }); return this.getSections(reordered); } }
stephanbaker/hello-gatsby
src/components/TitleAndDescription.tsx
import React from "react" import { string } from "prop-types"; interface TitleAndDescriptionProps { data: { site: { siteMetadata: { title: string, description: string } } } } export default class TitleAndDescription extends React.Component<TitleAndDescriptionProps, {}> { render = () => { return ( <div> <h2>{this.props.data.site.siteMetadata.title}</h2> <p>{this.props.data.site.siteMetadata.description}</p> </div> ) } }
mikita-kandratsyeu/crypto-wallet-app
src/constants/constants.ts
<reponame>mikita-kandratsyeu/crypto-wallet-app<filename>src/constants/constants.ts<gh_stars>0 export interface MarketTab { id: string; title: string; ref?: any; } const marketTabs: MarketTab[] = [ { id: '1', title: 'Cryptoassets', }, { id: '2', title: 'Exchanges', }, ]; // API // My Holdings // https://api.coingecko.com/api/v3/coins/markets?vs_currency=${currency}&order=${orderBy}&per_page=${perPage}&page=${page}&sparkline=${sparkline}&price_change_percentage=${priceChangePerc}&ids=${ids} // Coin Market // https://api.coingecko.com/api/v3/coins/markets?vs_currency=${currency}&order=${orderBy}&per_page=${perPage}&page=${page}&sparkline=${sparkline}&price_change_percentage=${priceChangePerc} const constants = { marketTabs, }; export default constants;
mikita-kandratsyeu/crypto-wallet-app
src/store/market/market.reducer.ts
<filename>src/store/market/market.reducer.ts<gh_stars>0 import { MarketState } from '../types'; import * as marketActions from './market.actions'; const initialState: MarketState = { myHoldings: [], coins: [], error: null, loading: false, }; const marketReducer = (state = initialState, action: any) => { switch (action.type) { case marketActions.GET_HOLDINGS_BEGIN: return { ...state, loading: true, }; case marketActions.GET_HOLDINGS_SUCCESS: return { ...state, myHoldings: action.payload.myHoldings, }; case marketActions.GET_COIN_MARKET_BEGIN: return { ...state, loading: true, }; case marketActions.GET_COIN_MARKET_SUCCESS: return { ...state, coins: action.payload.coins, }; case marketActions.GET_HOLDINGS_FAILURE: case marketActions.GET_COIN_MARKET_FAILURE: return { ...state, error: action.payload.error, }; default: return state; } }; export default marketReducer;
mikita-kandratsyeu/crypto-wallet-app
src/store/market/market.actions.ts
import axios from 'axios'; import { Dispatch } from 'redux'; export const GET_HOLDINGS_BEGIN = 'GET_HOLDINGS_BEGIN'; export const GET_HOLDINGS_SUCCESS = 'GET_HOLDINGS_SUCCESS'; export const GET_HOLDINGS_FAILURE = 'GET_HOLDINGS_FAILURE'; export const GET_COIN_MARKET_BEGIN = 'GET_COIN_MARKET_BEGIN'; export const GET_COIN_MARKET_SUCCESS = 'GET_COIN_MARKET_SUCCESS'; export const GET_COIN_MARKET_FAILURE = 'GET_COIN_MARKET_FAILURE'; export const getHoldingsBegin = () => ({ type: GET_HOLDINGS_BEGIN, }); export const getHoldingsSuccess = (myHoldings: any) => ({ type: GET_HOLDINGS_SUCCESS, payload: { myHoldings }, }); export const getHoldingsFailure = (err: Error) => ({ type: GET_HOLDINGS_FAILURE, payload: { error: err }, }); export const getHoldings = ( holdings: any[] = [], currency: string = 'usd', orderBy: string = 'market_cap_desc', sparkline: boolean = true, priceChangePerc: string = '7d', perPage: number = 10, page: number = 1, ) => { return (dispatch: Dispatch) => { dispatch(getHoldingsBegin()); const ids = holdings.map((item: any) => item.id).join(','); const apiUrl = `https://api.coingecko.com/api/v3/coins/markets?vs_currency=${currency}&order=${orderBy}&per_page=${perPage}&page=${page}&sparkline=${sparkline}&price_change_percentage=${priceChangePerc}&ids=${ids}`; return axios({ url: apiUrl, method: 'GET', headers: { Accept: 'application/json', }, }) .then(res => { if (res.status === 200) { const myHoldings = res.data.map((item: any) => { const coin: any = holdings.find((a: any) => a.id === item.id); const price7d = item.current_price / (1 + item.price_change_percentage_7d_in_currency * 0.01); return { id: item.id, symbol: item.symbol, name: item.name, image: item.image, current_price: item.current_price, qty: coin.qty, total: coin.qty * item.current_price, price_change_percentage_7d_in_currency: item.price_change_percentage_7d_in_currency, holding_value_change_7d: (item.current_price - price7d) * coin.qty, sparkline_in_7d: { value: item.sparkline_in_7d.price.map( (price: any) => price * coin.qty, ), }, }; }); dispatch(getHoldingsSuccess(myHoldings)); } else { dispatch(getHoldingsFailure(res.data)); } }) .catch(err => { dispatch(getHoldingsFailure(err)); }); }; }; export const getCoinMarketBegin = () => ({ type: GET_COIN_MARKET_BEGIN, }); export const getCoinMarketSuccess = (coins: any) => ({ type: GET_COIN_MARKET_SUCCESS, payload: { coins }, }); export const getCoinMarketFailure = (err: Error) => ({ type: GET_COIN_MARKET_FAILURE, payload: { error: err }, }); export const getCoinMarket = ( currency: string = 'usd', orderBy: string = 'market_cap_desc', sparkline: boolean = true, priceChangePerc: string = '7d', perPage: number = 10, page: number = 1, ) => { return (dispatch: Dispatch) => { dispatch(getCoinMarketBegin()); const apiUrl = `https://api.coingecko.com/api/v3/coins/markets?vs_currency=${currency}&order=${orderBy}&per_page=${perPage}&page=${page}&sparkline=${sparkline}&price_change_percentage=${priceChangePerc}`; return axios({ url: apiUrl, method: 'GET', headers: { Accept: 'application/json', }, }) .then(res => { if (res.status === 200) { dispatch(getCoinMarketSuccess(res.data)); } else { dispatch(getCoinMarketFailure(res.data)); } }) .catch(err => { dispatch(getCoinMarketFailure(err)); }); }; };
mikita-kandratsyeu/crypto-wallet-app
src/constants/routes.ts
enum stackRoutes { MainLayout = 'MainLayout', Home = 'Home', Portfolio = 'Portfolio', Trade = 'Trade', Market = 'Market', Profile = 'Profile', } export default stackRoutes;
mikita-kandratsyeu/crypto-wallet-app
src/components/types.ts
<gh_stars>0 import { Animated } from 'react-native'; import { icons } from './Icon'; export type IconTypes = keyof typeof icons; export interface ChartProps { containerStyle?: any; chartPrices: any[]; } export interface BalanceInfoProps { title: string; displayAmount: string | number; changePct: string | number; containerStyle?: any; } export interface IconProps { name: IconTypes; width?: number; height?: number; color: string; } export interface IconTextButtonProps { label: string; icon: IconTypes; containerStyle?: any; onPress: () => void; } export interface TabBarCustomButtonProps { children: React.ReactNode; onPress: () => void; } export interface TabIconProps { focused: boolean; icon: IconTypes; label: string; isTrade?: boolean; } export interface SwitcherProps { scrollX: Animated.Value; onPress: (index: number) => void; } export interface TextButtonProps { label: string; onPress: () => void; containerStyle?: any; } export interface TabIndicatorProps { measureLayout: any[]; scrollX: Animated.Value; } export interface SectionTitleProps { title: string; } export interface SettingProps { title: string; value?: string; switchValue?: boolean; type?: 'button' | 'switch' | undefined; onPress?: () => void; onSwitchValueChange?: (value: boolean) => void; }
mikita-kandratsyeu/crypto-wallet-app
src/screens/Portfolio.tsx
import React, { useCallback, useState } from 'react'; import { useFocusEffect } from '@react-navigation/core'; import { View, Text, TouchableOpacity, FlatList, StyleSheet, Image, } from 'react-native'; import { connect } from 'react-redux'; // @ts-ignore import AnimateNumber from 'react-native-countup'; import { MainLayoutWrapper } from '.'; import { getHoldings } from '../store/market/market.actions'; import { Store } from '../store/types'; import { colors, dummyData, fonts, messages, sizes } from '../constants'; import { PortfolioProps } from './types'; import { getTotalWallet, getValueChange } from './services'; import { BalanceInfo, Chart, Icon } from '../components'; const Portfolio: React.FC<PortfolioProps> = props => { const { myHoldings, getHoldings } = props; useFocusEffect( useCallback(() => { getHoldings(dummyData.holdings); }, []), ); const [selectedCoin, setSelectedCoin] = useState<any>(null); const valueChange = getValueChange(myHoldings); const totalWallet = getTotalWallet(myHoldings); const percentChange = (valueChange / (totalWallet - valueChange)) * 100; return ( <MainLayoutWrapper> <View style={styles.root}> <View style={styles.currentBalanceContainer}> <BalanceInfo title={messages.currentBalance} displayAmount={totalWallet} changePct={percentChange} containerStyle={styles.balanceInfoContainer} /> </View> <Chart containerStyle={{ marginTop: sizes.padding }} chartPrices={ selectedCoin ? // eslint-disable-next-line camelcase selectedCoin?.sparkline_in_7d?.value : // eslint-disable-next-line camelcase myHoldings[0]?.sparkline_in_7d?.value } /> <FlatList data={myHoldings} keyExtractor={item => item.id} contentContainerStyle={styles.assetsListContainer} // eslint-disable-next-line prettier/prettier ListHeaderComponent={( <View> <Text style={styles.assetsListHeaderText}> {messages.yourAssets} </Text> <View style={styles.assetsListSectionContainer}> <Text style={styles.assetsListSectionHeader}> {messages.asset} </Text> <Text style={[ styles.assetsListSectionHeader, styles.textAlignRight, ]} > {messages.price} </Text> <Text style={[ styles.assetsListSectionHeader, styles.textAlignRight, ]} > {messages.holdings} </Text> </View> </View> // eslint-disable-next-line prettier/prettier )} renderItem={({ item }) => { const priceColor = () => { if (item.price_change_percentage_7d_in_currency === 0) { return colors.lightGray3; } if (item.price_change_percentage_7d_in_currency > 0) { return colors.lightGreen; } return colors.red; }; const changeIconStyle = { transform: Number(item.price_change_percentage_7d_in_currency) > 0 ? [{ rotate: '45deg' }] : [{ rotate: '125deg' }], }; return ( <TouchableOpacity style={styles.assetsListItem} onPress={() => setSelectedCoin(item)} > <View style={styles.assetItem}> <Image source={{ uri: item.image }} style={styles.icon} /> <Text style={styles.assetItemName}>{item.name}</Text> </View> <View style={styles.assetItemPrice}> <Text style={styles.assetItemPriceText}> {`$ ${Number(item.current_price).toLocaleString(undefined, { maximumFractionDigits: 2, })}`} </Text> <View style={styles.assetItemPriceChangeContainer}> {item.price_change_percentage_7d_in_currency !== 0 && ( <View style={changeIconStyle}> <Icon name="UpArrow" height={10} width={10} color={priceColor()} /> </View> )} <Text style={[ styles.assetItemPriceChangeText, { color: priceColor(), }, ]} > <AnimateNumber value={Number( item.price_change_percentage_7d_in_currency || 0, )} timing="linear" interval={15} formatter={(value: number) => `${value.toFixed(2)}%`} /> </Text> </View> </View> <View style={styles.assetItemHoldings}> <Text style={styles.assetItemHoldingsText}> {`$ ${Number(item.total).toLocaleString(undefined, { maximumFractionDigits: 2, })}`} </Text> <Text style={styles.assetItemHoldingsQty}> {`${item.qty} ${item.symbol.toUpperCase()}`} </Text> </View> </TouchableOpacity> ); }} /> </View> </MainLayoutWrapper> ); }; const styles = StyleSheet.create({ root: { flex: 1, paddingTop: 15, backgroundColor: colors.black, }, currentBalanceContainer: { paddingHorizontal: sizes.padding, paddingBottom: sizes.padding * 2, borderRadius: 25, backgroundColor: colors.gray, marginLeft: sizes.base, marginRight: sizes.base, }, balanceInfoContainer: { marginTop: 15, marginBottom: 15, height: 30, }, assetsListContainer: { marginTop: 30, paddingHorizontal: sizes.padding, }, assetsListHeaderText: { color: colors.white, ...fonts.h3, fontSize: 18, }, assetsListSectionContainer: { flexDirection: 'row', marginTop: sizes.radius, }, assetsListSectionHeader: { flex: 1, color: colors.lightGray3, }, textAlignRight: { textAlign: 'right', }, assetsListItem: { flexDirection: 'row', height: 55, }, icon: { height: 20, width: 20, }, assetItem: { flex: 1, flexDirection: 'row', alignItems: 'center', }, assetItemName: { marginLeft: sizes.radius, color: colors.white, ...fonts.h3, }, assetItemPrice: { flex: 1, justifyContent: 'center', }, assetItemPriceText: { textAlign: 'right', color: colors.white, ...fonts.h4, lineHeight: 15, }, assetItemPriceChangeContainer: { flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', }, assetItemPriceChangeText: { marginLeft: 5, ...fonts.body5, lineHeight: 15, }, assetItemHoldings: { flex: 1, justifyContent: 'center', }, assetItemHoldingsText: { textAlign: 'right', color: colors.white, ...fonts.h4, lineHeight: 15, }, assetItemHoldingsQty: { textAlign: 'right', color: colors.lightGray3, ...fonts.body5, lineHeight: 15, }, }); const mapStateToProps = (state: Store) => ({ myHoldings: state.marketReducer.myHoldings, }); const mapDispatchToProps = (dispatch: any) => ({ getHoldings: ( holdings: any[], currency: string, orderBy: string, sparkline: boolean, priceChangePerc: string, perPage: number, page: number, ) => dispatch( getHoldings( holdings, currency, orderBy, sparkline, priceChangePerc, perPage, page, ), ), }); export default connect(mapStateToProps, mapDispatchToProps)(Portfolio);
mikita-kandratsyeu/crypto-wallet-app
src/components/Icon.tsx
// @ts-nocheck import React from 'react'; import { colors } from '../constants'; import Close from '../../assets/icons/close.svg'; import Briefcase from '../../assets/icons/briefcase.svg'; import Home from '../../assets/icons/home.svg'; import Market from '../../assets/icons/market.svg'; import Profile from '../../assets/icons/profile.svg'; import RightArrow from '../../assets/icons/right-arrow.svg'; import Send from '../../assets/icons/send.svg'; import Trade from '../../assets/icons/trade.svg'; import UpArrow from '../../assets/icons/up-arrow.svg'; import Verified from '../../assets/icons/verified.svg'; import WithDraw from '../../assets/icons/withdraw.svg'; import { IconProps } from './types'; export const icons = { Close, Briefcase, Home, Market, Profile, RightArrow, Send, Trade, UpArrow, Verified, WithDraw, }; export const Icon: React.FC<IconProps> = props => { const { name, width = 15, height = 15, color = colors.white } = props; const SvgIcon = icons[name]; return <SvgIcon fill={color} width={width} height={height} />; };
mikita-kandratsyeu/crypto-wallet-app
src/components/TextButton.tsx
import React from 'react'; import { StyleSheet, Text } from 'react-native'; import { TouchableOpacity } from 'react-native-gesture-handler'; import { colors, fonts, sizes } from '../constants'; import { TextButtonProps } from './types'; export const TextButton: React.FC<TextButtonProps> = props => { const { label, onPress, containerStyle } = props; return ( <TouchableOpacity style={[styles.root, containerStyle]} onPress={onPress}> <Text style={styles.text}>{label}</Text> </TouchableOpacity> ); }; const styles = StyleSheet.create({ root: { alignItems: 'center', justifyContent: 'center', paddingVertical: 3, paddingHorizontal: 18, borderRadius: sizes.radius, backgroundColor: colors.gray1, }, text: { color: colors.white, ...fonts.h3, }, });
mikita-kandratsyeu/crypto-wallet-app
src/constants/messages.ts
<gh_stars>0 enum messages { home = 'Home', portfolio = 'Portfolio', trade = 'Trade', market = 'Market', profile = 'Profile', transfer = 'Transfer', withdraw = 'Withdraw', yourWallet = 'Your Wallet', changes7d = '7d changes', changes7dShort = '% (7d)', usd = 'USD', topCryptoCurrency = 'Top Cryptocurrency', currentBalance = 'Current Balance', yourAssets = 'Your Assets', asset = 'Asset', price = 'Price', holdings = 'Holdings', buttonAlert = 'Got it!', titleAlert = 'Future development', bodyAlert = 'This functionality is not available at the moment', top = 'Top', verified = 'Verified', app = 'APP', launchScreen = 'Launch Screen', launchScreenValue = 'Home', appearance = 'Appearance', appearanceValue = 'Dark', account = 'ACCOUNT', paymentCurrency = 'Payment Currency', paymentCurrencyValue = 'USD', language = 'Language', languageValue = 'English', security = 'SECURITY', faceId = 'Face ID', passwordSettings = '<PASSWORD>', changePassword = '<PASSWORD>', twoFactorAuth = '2-Factor Authentication', } export default messages;
mikita-kandratsyeu/crypto-wallet-app
src/screens/index.ts
import Home from './Home'; import MainLayoutWrapper from './MainLayoutWrapper'; import Portfolio from './Portfolio'; import Market from './Market'; import { Profile } from './Profile'; import { Trade } from './Trade'; export { Home, MainLayoutWrapper, Portfolio, Market, Profile, Trade };
mikita-kandratsyeu/crypto-wallet-app
src/components/SectionTitle.tsx
<gh_stars>0 import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import { colors, fonts, sizes } from '../constants'; import { SectionTitleProps } from './types'; export const SectionTitle: React.FC<SectionTitleProps> = props => { const { title } = props; return ( <View style={styles.root}> <Text style={styles.text}>{title}</Text> </View> ); }; const styles = StyleSheet.create({ root: { marginTop: sizes.padding, }, text: { color: colors.lightGray3, ...fonts.h4, }, });
mikita-kandratsyeu/crypto-wallet-app
src/store/types.ts
<filename>src/store/types.ts export interface Store { tabReducer: TabState; marketReducer: MarketState; } export interface TabState { isTradeModalVisible: boolean; } export interface MarketState { loading: boolean; error: any; myHoldings: any[]; coins: any[]; }
mikita-kandratsyeu/crypto-wallet-app
src/store/tab/tab.reducer.ts
import { TabState } from '../types'; import * as tabActionTypes from './tab.actions'; const initialState: TabState = { isTradeModalVisible: false, }; const tabReducer = (state = initialState, action: any) => { switch (action.type) { case tabActionTypes.SET_TRADE_MODAL_VISIBILITY: return { ...state, isTradeModalVisible: action.payload.isVisible, }; default: return state; } }; export default tabReducer;
mikita-kandratsyeu/crypto-wallet-app
src/screens/services.ts
<reponame>mikita-kandratsyeu/crypto-wallet-app import { Alert, AlertButton } from 'react-native'; const getTotalWallet = <T extends {}>(myHoldings: T[]) => myHoldings.reduce((a: number, b: any) => a + (b.total || 0), 0); const getValueChange = <T extends {}>(myHoldings: T[]) => myHoldings.reduce( (a: number, b: any) => a + (b.holding_value_change_7d || 0), 0, ); const showAlert = ({ title, body, buttons, }: { title: string; body: string; buttons?: AlertButton[]; }) => Alert.alert(title, body, buttons); export { getTotalWallet, getValueChange, showAlert };