repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
Mabloq/mabloq-notion
app/src/block/interfaces/blocks/image.interface.ts
import { BaseBlockInterface } from '../block.interface'; import { FileObjectInterface } from '../common/file-object.interface'; export interface ImageBlockInterface extends BaseBlockInterface { image: FileObjectInterface; }
Mabloq/mabloq-notion
app/src/block/tests/services/block.service.spec.ts
<filename>app/src/block/tests/services/block.service.spec.ts import { Test, TestingModule } from '@nestjs/testing'; import { BlockService } from '../../services/block.service'; import { getModelToken } from '@nestjs/mongoose'; import { Query, Model } from 'mongoose'; import { BlockInterface } from '../../interfaces/block.interface'; import { BlockDocument } from '../../schemas/block.schema'; import { CreateBlockDto } from '../../dto/create-block.dto'; import { json } from 'stream/consumers'; import { BlockDTOs } from '../../dto/extra-models/block-models'; import { mockParagraphBlock, mockParagraphBlockDocument, mapParagraphBlockArrToDocumentArr, } from '../mocks/blocks'; const blockArr = [ mockParagraphBlock('id-1', 'One Block to rule them all'), mockParagraphBlock('id-2', 'One Block to find them'), mockParagraphBlock('id-3', 'One Block to bring them all'), mockParagraphBlock('id-4', 'One Block to bring them all'), mockParagraphBlock('id-5', 'And in the neatness bind them.'), ]; const blockDocumentArr = mapParagraphBlockArrToDocumentArr(blockArr); describe('BlockService', () => { let service: BlockService; let model: Model<BlockDocument>; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ BlockService, { provide: getModelToken('Block'), useValue: { new: jest.fn().mockResolvedValue(mockParagraphBlock()), constructor: jest.fn().mockResolvedValue(mockParagraphBlock()), find: jest.fn(), findOne: jest.fn(), update: jest.fn(), create: jest.fn(), remove: jest.fn(), exec: jest.fn(), }, }, ], }).compile(); service = module.get<BlockService>(BlockService); model = module.get<Model<BlockDocument>>(getModelToken('Block')); }); it('should be defined', () => { expect(service).toBeDefined(); }); afterEach(() => { jest.clearAllMocks(); }); it('findMany: should return all listed block ids', async () => { //Spy mock! jest.spyOn(model, 'find').mockReturnValue({ exec: jest.fn().mockResolvedValueOnce(blockDocumentArr), } as any); //set scenario usig service, that uses model.find method const foundBlocks = await service.findMany([ 'id-1', 'id-2', 'id-3', 'id-4', 'id-5', ]); //assert that out our service actually calls our model.find method expect(foundBlocks).toEqual(blockDocumentArr); }); it('insertOne: returns created block', async () => { // spyc mock makes sure that if create gets called in our service.insertOne function we return a mock created block jest.spyOn(model, 'create').mockReturnValue({ exec: jest.fn().mockResolvedValueOnce(mockParagraphBlockDocument()), } as any); //set scenario using the service.insertOne method const createdBlock = await service.insertOne({ object: 'block', type: 'paragraph', paragraph: { rich_text: [ { type: 'text', text: { text: 'derp', }, }, ], }, }); }); });
Mabloq/mabloq-notion
app/src/block/controllers/page.controller.ts
import { Controller, Get, Post, Body, Patch, Param, Delete, } from '@nestjs/common'; import { CreateDatabaseDto } from '../dto/database/create-database.dto'; import { DatabaseService } from '../services/database.service'; @Controller('/api/rest/v1/page') export class PageController { constructor(private readonly databaseService: DatabaseService) {} @Post() create(@Body() createDatabaseDto: CreateDatabaseDto) { return this.databaseService.insertOne(createDatabaseDto); } @Get(':id') findOne(@Param('id') id: string) { return this.databaseService.findOne(id); } // @Patch(':id') // update(@Param('id') id: string, @Body() updateBlockDto: UpdateBlockDto) { // return this.blockService.update(+id, updateBlockDto); // } // @Delete(':id') // remove(@Param('id') id: string) { // return this.databaseService.remove(id); // } }
Mabloq/mabloq-notion
app/src/block/schemas/blocks/paragraph.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; import { BlockInterface, ParagraphInterface, ParagraphBlockInterface, BaseBlockInterface, } from 'src/block/interfaces'; import { RichTextInterface } from 'src/block/interfaces/common/rich-text.interface'; import { Block, BlockSchema } from '../block.schema'; import { RichText, RichTextSchema } from '../common/rich-text.schema'; export type ParagraphDocument = Paragraph & Document; export type ParagraphBlockDocument = ParagraphBlock & Document; @Schema({ _id: false }) export class Paragraph implements ParagraphInterface { @Prop({ _id: false, type: [RichTextSchema] }) rich_text: RichTextInterface[]; @Prop({ required: false }) color: string; @Prop({ type: BlockSchema, required: false }) children: BlockInterface[]; } export const ParagraphSchema = SchemaFactory.createForClass(Paragraph); @Schema({ _id: false }) export class ParagraphBlock implements ParagraphBlockInterface { object: string; type: string; updated_by: string; created_time: string; last_edited_time: string; has_children: boolean; children?: string[]; @Prop({ type: ParagraphSchema, required: true }) paragraph: ParagraphInterface; } export const ParagraphBlockSchema = SchemaFactory.createForClass(ParagraphBlock);
Mabloq/mabloq-notion
app/src/block/schemas/properties/property-types/select-property.schema.ts
import { Prop, Schema, SchemaFactory, raw } from '@nestjs/mongoose'; import { Document } from 'mongoose'; @Schema() export class SelectProperty { @Prop( raw({ name: { type: String, required: true }, }), ) select: { name: string }; } export const SelectPropertySchema = SchemaFactory.createForClass(SelectProperty); export type SelectPropertyDocument = SelectProperty & Document;
Mabloq/mabloq-notion
app/src/block/block.module.ts
import { Module } from '@nestjs/common'; import { BlockService } from './services/block.service'; import { BlockController } from './controllers/block.controller'; import { MongooseModule } from '@nestjs/mongoose'; import { Block, BlockSchema } from './schemas/block.schema'; import { BlockEnum } from './schemas/common/block-enum'; import { ParagraphBlockSchema } from './schemas/blocks/paragraph.schema'; import { Heading1BlockSchema } from './schemas/blocks/heading-1.schema'; import { ImageBlockSchema } from './schemas/common/image.schema'; import { CodeBlockSchema } from './schemas/blocks/code.schema'; import { DatabaseSchema } from './schemas/database.schema'; import { PageSchema } from './schemas/page.schema'; import { HigherOrderBlock, HigherOrderBlockSchema, } from './schemas/higher-order-block.schema'; import { ObjectEnum } from './schemas/common/object-enum'; import { DatabaseService } from './services/database.service'; import { DatabaseController } from './controllers/database.controller'; import { PageService } from './services/page.service'; @Module({ imports: [ MongooseModule.forFeature([ { name: Block.name, schema: BlockSchema, discriminators: [ { name: BlockEnum.PARAGRAPH, schema: ParagraphBlockSchema }, { name: BlockEnum.HEADING1, schema: Heading1BlockSchema }, { name: BlockEnum.IMAGE, schema: ImageBlockSchema }, { name: BlockEnum.CODE, schema: CodeBlockSchema }, ], }, ]), MongooseModule.forFeature([ { name: HigherOrderBlock.name, schema: HigherOrderBlockSchema, discriminators: [ { name: ObjectEnum.PAGE, schema: PageSchema }, { name: ObjectEnum.DATABASE, schema: DatabaseSchema }, ], }, ]), ], providers: [BlockService, DatabaseService, PageService], controllers: [BlockController, DatabaseController], }) export class BlockModule {}
Mabloq/mabloq-notion
app/src/block/interfaces/page.interface.ts
import { HigherOrderBlockInterface } from './high-order-block.interface'; import { PropertyInterface } from './properties/property.interface'; export interface PageInterface extends HigherOrderBlockInterface { properties: { title: PropertyInterface; [key: string | symbol]: PropertyInterface; }; has_content: boolean; content?: string[]; }
Mabloq/mabloq-notion
app/src/block/interfaces/common/parent.interface.ts
export interface DatabaseParentInterface { type: 'database'; database_id: string; } export interface PageParentInterface { type: 'page'; page_id: string; } export interface WorkspaceParentInterface { type: 'workspace'; workspace_id: string; } export type ParentInerface = | WorkspaceParentInterface | DatabaseParentInterface | PageParentInterface;
Mabloq/mabloq-notion
app/src/block/dto/append-block-children.dto.ts
<reponame>Mabloq/mabloq-notion<gh_stars>0 import { ApiProperty } from '@nestjs/swagger'; import { BlockModelRefs, BlockDTOs } from './extra-models/block-models'; export class CreateBlockDto { @ApiProperty({ required: true }) block_id: string; @ApiProperty({ type: 'array', items: { anyOf: BlockModelRefs, }, required: true, }) children: BlockDTOs; }
Mabloq/mabloq-notion
app/src/block/dto/extra-models/properties/property-types/select-property.dto.ts
<gh_stars>0 import { ApiExtraModels, ApiProperty, getSchemaPath } from '@nestjs/swagger'; import { SelectPropertyInterface } from 'src/block/interfaces/properties/property-types/select-property.interface'; @ApiExtraModels() export class SelectNameDto { @ApiProperty() name: string; } @ApiExtraModels() export class SelectPropertyDto implements SelectPropertyInterface { @ApiProperty() type: 'select'; @ApiProperty({ type: 'object', additionalProperties: { $ref: getSchemaPath(SelectNameDto), }, }) select: { name: string }; }
Mabloq/mabloq-notion
app/src/block/schemas/properties/property-types/multi-select-property.schema.ts
<filename>app/src/block/schemas/properties/property-types/multi-select-property.schema.ts import { Prop, Schema, SchemaFactory, raw } from '@nestjs/mongoose'; import { Document } from 'mongoose'; @Schema() export class MultiSelectProperty { @Prop( raw({ name: { type: [{ name: String }], required: true }, }), ) multi_select: [{ name: string }]; } export const MultiSelectPropertySchema = SchemaFactory.createForClass(MultiSelectProperty); export type SelectPropertyDocument = MultiSelectProperty & Document;
Mabloq/mabloq-notion
app/src/block/schemas/common/block-enum.ts
export enum BlockEnum { PARAGRAPH = 'paragraph', HEADING1 = 'heading_1', IMAGE = 'image', CODE = 'code', FILE = 'file', } export type BlockType = | BlockEnum.PARAGRAPH | BlockEnum.HEADING1 | BlockEnum.IMAGE | BlockEnum.FILE | BlockEnum.CODE;
Mabloq/mabloq-notion
app/src/block/schemas/blocks/heading-1.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; import { Heading1BlockInterface, Heading1Interface, } from 'src/block/interfaces'; import { RichTextInterface } from 'src/block/interfaces/common/rich-text.interface'; import { RichTextSchema } from '../common/rich-text.schema'; export type Heading1Document = Heading1 & Document; export type Heading1BlockDocument = Heading1Block & Document; @Schema() export class Heading1 implements Heading1Interface { @Prop({ _id: false, type: [RichTextSchema] }) rich_text: RichTextInterface[]; @Prop() color: string; } export class Heading1Block implements Heading1BlockInterface { object: string; id: string; type: string; created_time: string; updated_by: string; //TODO: Partial<User> last_edited_time: string; has_children: boolean; @Prop({ type: Heading1, required: true }) heading_1: Heading1; } export const Heading1Schema = SchemaFactory.createForClass(Heading1); export const Heading1BlockSchema = SchemaFactory.createForClass(Heading1Block);
Mabloq/mabloq-notion
app/src/block/dto/extra-models/blocks/heading1.dto.ts
import { ApiProperty, ApiExtraModels, getSchemaPath } from '@nestjs/swagger'; import { RichTextDto } from '../common/rich-text.dto'; import { BaseBlockDto } from '../base-block.dto'; @ApiExtraModels(RichTextDto) export class Heading1Dto { @ApiProperty({ required: false }) color: string; @ApiProperty({ required: true, type: 'array', items: { $ref: getSchemaPath(RichTextDto) }, }) rich_text: RichTextDto[]; } @ApiExtraModels(Heading1Dto) export class Heading1BlockDto extends BaseBlockDto { @ApiProperty({ type: 'object', items: { $ref: getSchemaPath(Heading1Dto) }, }) heading_1: Heading1Dto; }
Mabloq/mabloq-notion
app/src/block/dto/extra-models/parents/database-parent.dto.ts
<gh_stars>0 import { ApiExtraModels, ApiProperty } from '@nestjs/swagger'; import { DatabaseParentInterface } from 'src/block/interfaces/common/parent.interface'; @ApiExtraModels() export class DatabaseParentDto implements DatabaseParentInterface { @ApiProperty({ default: 'database', required: true, }) type: 'database'; @ApiProperty({ required: true }) database_id: string; }
Mabloq/mabloq-notion
app/src/block/interfaces/properties/property-config/select-config.interface.ts
export interface SelectOptionInterface { id: string; color: string; name: string; } export interface SelectConfigInterface { type: 'select'; options: SelectOptionInterface[]; }
Mabloq/mabloq-notion
app/src/block/dto/create-block.dto.ts
<filename>app/src/block/dto/create-block.dto.ts import { BlockDTOs } from './extra-models/block-models'; export type CreateBlockDto = BlockDTOs;
Mabloq/mabloq-notion
app/src/block/schemas/page.schema.ts
<reponame>Mabloq/mabloq-notion<filename>app/src/block/schemas/page.schema.ts import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document, Schema as MongooseSchema } from 'mongoose'; import { Block, BlockSchema } from './block.schema'; import { RichText, RichTextSchema } from './common/rich-text.schema'; import { Image, ImageSchema } from './common/image.schema'; import { PropertySchema, Property } from './properties/property.schema'; import { PageInterface } from '../interfaces/page.interface'; import { FileObjectInterface } from '../interfaces/common/file-object.interface'; import { PropertyInterface } from '../interfaces/properties/property.interface'; import { ParentInerface } from '../interfaces/common/parent.interface'; import { ObjectEnum } from './common/object-enum'; import mongoose from 'mongoose'; @Schema() export class Page implements PageInterface { object!: string; archived: boolean; icon: FileObjectInterface; cover: FileObjectInterface; properties: { title: PropertyInterface; [key: string | symbol]: PropertyInterface; }; parent: ParentInerface; parent_id: string; created_time: string; created_by: string; //TODO: Partial<User> last_edited_time: string; last_edited_by: string; //TODO: Partial<User> @Prop({ type: Boolean, default: false }) has_content: boolean; @Prop({ type: mongoose.Types.ObjectId, ref: 'Block' }) content: string[]; } export type PageDocument = Page & Document; export const PageSchema = SchemaFactory.createForClass(Page);
Mabloq/mabloq-notion
app/src/block/interfaces/high-order-block.interface.ts
import { ParentInerface } from './common/parent.interface'; import { PropertyInterface } from './properties/property.interface'; import { FileObjectInterface } from './common/file-object.interface'; export interface HigherOrderBlockInterface { id?: string; object: string; parent?: ParentInerface; parent_id?: string; archived?: boolean; cover?: FileObjectInterface; icon?: FileObjectInterface; created_time: string; created_by: string; last_edited_time: string; last_edited_by: string; }
Mabloq/mabloq-notion
app/src/block/interfaces/database.interface.ts
<filename>app/src/block/interfaces/database.interface.ts import { PropertyConfigInterface } from './properties/property.interface'; import { HigherOrderBlockInterface } from './high-order-block.interface'; export interface DatabaseInterface extends HigherOrderBlockInterface { properties: { title: PropertyConfigInterface; [key: string | symbol]: PropertyConfigInterface; }; }
Mabloq/mabloq-notion
app/src/block/interfaces/properties/property-types/number-property.interface.ts
export interface NumberPropertyInterface { type: 'number'; number: number; }
Mabloq/mabloq-notion
app/src/block/tests/mocks/page/index.ts
<gh_stars>0 import { BlockDTOs } from 'src/block/dto/extra-models/block-models'; import { CreatePageDto } from 'src/block/dto/page/create-page.dto'; import { ParentInerface } from 'src/block/interfaces/common/parent.interface'; import { PageInterface } from 'src/block/interfaces/page.interface'; import { PropertiesInterface } from 'src/block/interfaces/properties/property.interface'; import { HigherOrderBlockDocument } from 'src/block/schemas/higher-order-block.schema'; import { PageDocument } from 'src/block/schemas/page.schema'; const dateIso = new Date().toISOString(); const mockBasePage = ( id = 'a uuid', object = 'page', last_edited_by = 'mabloq', created_by = 'mabloq', has_content = false, ): Omit<PageInterface, 'properties'> => ({ id, object, created_by, created_time: dateIso, last_edited_by, has_content, last_edited_time: dateIso, }); export const mockPage = ( id = 'a uuid', title = 'A Page Title', properties: PropertiesInterface = { title: { type: 'title', title: [ { type: 'text', plain_text: title, text: { text: title }, }, ], }, }, content: string[], ): PageInterface => { const basePage = mockBasePage(id); return { ...basePage, properties, content, }; }; export const mockCreatePageDto = ( id = 'a uuid', title = 'A Page Title', properties: PropertiesInterface = { title: { type: 'title', title: [ { type: 'text', plain_text: title, text: { text: title }, }, ], }, }, parent: ParentInerface = { type: 'page', page_id: 'id-page-1' }, content: BlockDTOs[] = [], ): CreatePageDto => { const basePage = mockBasePage(id); return { ...basePage, properties, parent, content, }; }; export const mockPageDocument = ( mock?: Partial<PageInterface>, ): Partial<HigherOrderBlockDocument | PageDocument> => ({ _id: mock?.id || 'a uuid', object: mock?.object, last_edited_by: mock?.last_edited_by || 'mabloq', created_time: mock?.created_time || dateIso, last_edited_time: mock?.last_edited_time || dateIso, has_content: mock?.has_content || false, content: mock?.content || ['block uuid'], });
Mabloq/mabloq-notion
app/src/block/utils/page-validators/validators/page-parent-validator.ts
import { CreatePageDto } from '../../../dto/page/create-page.dto'; import IPageValidator from '../page-validator-interface'; import { PropertiesInterface } from '../../../interfaces/properties/property.interface'; export default class PageParentValidator implements IPageValidator { private createPageDto: CreatePageDto; private onlyTitleProperties(properties: PropertiesInterface) { const fieldValues = Object.keys(properties); return fieldValues.length == 1 && fieldValues[0] == 'title'; } constructor(createPageDto: CreatePageDto) { this.createPageDto = createPageDto; } async validate(): Promise<void> { if (!this.onlyTitleProperties(this.createPageDto.properties)) { // console.log( // 'Invalid Field Exception: Pages with parents of type page can only use title property', // ); throw new Error( 'Invalid Field Exception: Pages with parents of type page can only use title property', ); } } }
Mabloq/mabloq-notion
app/src/block/schemas/higher-order-block.schema.ts
<filename>app/src/block/schemas/higher-order-block.schema.ts import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document, Schema as MongooseSchema } from 'mongoose'; import { ParentSchema } from './parents/parent.schema'; import { ImageSchema } from './common/image.schema'; import { FileObjectInterface } from '../interfaces/common/file-object.interface'; import { ParentInerface } from '../interfaces/common/parent.interface'; import { ObjectEnum } from './common/object-enum'; import { HigherOrderBlockInterface } from '../interfaces/high-order-block.interface'; import { DatabaseParentSchema } from './parents/database-parent.schema'; import { PageParentSchema } from './parents/page-parent.schema'; import mongoose from 'mongoose'; import { FileObjectSchema } from './common/file-object.schema'; export enum ParentEnum { DATABASE_ID = 'database_id', PAGE_ID = 'page_id', } @Schema({ discriminatorKey: 'object' }) export class HigherOrderBlock implements HigherOrderBlockInterface { @Prop({ type: String, required: true, enum: Object.values(ObjectEnum), message: '{VALUE} is not supported', }) object!: string; @Prop({ type: Boolean, default: false }) archived: boolean; @Prop({ type: FileObjectSchema, required: false }) icon: FileObjectInterface; @Prop({ type: FileObjectSchema, required: false }) cover: FileObjectInterface; @Prop({ type: ParentSchema, required: false }) parent: ParentInerface; @Prop({ type: mongoose.Types.ObjectId, ref: 'HigherOrderBlock', required: false, index: { partialFilterExpression: { parent_id: { $exists: true, $gt: '' } }, }, }) parent_id: string; @Prop({ type: Date, }) created_time: string; @Prop() created_by: string; //TODO: Partial<User> @Prop({ type: Date, }) last_edited_time: string; @Prop() last_edited_by: string; //TODO: Partial<User> } export type HigherOrderBlockDocument = HigherOrderBlock & Document; export const HigherOrderBlockSchema = SchemaFactory.createForClass(HigherOrderBlock); HigherOrderBlockSchema.index( { parent: 1 }, { partialFilterExpression: { index: { $exists: true, $gt: '' } }, }, ); HigherOrderBlockSchema.path<MongooseSchema.Types.Subdocument>( 'parent', ).discriminator('database_id', DatabaseParentSchema); HigherOrderBlockSchema.path<MongooseSchema.Types.Subdocument>( 'parent', ).discriminator('page_id', PageParentSchema);
Mabloq/mabloq-notion
app/src/block/dto/extra-models/common/annotations.dto.ts
import { ApiProperty } from '@nestjs/swagger'; export class AnnotationDto { @ApiProperty({ type: 'boolean', default: false, }) bold: boolean; @ApiProperty({ type: 'boolean', default: false, }) italic: boolean; @ApiProperty({ type: 'boolean', default: false, }) strikethrough: boolean; @ApiProperty({ type: 'boolean', default: false, }) underline: boolean; @ApiProperty({ type: 'boolean', default: false, }) code: boolean; }
Mabloq/mabloq-notion
app/src/block/schemas/common/rich-text.schema.ts
<gh_stars>0 import { Prop, Schema, SchemaFactory, raw } from '@nestjs/mongoose'; @Schema({ _id: false }) export class RichText { @Prop({ required: true, default: 'text' }) type: string; @Prop( raw({ content: { type: String, required: true }, link: { type: String, required: false }, }), ) text: Record<string, string>; @Prop( raw({ type: { bold: { type: Boolean, default: false }, italic: { type: Boolean, default: false }, strikethrough: { type: Boolean, default: false }, underline: { type: Boolean, default: false }, code: { type: Boolean, default: false }, }, required: false, }), ) annotation: Record<string, boolean>; } export const RichTextSchema = SchemaFactory.createForClass(RichText);
Mabloq/mabloq-notion
app/src/block/services/database.service.ts
<reponame>Mabloq/mabloq-notion import { Injectable } from '@nestjs/common'; import { CreateDatabaseDto } from '../dto/database/create-database.dto'; import { Model, FilterQuery } from 'mongoose'; import { InjectModel } from '@nestjs/mongoose'; import { HigherOrderBlock } from '../schemas/higher-order-block.schema'; import { DatabaseDocument } from '../schemas/database.schema'; @Injectable() export class DatabaseService { constructor( @InjectModel(HigherOrderBlock.name) private higherOrderBlockModel: Model<HigherOrderBlock>, ) {} async insertOne( createDatabaseDto: CreateDatabaseDto, ): Promise<HigherOrderBlock> { const createdBlock = await this.higherOrderBlockModel.create( createDatabaseDto, ); return createdBlock.save(); } async findChildren(parentId: string) { const findQuery: FilterQuery<HigherOrderBlock> = { parent_id: parentId, }; const fetchedBlocks = await this.higherOrderBlockModel .find(findQuery) .exec(); return fetchedBlocks; } async findOne(id: string): Promise<Partial<DatabaseDocument>> { return (await this.higherOrderBlockModel.findById( id, )) as Partial<DatabaseDocument>; } }
Mabloq/mabloq-notion
app/src/block/schemas/common/file-object.schema.ts
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { FileObjectInterface } from 'src/block/interfaces/common/file-object.interface'; @Schema({ _id: false }) export class FileObject implements FileObjectInterface { @Prop({ default: 'external' }) type: string; @Prop({ required: true }) url: string; } export const FileObjectSchema = SchemaFactory.createForClass(FileObject);
joejensen/react-bouncing-balls
src/Vector.tsx
/** * A basic 3d vector used to track position and velocity of the balls */ export class Vector { constructor(public x: number, public y: number, public z: number) { } setValue(x: number, y: number, z: number): void { this.x = x; this.y = y; this.z = z; } }
joejensen/react-bouncing-balls
src/BouncingBallsDiv.tsx
/** * @class BouncingBallsDivComponent */ import * as React from 'react'; import {RefObject} from "react"; import {PointCollection} from "./PointCollection"; export type BouncingBallsDivProps = { src: string; width: number; height: number; cellSize: number; } export default class BouncingBallsDivComponent extends React.Component<BouncingBallsDivProps> { static defaultProps: BouncingBallsDivProps = { src: '', width: 512, height: 512, cellSize: 20 }; private readonly containerRef: RefObject<HTMLDivElement>; private readonly pointCollection: PointCollection = new PointCollection(); constructor(props: BouncingBallsDivProps) { super(props); this.containerRef = React.createRef(); } render() { return ( <div ref={this.containerRef} className="BouncingBallsDiv_container"/> ) } public componentDidMount(): void { const containerEl: HTMLDivElement | null = this.containerRef.current; if( !containerEl) { return; } containerEl.ontouchstart = e => { e.preventDefault(); }; containerEl.ontouchmove = e => { e.preventDefault(); let mPosx = 0; let mPosy = 0; let ePosx = 0; let ePosy = 0; if (e.targetTouches[0].pageX || e.targetTouches[0].pageY) { mPosx = e.targetTouches[0].pageX; mPosy = e.targetTouches[0].pageY; } else if (e.targetTouches[0].clientX || e.targetTouches[0].clientY) { mPosx = e.targetTouches[0].clientX + document.body.scrollLeft + document.documentElement.scrollLeft; mPosy = e.targetTouches[0].clientY + document.body.scrollTop + document.documentElement.scrollTop; } let currentObject: any = containerEl; if ( currentObject.offsetParent) { do { ePosx += currentObject.offsetLeft; ePosy += currentObject.offsetTop; currentObject = currentObject.offsetParent; } while ( currentObject.offsetParent); } this.pointCollection.mousePos.setValue(mPosx - ePosx, mPosy - ePosy, 0); }; containerEl.ontouchend = e => { e.preventDefault(); this.pointCollection.mousePos.setValue(-999, -999, -999); }; containerEl.ontouchcancel = e => { e.preventDefault(); this.pointCollection.mousePos.setValue(-999, -999, -999); }; containerEl.onmousemove = e => { let mPosx = 0; let mPosy = 0; let ePosx = 0; let ePosy = 0; if (e.pageX || e.pageY) { mPosx = e.pageX; mPosy = e.pageY; } else if (e.clientX || e.clientY) { mPosx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; mPosy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } let currentObject: any = containerEl; if ( currentObject.offsetParent) { do { ePosx += currentObject.offsetLeft; ePosy += currentObject.offsetTop; currentObject = currentObject.offsetParent; } while ( currentObject.offsetParent); } this.pointCollection.mousePos.setValue(mPosx - ePosx, mPosy - ePosy, 0); }; containerEl.onmouseleave = _e => { this.pointCollection.mousePos.setValue(-999, -999, -999); }; containerEl.setAttribute('style', `width:${this.props.width}px; height:${this.props.height}px`); this.pointCollection.loadFromSource( this.props.src, this.props.width, this.props.height, this.props.cellSize); this.timeout(); } private timeout(): void { const container: HTMLDivElement | null = this.containerRef.current; if( !container) { return; } this.pointCollection.drawDiv(container); this.pointCollection.update(); setTimeout(() => this.timeout(), 30); } }
joejensen/react-bouncing-balls
src/Point.tsx
import {Vector} from './vector'; /** * A point tracks the size and position of each ball */ export class Point { public curPos: Vector; public friction: number; public originalPos: Vector; public radius: number; public size: number; public springStrength: number; public targetPos: Vector; public velocity: Vector; public color: string; // References used only by the div renderer private ballDiv: Element; constructor(x: number, y: number, z: number, size: number, color: string) { this.curPos = new Vector(x, y, z); this.size = size; this.color = color; this.friction = 0.8; this.originalPos = new Vector(x, y, z); this.radius = size; this.size = size; this.springStrength = 0.1; this.targetPos = new Vector(x, y, z); this.velocity = new Vector(0.0, 0.0, 0.0); } update(): void { const dx = this.targetPos.x - this.curPos.x; const ax = dx * this.springStrength; this.velocity.x += ax; this.velocity.x *= this.friction; this.curPos.x += this.velocity.x; const dy = this.targetPos.y - this.curPos.y; const ay = dy * this.springStrength; this.velocity.y += ay; this.velocity.y *= this.friction; this.curPos.y += this.velocity.y; const dox = this.originalPos.x - this.curPos.x; const doy = this.originalPos.y - this.curPos.y; const dd = (dox * dox) + (doy * doy); const d = Math.sqrt(dd); this.targetPos.z = d / 100 + 1; const dz = this.targetPos.z - this.curPos.z; const az = dz * this.springStrength; this.velocity.z += az; this.velocity.z *= this.friction; this.curPos.z += this.velocity.z; this.radius = this.size * this.curPos.z; if (this.radius < 1) { this.radius = 1; } } drawCanvas(cx: CanvasRenderingContext2D): void { cx.fillStyle = this.color; cx.beginPath(); cx.arc(this.curPos.x, this.curPos.y, this.radius, 0, Math.PI * 2, true); cx.fill(); } drawDiv( parent: Element): void { if (!this.ballDiv) { this.ballDiv = document.createElement('div'); this.ballDiv.classList.add('point'); parent.appendChild(this.ballDiv); } this.ballDiv.setAttribute('style', `background-color: ${this.color}; top: ${this.curPos.y - this.radius}px; left: ${this.curPos.x - this.radius}px; width: ${this.radius * 2}px; height: ${this.radius * 2}px`); } }
joejensen/react-bouncing-balls
src/BouncingBallsCanvas.tsx
/** * @class BouncingBallsCanvasComponent */ import * as React from 'react'; import {RefObject} from "react"; import {PointCollection} from "./PointCollection"; import {BouncingBallsDivProps} from "./BouncingBallsDiv"; export type BouncingBallsCanvasProps = { src: string; width: number; height: number; cellSize: number; } export default class BouncingBallsCanvasComponent extends React.Component<BouncingBallsCanvasProps> { static defaultProps: BouncingBallsDivProps = { src: '', width: 512, height: 512, cellSize: 20 }; private readonly canvasRef: RefObject<HTMLCanvasElement>; private readonly pointCollection: PointCollection = new PointCollection(); private cx: CanvasRenderingContext2D | null; constructor(props: BouncingBallsCanvasProps) { super(props); this.canvasRef = React.createRef(); } render() { return ( <canvas ref={this.canvasRef} className="react-bouncing-balls-canvas"/> ) } public componentDidMount(): void { const canvasEl: HTMLCanvasElement | null= this.canvasRef.current; if( !canvasEl) { return; } canvasEl.ontouchstart = e => { e.preventDefault(); }; canvasEl.ontouchmove = e => { e.preventDefault(); let mPosx = 0; let mPosy = 0; let ePosx = 0; let ePosy = 0; if (e.targetTouches[0].pageX || e.targetTouches[0].pageY) { mPosx = e.targetTouches[0].pageX; mPosy = e.targetTouches[0].pageY; } else if (e.targetTouches[0].clientX || e.targetTouches[0].clientY) { mPosx = e.targetTouches[0].clientX + document.body.scrollLeft + document.documentElement.scrollLeft; mPosy = e.targetTouches[0].clientY + document.body.scrollTop + document.documentElement.scrollTop; } let currentObject: any = canvasEl; if ( currentObject.offsetParent) { do { ePosx += currentObject.offsetLeft; ePosy += currentObject.offsetTop; currentObject = currentObject.offsetParent; } while ( currentObject.offsetParent); } this.pointCollection.mousePos.setValue(mPosx - ePosx, mPosy - ePosy, 0); }; canvasEl.ontouchend = e => { e.preventDefault(); this.pointCollection.mousePos.setValue(-999, -999, -999); }; canvasEl.ontouchcancel = e => { e.preventDefault(); this.pointCollection.mousePos.setValue(-999, -999, -999); }; canvasEl.onmousemove = e => { let mPosx = 0; let mPosy = 0; let ePosx = 0; let ePosy = 0; if (e.pageX || e.pageY) { mPosx = e.pageX; mPosy = e.pageY; } else if (e.clientX || e.clientY) { mPosx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; mPosy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } let currentObject: any = canvasEl; if ( currentObject.offsetParent) { do { ePosx += currentObject.offsetLeft; ePosy += currentObject.offsetTop; currentObject = currentObject.offsetParent; } while ( currentObject.offsetParent); } this.pointCollection.mousePos.setValue(mPosx - ePosx, mPosy - ePosy, 0); }; canvasEl.onmouseleave = _e => { this.pointCollection.mousePos.setValue(-999, -999, -999); }; this.cx = canvasEl.getContext('2d'); // set the width and height canvasEl.width = this.props.width; canvasEl.height = this.props.height; this.pointCollection.loadFromSource( this.props.src, this.props.width, this.props.height, this.props.cellSize); this.timeout(); } private timeout(): void { const canvasEl: HTMLCanvasElement | null = this.canvasRef.current; if (!canvasEl || !this.cx) { return; } this.cx.clearRect(0, 0, canvasEl.width, canvasEl.height); this.pointCollection.drawCanvas(this.cx); this.pointCollection.update(); setTimeout(() => this.timeout(), 30); } }
joejensen/react-bouncing-balls
src/PointCollection.tsx
import {Vector} from './vector'; import {Point} from './point'; /** * A collection of points / balls to be rendered to either a canvas or the dom as well as utilities to populate it */ export class PointCollection { public mousePos: Vector = new Vector(0, 0, 0); public points: Point[] = []; /** * Generates a css style color from the RGBA coordinates of a color */ private static toColor( r: number, g: number, b: number, a: number): string { return 'rgba(' + [r, g, b, a].join(',') + ')'; } /** * Adjusts a point to fit within the desired area */ private static scalePoint( p: Point, canvasWidth: number, canvasHeight: number, imageWidth: number, imageHeight: number): void { p.curPos.x = ((canvasWidth - imageWidth) / 2) + p.curPos.x; p.curPos.y = ((canvasHeight - imageHeight) / 2) + p.curPos.y; p.originalPos.x = ((canvasWidth - imageWidth) / 2) + p.originalPos.x; p.originalPos.y = ((canvasHeight - imageHeight) / 2) + p.originalPos.y; } /** * Determines the average color within the cell so we know the color of the ball, summing the squares gives a better looking color */ private static dominantColor( x: number, y: number, w: number, cellSize: number, data: Uint8ClampedArray): string | null { // Average the colors in the area let pixels = 0; let rSummed = 0; let gSummed = 0; let bSummed = 0; let aSummed = 0; for ( let localX = x; localX < x + cellSize; localX++) { for ( let localY = y; localY < y + cellSize; localY++) { const i = ((y * w) + x) * 4; if ( i < data.byteLength) { const r = data[i]; rSummed += r * r; const g = data[i + 1]; gSummed += g * g; const b = data[i + 2]; bSummed += b * b; const a = data[i + 3]; aSummed += a * a; pixels++; } } } const rFinal = Math.sqrt(rSummed / pixels); const gFinal = Math.sqrt(gSummed / pixels); const bFinal = Math.sqrt(bSummed / pixels); const aFinal = Math.sqrt(aSummed / pixels); if ( aFinal < 10 || (rFinal > 230 && gFinal > 230 && bFinal > 230)) { return null; } return PointCollection.toColor(rFinal, gFinal, bFinal, aFinal); } /** * Extracts point for an image into the point collection */ public loadFromSource( src: string, destWidth: number, destHeight: number, cellSize: number): void { const img = new Image(); img.crossOrigin = 'Anonymous'; img.onload = () => { const tempCanvas = document.createElement('canvas'); tempCanvas.className = 'ng-bouncing-balls-bg-canvas'; tempCanvas.width = img.width; tempCanvas.height = img.height; const context = tempCanvas.getContext('2d'); if( context != null) { context.drawImage(img, 0, 0, img.width, img.height); const pixels = context.getImageData(0, 0, img.width, img.height); this.pointsFromImage(pixels, destWidth, destHeight, cellSize); } }; img.onerror = (err) => { console.log(err); }; img.src = src; } private pointsFromImage( img: ImageData, destWidth: number, destHeight: number, cellSize: number): void { const realCellSize = Math.max( 1, cellSize); const cellRadius = Math.floor(realCellSize / 2); const cols = Math.ceil(img.width / realCellSize); const rows = Math.ceil(img.height / realCellSize); for ( let y = 0; y < rows; y++) { for ( let x = 0; x < cols; x++) { const cellX = x * realCellSize; const cellY = y * realCellSize; const color = PointCollection.dominantColor(cellX, cellY, img.width, realCellSize, img.data); if ( color) { const p = new Point(cellX + cellRadius, cellY + cellRadius, 0, cellRadius, color); PointCollection.scalePoint(p, destWidth, destHeight, img.width, img.height); this.points.push(p); } } } } /** * Triggers the per-frame updates to the point collection */ update(): void { for (const point of this.points) { const dx = this.mousePos.x - point.curPos.x; const dy = this.mousePos.y - point.curPos.y; const dd = (dx * dx) + (dy * dy); const d = Math.sqrt(dd); if (d < 150) { point.targetPos.x = (this.mousePos.x < point.curPos.x) ? point.curPos.x - dx : point.curPos.x - dx; point.targetPos.y = (this.mousePos.y < point.curPos.y) ? point.curPos.y - dy : point.curPos.y - dy; } else { point.targetPos.x = point.originalPos.x; point.targetPos.y = point.originalPos.y; } point.update(); } } /** * Draws the point collection to a canvas */ drawCanvas(cx: CanvasRenderingContext2D): void { for (const point of this.points) { point.drawCanvas(cx); } } /** * Draws the point collection to the DOM */ drawDiv(parent: Element): void { for (const point of this.points) { point.drawDiv(parent); } } }
joejensen/react-bouncing-balls
src/index.tsx
<reponame>joejensen/react-bouncing-balls import BouncingBallsCanvasComponent from './BouncingBallsCanvas'; import BouncingBallsDivComponent from './BouncingBallsDiv'; import './index.css'; export {BouncingBallsDivComponent, BouncingBallsCanvasComponent}; export default {BouncingBallsDivComponent, BouncingBallsCanvasComponent};
virginiah894/Quotes
src/app/highlight.directive.ts
import { Directive, ElementRef , HostListener} from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private elem:ElementRef) { // @HostListener("mouseenter") onmouseenter(){ // this.colorChange("red") // } // @HostListener("mouseleave") onmouseleave(){ // this.colorChange("aqua") // } // private colorChange(tap:string){ // this.elem.nativeElement.style.color=tap; // } this.elem.nativeElement.style.background="blue"; } }
virginiah894/Quotes
src/app/dates.pipe.ts
<reponame>virginiah894/Quotes<filename>src/app/dates.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'dates' }) export class DatesPipe implements PipeTransform { transform(value: any):number{ let today:Date = new Date(); //get current date and time let todayWithNoTime:any = new Date(today.getFullYear(), today.getMonth(), today.getDate()) var dateDifference = Math.abs(value - todayWithNoTime) //returns value in miliseconds const secondsInDay = 86400; //60 seconds * 60 minutes in an hour * 24 hours in a day var dateDifferenceSeconds = dateDifference*0.001; //converts miliseconds to seconds var dateCounter = Math.round(dateDifferenceSeconds/secondsInDay); var upDate =dateCounter/365 if (dateCounter >= 1 && value > todayWithNoTime){ return 0; }else{ return Math.round(upDate); } } }
virginiah894/Quotes
src/app/quote.ts
<gh_stars>1-10 export class Quote { showAuthor:boolean; constructor(public id:number,public name:string,public author:string,public datePublished:Date,public submitter:string, public upvote:number,public downvote:number,){ this.showAuthor=false; } }
syrflover/iterator-helper
deno/methods/min.ts
import { compare } from "../lib/compare/mod.ts"; import { minBy } from "./minBy.ts"; export function min<T>(iter: AsyncIterable<T>): Promise<T | undefined> { return minBy(compare, iter); }
syrflover/iterator-helper
deno/lib/iterable/toAsyncIterable.ts
<filename>deno/lib/iterable/toAsyncIterable.ts import { isArrayLikeOrString } from '../../types/guards/isArrayLikeOrString.ts'; import { toIterable } from './toIterable.ts'; export function toAsyncIterable<T>( iter: Iterable<T> | AsyncIterable<T> | Promise<Iterable<T>> | Promise<AsyncIterable<T>>, ): AsyncIterable<T> { const iter_ = (async function*() { const iter__ = await iter; const iter___ = isArrayLikeOrString(iter__) ? toIterable(iter__) : iter__; yield* iter___; })(); return { async *[Symbol.asyncIterator]() { yield* iter_; }, }; } /** * as toAsyncIterable */ export const sequence = toAsyncIterable;
syrflover/iterator-helper
src/lib/iterable/toAsyncIterable_test.ts
<filename>src/lib/iterable/toAsyncIterable_test.ts import { assertEquals, assert } from 'https://deno.land/std/testing/asserts.ts'; import { toAsyncIterable } from './mod.ts'; function* iterable(): Iterable<number> { yield 1; yield 2; yield 3; yield 4; } async function* asyncIterable(): AsyncIterable<number> { yield 1; yield 2; yield 3; yield 4; } Deno.test('toAsyncIterable() from Array', async () => { const actual: number[] = []; const expected = [1, 2, 3, 4]; const iter = toAsyncIterable([1, 2, 3, 4]); for await (const _ of iter) { actual.push(_); } assertEquals(actual, expected); assert(Symbol.asyncIterator in iter); }); Deno.test('toAsyncIterable() from Iterable', async () => { const actual: number[] = []; const expected = [1, 2, 3, 4]; const iter = toAsyncIterable(iterable()); for await (const _ of iter) { actual.push(_); } assertEquals(actual, expected); assert(Symbol.asyncIterator in iter); }); Deno.test('toAsyncIterable() from AsyncIterable', async () => { const actual: number[] = []; const expected = [1, 2, 3, 4]; const iter = toAsyncIterable(asyncIterable()); for await (const _ of iter) { actual.push(_); } assertEquals(actual, expected); assert(Symbol.asyncIterator in iter); }); Deno.test('toAsyncIterable() from Promise Array', async () => { const actual: number[] = []; const expected = [1, 2, 3, 4]; const iter = toAsyncIterable(Promise.resolve([1, 2, 3, 4])); for await (const _ of iter) { actual.push(_); } assertEquals(actual, expected); assert(Symbol.asyncIterator in iter); }); Deno.test('toAsyncIterable() from Promise Iterable', async () => { const actual: number[] = []; const expected = [1, 2, 3, 4]; const iter = toAsyncIterable(Promise.resolve(iterable())); for await (const _ of iter) { actual.push(_); } assertEquals(actual, expected); assert(Symbol.asyncIterator in iter); }); Deno.test('toAsyncIterable() from Promise AsyncIterable', async () => { const actual: number[] = []; const expected = [1, 2, 3, 4]; const iter = toAsyncIterable(Promise.resolve(asyncIterable())); for await (const _ of iter) { actual.push(_); } assertEquals(actual, expected); assert(Symbol.asyncIterator in iter); }); Deno.test('toAsyncIterable() from String', async () => { const actual: string[] = []; const expected = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']; const iter = toAsyncIterable('hello world'); for await (const _ of iter) { actual.push(_); } assertEquals(actual, expected); assert(Symbol.asyncIterator in iter); });
syrflover/iterator-helper
deno/lib/iterable/init.ts
import { initLast } from './initLast.ts'; export async function* init<T>(iter: AsyncIterable<T>) { const [r] = await initLast(iter); yield* r; }
syrflover/iterator-helper
deno/methods/scan.ts
<reponame>syrflover/iterator-helper import type { ScanFn } from "../types/functions/mod.ts"; import { _curry, Curry2 } from "../lib/utils/mod.ts"; async function* _scan_impl_fn<A, B>( fn: ScanFn<A, B>, init: B | Promise<B>, iter: AsyncIterable<A>, ): AsyncIterable<B> { let state = await init; yield state; for await (const elem of iter) { state = await fn(state, elem); yield state; } } export interface Scan { <A, B>( fn: ScanFn<A, B>, init: B | Promise<B>, iter: AsyncIterable<A>, ): AsyncIterable<B>; <A, B>( fn: ScanFn<A, B>, init: B | Promise<B>, ): (iter: AsyncIterable<A>) => AsyncIterable<B>; <A, B>( fn: ScanFn<A, B>, ): Curry2<B | Promise<B>, AsyncIterable<A>, AsyncIterable<B>>; } export const scan: Scan = _curry(_scan_impl_fn);
syrflover/iterator-helper
deno/lib/utils/curry.ts
export function curry<P1, P2, R>(f: (p1: P1, p2: P2) => R): Curry2<P1, P2, R>; export function curry<P1, P2, P3, R>(f: (p1: P1, p2: P2, p3: P3) => R): Curry3<P1, P2, P3, R>; export function curry<P1, P2, P3, P4, R>(f: (p1: P1, p2: P2, p3: P3, p4: P4) => R): Curry4<P1, P2, P3, P4, R>; export function curry<P1, P2, P3, P4, P5, R>(f: (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5) => R): Curry5<P1, P2, P3, P4, P5, R>; export function curry<P1, P2, P3, P4, P5, P6, R>( f: (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6) => R, ): Curry6<P1, P2, P3, P4, P5, P6, R>; export function curry<P1, P2, P3, P4, P5, P6, P7, R>( f: (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7) => R, ): Curry7<P1, P2, P3, P4, P5, P6, P7, R>; export function curry<P1, P2, P3, P4, P5, P6, P7, P8, R>( f: (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8) => R, ): Curry8<P1, P2, P3, P4, P5, P6, P7, P8, R>; export function curry<P1, P2, P3, P4, P5, P6, P7, P8, P9, R>( f: (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9) => R, ): Curry9<P1, P2, P3, P4, P5, P6, P7, P8, P9, R>; export function curry<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, R>( f: (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10) => R, ): Curry10<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, R>; export function curry(fn: (...args: any[]) => any) { return (...args: any[]) => { if (fn.length > args.length) { return (...nextArgs: any[]) => (curry(fn) as any)(...args, ...nextArgs); } return fn(...args); }; } export function _curry(fn: (...args: any[]) => any) { return (...args: any[]) => { if (fn.length > args.length) { return (...nextArgs: any[]) => (curry(fn) as any)(...args, ...nextArgs); } return fn(...args); }; } export interface Curry2<P1, P2, R> { (p1: P1): (p2: P2) => R; (p1: P1, p2: P2): R; } export interface Curry3<P1, P2, P3, R> { (p1: P1): Curry2<P2, P3, R>; (p1: P1, p2: P2): (p3: P3) => R; (p1: P1, p2: P2, p3: P3): R; } export interface Curry4<P1, P2, P3, P4, R> { (p1: P1): Curry3<P2, P3, P4, R>; (p1: P1, p2: P2): Curry2<P3, P4, R>; (p1: P1, p2: P2, p3: P3): (p4: P4) => R; (p1: P1, p2: P2, p3: P3, p4: P4): R; } export interface Curry5<P1, P2, P3, P4, P5, R> { (p1: P1): Curry4<P2, P3, P4, P5, R>; (p1: P1, p2: P2): Curry3<P3, P4, P5, R>; (p1: P1, p2: P2, p3: P3): Curry2<P4, P5, R>; (p1: P1, p2: P2, p3: P3, p4: P4): (p5: P5) => R; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5): R; } export interface Curry6<P1, P2, P3, P4, P5, P6, R> { (p1: P1): Curry5<P2, P3, P4, P5, P6, R>; (p1: P1, p2: P2): Curry4<P3, P4, P5, P6, R>; (p1: P1, p2: P2, p3: P3): Curry3<P4, P5, P6, R>; (p1: P1, p2: P2, p3: P3, p4: P4): Curry2<P5, P6, R>; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5): (p6: P6) => R; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6): R; } export interface Curry7<P1, P2, P3, P4, P5, P6, P7, R> { (p1: P1): Curry6<P2, P3, P4, P5, P6, P7, R>; (p1: P1, p2: P2): Curry5<P3, P4, P5, P6, P7, R>; (p1: P1, p2: P2, p3: P3): Curry4<P4, P5, P6, P7, R>; (p1: P1, p2: P2, p3: P3, p4: P4): Curry3<P5, P6, P7, R>; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5): Curry2<P6, P7, R>; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6): (p7: P7) => R; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7): R; } export interface Curry8<P1, P2, P3, P4, P5, P6, P7, P8, R> { (p1: P1): Curry7<P2, P3, P4, P5, P6, P7, P8, R>; (p1: P1, p2: P2): Curry6<P3, P4, P5, P6, P7, P8, R>; (p1: P1, p2: P2, p3: P3): Curry5<P4, P5, P6, P7, P8, R>; (p1: P1, p2: P2, p3: P3, p4: P4): Curry4<P5, P6, P7, P8, R>; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5): Curry3<P6, P7, P8, R>; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6): Curry2<P7, P8, R>; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7): (p8: P8) => R; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8): R; } export interface Curry9<P1, P2, P3, P4, P5, P6, P7, P8, P9, R> { (p1: P1): Curry8<P2, P3, P4, P5, P6, P7, P8, P9, R>; (p1: P1, p2: P2): Curry7<P3, P4, P5, P6, P7, P8, P9, R>; (p1: P1, p2: P2, p3: P3): Curry6<P4, P5, P6, P7, P8, P9, R>; (p1: P1, p2: P2, p3: P3, p4: P4): Curry5<P5, P6, P7, P8, P9, R>; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5): Curry4<P6, P7, P8, P9, R>; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6): Curry3<P7, P8, P9, R>; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7): Curry2<P8, P9, R>; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8): (p9: P9) => R; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9): R; } export interface Curry10<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, R> { (p1: P1): Curry9<P2, P3, P4, P5, P6, P7, P8, P9, P10, R>; (p1: P1, p2: P2): Curry8<P3, P4, P5, P6, P7, P8, P9, P10, R>; (p1: P1, p2: P2, p3: P3): Curry7<P4, P5, P6, P7, P8, P9, P10, R>; (p1: P1, p2: P2, p3: P3, p4: P4): Curry6<P5, P6, P7, P8, P9, P10, R>; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5): Curry5<P6, P7, P8, P9, P10, R>; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6): Curry4<P7, P8, P9, P10, R>; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7): Curry3<P8, P9, P10, R>; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8): Curry2<P9, P10, R>; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9): (p10: P10) => R; (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, p10: P10): R; }
syrflover/iterator-helper
src/types/guards/isIterable_test.ts
<filename>src/types/guards/isIterable_test.ts<gh_stars>1-10 import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { isIterable } from './mod.ts'; function* iterable() { yield 1; yield 2; yield 3; yield 4; } async function* asyncIterable() { yield 1; yield 2; yield 3; yield 4; } Deno.test('isIterable() Array == true', () => { const actual = isIterable([1, 2, 3, 4]); const expected = true; assertEquals(actual, expected); }); Deno.test('isIterable() Iterable == true', () => { const actual = isIterable(iterable()); const expected = true; assertEquals(actual, expected); }); Deno.test('isIterable() AsyncIterable == false', () => { const actual = isIterable(asyncIterable()); const expected = false; assertEquals(actual, expected); }); Deno.test('isIterable() undefined == false', () => { const actual = isIterable(undefined); const expected = false; assertEquals(actual, expected); });
syrflover/iterator-helper
src/methods/cycle.ts
import { getLogger } from '../logger.ts'; const logger = await getLogger('methods/cycle'); async function* _cycle_impl_fn<T>(iter: AsyncIterable<T>): AsyncIterable<T> { logger.trace('cycle()'); const r: T[] = []; for await (const elem of iter) { yield elem; r.push(elem); } while (true) { yield* r; } } export function cycle<T>(iter: AsyncIterable<T>): AsyncIterable<T> { return _cycle_impl_fn(iter); }
syrflover/iterator-helper
src/types/guards/isString_test.ts
<gh_stars>1-10 import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { isString } from './mod.ts'; Deno.test('isString() string', () => { const actual = isString('hello'); const expected = true; assertEquals(actual, expected); }); Deno.test('isString() array', () => { const actual = isString(['hello', 'world']); const expected = false; assertEquals(actual, expected); }); Deno.test('isString() undefined', () => { const actual = isString(undefined); const expected = false; assertEquals(actual, expected); });
syrflover/iterator-helper
scripts/lib/readDir.ts
<gh_stars>1-10 /* eslint-disable */ export async function* readDir(dir: string, ex: string[] = []): AsyncIterable<string> { const files = Deno.readDir(dir); // const entries: string[] = []; for await (const file of files) { try { if (ex.includes(`${dir}/${file.name}`)) { continue; } const stat = await Deno.stat(`${dir}/${file.name}`); if (stat.isFile) { yield `${dir}/${file.name}`; // entries.push(`${dir}/${file.name}`); } else if (stat.isDirectory) { const entries_d = readDir(`${dir}/${file.name}`, ex); yield* entries_d; // entries.push(...entries_d); } } catch (error) { console.error(error); throw error; } } // yield entries; }
syrflover/iterator-helper
src/lib/utils/flip_test.ts
<filename>src/lib/utils/flip_test.ts<gh_stars>1-10 import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { flip } from './mod.ts'; Deno.test('flip() div', () => { const actual = flip((a, b) => a / b, 1, 2); const expected = 2 / 1; assertEquals(actual, expected); });
syrflover/iterator-helper
deno/lib/utils/flip.ts
// (A -> B -> C) -> B -> A -> C export function flip<A, B, C>(fn: (a: A, b: B) => C, b: B, a: A) { return fn(a, b); }
syrflover/iterator-helper
deno/lib/compare/compare.ts
<filename>deno/lib/compare/compare.ts import { Ord } from '../../types/ordering.ts'; export function compare<T>(a: T, b: T): Ord { if (a < b) { return Ord.Less; } if (a > b) { return Ord.Greater; } return Ord.Equal; }
syrflover/iterator-helper
deno/methods/take.ts
<reponame>syrflover/iterator-helper<filename>deno/methods/take.ts import { _curry } from "../lib/utils/mod.ts"; async function* _take_impl_fn<T>( limit: number, iter: AsyncIterable<T>, ): AsyncIterable<T> { let current = 1; for await (const elem of iter) { if (current > limit) { return; } yield elem; current += 1; } } export interface Take { <T>(limit: number, iter: AsyncIterable<T>): AsyncIterable<T>; <T>(limit: number): (iter: AsyncIterable<T>) => AsyncIterable<T>; } export const take: Take = _curry(_take_impl_fn);
syrflover/iterator-helper
src/types/guards/isArrayLike.ts
export function isTypedArray(a: any) { return ArrayBuffer.isView(a); } export function isArrayLike(a: any): a is any[] { return Array.isArray(a) || isTypedArray(a); }
syrflover/iterator-helper
src/methods/inspect_test.ts
import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { iterator } from '../mod.ts'; Deno.test('inspect() [1, 2, 3, 4]', async () => { const a = iterator([1, 4, 2, 3]); const actual: number[] = []; const expected = [1, 4, 2, 3]; const i = a.inspect((e) => { actual.push(e); }); for await (const _ of i) { (() => {})(); } assertEquals(actual, expected); }); Deno.test('inspect() [1,4,2,3].filter(isEven)', async () => { const a = iterator([1, 4, 2, 3]); const actual: number[] = []; const expected = [4, 2]; const i = a .filter((e) => e % 2 === 0) .inspect((e) => { actual.push(e); }); for await (const _ of i) { (() => {})(); } assertEquals(actual, expected); });
syrflover/iterator-helper
src/methods/unzip_test.ts
<reponame>syrflover/iterator-helper import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import type { Pair } from '../types/mod.ts'; import { iterator } from '../mod.ts'; Deno.test('unzip() [[1, 5], [2, 6], [3, 7], [4, 8]]', async () => { const a = iterator<Pair<number, number>>([ [1, 5], [2, 6], [3, 7], [4, 8], ]); const actual_left: number[] = []; const expected_left = [1, 2, 3, 4]; const actual_right: number[] = []; const expected_right = [5, 6, 7, 8]; const [left, right] = await a.unzip(); for await (const _ of left) { actual_left.push(_); } for await (const _ of right) { actual_right.push(_); } assertEquals(actual_left, expected_left); assertEquals(actual_right, expected_right); }); Deno.test(`unzip() [[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd']]`, async () => { const a = iterator<Pair<number, string>>([ [1, 'a'], [2, 'b'], [3, 'c'], [4, 'd'], ]); const actual_left: number[] = []; const expected_left = [1, 2, 3, 4]; const actual_right: string[] = []; const expected_right = ['a', 'b', 'c', 'd']; const [left, right] = await a.unzip(); for await (const _ of left) { actual_left.push(_); } for await (const _ of right) { actual_right.push(_); } assertEquals(actual_left, expected_left); assertEquals(actual_right, expected_right); }); Deno.test(`unzip() [1,2,3,4].zip(['a','b','c','d'])`, async () => { const a = iterator([1, 2, 3, 4]); const actual_left: number[] = []; const expected_left = [1, 2, 3, 4]; const actual_right: string[] = []; const expected_right = ['a', 'b', 'c', 'd']; const [left, right] = await a.zip(['a', 'b', 'c', 'd']).unzip(); for await (const _ of left) { actual_left.push(_); } for await (const _ of right) { actual_right.push(_); } assertEquals(actual_left, expected_left); assertEquals(actual_right, expected_right); });
syrflover/iterator-helper
src/methods/max.ts
import { getLogger } from '../logger.ts'; import { compare } from '../lib/compare/mod.ts'; import { maxBy } from './maxBy.ts'; const logger = await getLogger('methods/max'); export function max<T>(iter: AsyncIterable<T>): Promise<T | undefined> { logger.trace('max()'); return maxBy(compare, iter); }
syrflover/iterator-helper
deno/methods/average.ts
import { Pair, pair } from "../types/mod.ts"; import { fold } from "./fold.ts"; export async function _average_impl_fn(iter: AsyncIterable<number>) { const [count, summed] = await fold( ([current, value]: Pair<number, number>, e: number) => pair(current + 1, value + e), pair(0, 0), iter, ); return count === 0 ? 0 : summed / count; } export function average(iter: AsyncIterable<number>) { return _average_impl_fn(iter); }
syrflover/iterator-helper
deno/lib/compare/min.ts
<filename>deno/lib/compare/min.ts import { id } from '../utils/mod.ts'; import { compare } from './compare.ts'; import { minBy } from './minBy.ts'; export function min<T>(a: T, b: T): Promise<T> { return minBy(id, compare, a, b); }
syrflover/iterator-helper
src/methods/find_test.ts
<filename>src/methods/find_test.ts import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { iterator } from '../mod.ts'; Deno.test('find(3) === 3', async () => { const a = iterator([1, 2, 3, 4, 5]); const actual = await a.find((e) => e === 3); const expected = 3; assertEquals(actual, expected); }); Deno.test('find(6) === undefined', async () => { const a = iterator([1, 2, 3, 4, 5]); const actual = await a.find((e) => e === 6); const expected = undefined; assertEquals(actual, expected); });
syrflover/iterator-helper
deno/methods/map.ts
import type { MapFn } from "../types/functions/mod.ts"; import { _curry } from "../lib/utils/mod.ts"; async function* _map_impl_fn<T, R>( fn: MapFn<T, R>, iter: AsyncIterable<T>, ): AsyncIterable<R> { for await (const elem of iter) { const mapped = await fn(elem); yield mapped; } } export interface Map { <T, R>(fn: MapFn<T, R>, iter: AsyncIterable<T>): AsyncIterable<R>; <T, R>(fn: MapFn<T, R>): (iter: AsyncIterable<T>) => AsyncIterable<R>; } export const map: Map = _curry(_map_impl_fn);
syrflover/iterator-helper
src/lib/iterable/init_test.ts
import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { init } from './mod.ts'; async function* asyncIterable() { yield 1; yield 2; yield 3; yield 4; } Deno.test('init() [1, 2, 3, 4]', async () => { const actual: number[] = []; const expected = [1, 2, 3]; for await (const _ of init(asyncIterable())) { actual.push(_); } assertEquals(actual, expected); });
syrflover/iterator-helper
scripts/deno_build.ts
/* eslint-disable */ import { dirname } from 'https://deno.land/std/path/mod.ts'; import { readDir } from './lib/readDir.ts'; const encoder = new TextEncoder(); const decoder = new TextDecoder('utf8'); const entries = readDir('src', ['src/playground.ts', 'src/logger.ts']); for await (const entry of entries) { if (entry.endsWith('_test.ts')) { continue; } const code = await Deno.readFile(entry); const to = decoder .decode(code) .replace(/const logger.+;/, '') .replace(/import { getLogger } from \'.+logger\.ts\';/, '') .replace(/logger\..+\(.+\);/g, ''); const filepath = entry.replace(/src/, 'deno'); const dir = dirname(filepath); await Deno.mkdir(dir, { recursive: true }); await Deno.writeFile(filepath, encoder.encode(to)); }
syrflover/iterator-helper
src/methods/product.ts
<gh_stars>1-10 import { getLogger } from '../logger.ts'; import { fold } from './fold.ts'; const logger = await getLogger('methods/product'); export function product(iter: AsyncIterable<number>): Promise<number> { logger.trace('product()'); return fold((acc, e) => acc * e, 1, iter); }
syrflover/iterator-helper
src/types/guards/isNull_test.ts
<filename>src/types/guards/isNull_test.ts import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { isNull } from './mod.ts'; Deno.test('isNull() null', () => { const actual = isNull(null); const expected = true; assertEquals(actual, expected); }); Deno.test('isNull() undefined', () => { const actual = isNull(undefined); const expected = true; assertEquals(actual, expected); }); Deno.test('isNull() NaN', () => { const actual = isNull(NaN); const expected = true; assertEquals(actual, expected); }); Deno.test('isNull() string', () => { const actual = isNull(''); const expected = false; assertEquals(actual, expected); }); Deno.test('isNull() number', () => { const actual = isNull(0); const expected = false; assertEquals(actual, expected); }); Deno.test('isNull() array', () => { const actual = isNull(['hello', 'world']); const expected = false; assertEquals(actual, expected); }); Deno.test('isNull() object', () => { const actual = isNull({ a: 1 }); const expected = false; assertEquals(actual, expected); });
syrflover/iterator-helper
deno/methods/zip.ts
<gh_stars>1-10 import { Pair, pair } from "../types/mod.ts"; import { next_async, sequence } from "../lib/iterable/mod.ts"; import { _curry } from "../lib/utils/mod.ts"; async function* _zip_impl_fn<T, U>( other: AsyncIterable<U | Promise<U>>, iter: AsyncIterable<T>, ): AsyncIterable<Pair<T, U>> { for await (const elem of iter) { const { done: other_done, value: other_value } = await next_async(other); if (other_done) { return; } yield pair(elem, other_value as U); } } export interface Zip { <T, U>( other: Iterable<U | Promise<U>> | AsyncIterable<U | Promise<U>>, iter: AsyncIterable<T>, ): AsyncIterable<Pair<T, U>>; <T, U>( other: Iterable<U | Promise<U>> | AsyncIterable<U | Promise<U>>, ): (iter: AsyncIterable<T>) => AsyncIterable<Pair<T, U>>; } export const zip: Zip = _curry( <T, U>( other: Iterable<U | Promise<U>> | AsyncIterable<U | Promise<U>>, iter: AsyncIterable<T>, ) => { const other_ = sequence(other); return _zip_impl_fn(other_, iter); }, );
syrflover/iterator-helper
src/methods/scan_test.ts
import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { iterator } from '../mod.ts'; Deno.test('scan() state + elem', async () => { const a = iterator([1, 2, 3, Promise.resolve(4), 5]); const actual_elements: number[] = []; const expected_elements = [1, 2, 3, 4, 5]; const actual_result: number[] = []; const expected_result = [1, 2, 4, 7, 11, 16]; for await (const _ of a.scan(Promise.resolve(1), (st, e) => { actual_elements.push(e); return st + e; })) { actual_result.push(_); } assertEquals(actual_elements, expected_elements); assertEquals(actual_result, expected_result); }); Deno.test('scan() `${state}${elem}`', async () => { const a = iterator([1, 2, 3, Promise.resolve(4), 5]); const actual_elements: number[] = []; const expected_elements = [1, 2, 3, 4, 5]; const actual_result: string[] = []; const expected_result = ['1', '11', '112', '1123', '11234', '112345']; for await (const _ of a.scan('1', (st, e) => { actual_elements.push(e); return `${st}${e}`; })) { actual_result.push(_); } assertEquals(actual_elements, expected_elements); assertEquals(actual_result, expected_result); });
syrflover/iterator-helper
src/types/guards/isPromise.ts
<filename>src/types/guards/isPromise.ts import { isNull } from './isNull.ts'; export function isPromise(a: any): a is Promise<any> { return isNull(a) ? false : a.constructor === Promise; }
syrflover/iterator-helper
src/lib/iterable/initLast_test.ts
<reponame>syrflover/iterator-helper<filename>src/lib/iterable/initLast_test.ts /* eslint no-empty-function: "off" */ import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { initLast } from './mod.ts'; async function* asyncIterable(): AsyncIterable<number> { yield 1; yield 2; yield 3; yield 4; } async function* emptyAsyncIterable() {} Deno.test('initLast() [1, 2, 3, 4]', async () => { const [init, last] = await initLast(asyncIterable()); const actual_init: number[] = []; const expected_init = [1, 2, 3]; const actual_last = last; const expected_last = 4; for await (const _ of init) { actual_init.push(_); } assertEquals(actual_init, expected_init); assertEquals(actual_last, expected_last); }); Deno.test('initLast() empty', async () => { const [init, last] = await initLast(emptyAsyncIterable()); const actual_init: number[] = []; const expected_init: number[] = []; const actual_last = last; const expected_last = undefined; for await (const _ of init) { actual_init.push(_); } assertEquals(actual_init, expected_init); assertEquals(actual_last, expected_last); });
syrflover/iterator-helper
deno/lib/iterable/toIterable.ts
<filename>deno/lib/iterable/toIterable.ts export function* toIterable<T>(iter: Iterable<T>): Iterable<T> { yield* iter; }
syrflover/iterator-helper
src/methods/fold1.ts
import type { FoldFn } from '../types/functions/mod.ts'; import { getLogger } from '../logger.ts'; import { next_async } from '../lib/iterable/mod.ts'; import { _curry } from '../lib/utils/mod.ts'; import { fold } from './fold.ts'; const logger = await getLogger('methods/fold1'); async function _fold1_impl_fn<T>(fn: FoldFn<T, T>, iter: AsyncIterable<T>) { logger.trace('fold1()'); const { done, value: head } = await next_async(iter); logger.debug('done =', done); logger.debug('value =', head); if (done) { throw new Error('Least one element is required in Iterator'); } return fold(fn, head, iter); } export interface Fold1 { <T>(fn: FoldFn<T, T>, iter: AsyncIterable<T>): Promise<T>; <T>(fn: FoldFn<T, T>): (iter: AsyncIterable<T>) => Promise<T>; } export const fold1: Fold1 = _curry(_fold1_impl_fn);
syrflover/iterator-helper
deno/types/global.ts
import type { EP } from "./promise.ts"; import { iterator, ToAsyncIterator } from "../mod.ts"; declare global { interface String { iter(): ToAsyncIterator<string>; } interface Array<T> { iter(): ToAsyncIterator<EP<T>>; } interface Int8Array { iter(): ToAsyncIterator<number>; } interface Int16Array { iter(): ToAsyncIterator<number>; } interface Int32Array { iter(): ToAsyncIterator<number>; } interface Uint8Array { iter(): ToAsyncIterator<number>; } interface Uint8ClampedArray { iter(): ToAsyncIterator<number>; } interface Uint16Array { iter(): ToAsyncIterator<number>; } interface Uint32Array { iter(): ToAsyncIterator<number>; } interface Float32Array { iter(): ToAsyncIterator<number>; } interface Float64Array { iter(): ToAsyncIterator<number>; } } String.prototype.iter = function () { return iterator(this); }; Array.prototype.iter = function () { return iterator(this); }; Int8Array.prototype.iter = function () { return iterator(this); }; Int16Array.prototype.iter = function () { return iterator(this); }; Int32Array.prototype.iter = function () { return iterator(this); }; Uint8Array.prototype.iter = function () { return iterator(this); }; Uint8ClampedArray.prototype.iter = function () { return iterator(this); }; Uint16Array.prototype.iter = function () { return iterator(this); }; Uint32Array.prototype.iter = function () { return iterator(this); }; Float32Array.prototype.iter = function () { return iterator(this); }; Float64Array.prototype.iter = function () { return iterator(this); };
syrflover/iterator-helper
src/methods/chain.ts
import { getLogger } from '../logger.ts'; import { _curry } from '../lib/utils/mod.ts'; const logger = await getLogger('methods/chain'); async function* _chain_impl_fn<T>(other: Iterable<T | Promise<T>> | AsyncIterable<T | Promise<T>>, iter: AsyncIterable<T>): AsyncIterable<T> { logger.trace('chain()'); yield* iter; yield* other; } export interface Chain { <T>(other: Iterable<T | Promise<T>> | AsyncIterable<T | Promise<T>>, iter: AsyncIterable<T>): AsyncIterable<T>; <T>(other: Iterable<T | Promise<T>> | AsyncIterable<T | Promise<T>>): (iter: AsyncIterable<T>) => AsyncIterable<T>; } export const chain: Chain = _curry(_chain_impl_fn);
syrflover/iterator-helper
src/methods/any_test.ts
<filename>src/methods/any_test.ts import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import type { Pair } from '../types/mod.ts'; import { iterator } from '../mod.ts'; Deno.test('any() x > 0', async () => { const a = iterator([1, 2, 3]); const actual: Pair<boolean, number[]> = [await a.any((e) => e > 0), []]; const expected: Pair<boolean, number[]> = [true, [2, 3]]; for await (const _ of a) { actual[1].push(_); } assertEquals(actual, expected); }); Deno.test('any() x > 1', async () => { const a = iterator([1, 2, 3]); const actual: Pair<boolean, number[]> = [await a.any((e) => e > 1), []]; const expected: Pair<boolean, number[]> = [true, [3]]; for await (const _ of a) { actual[1].push(_); } assertEquals(actual, expected); }); Deno.test('any() x > 2', async () => { const a = iterator([1, 2, 3]); const actual: Pair<boolean, number[]> = [await a.any((e) => e > 2), []]; const expected: Pair<boolean, number[]> = [true, []]; for await (const _ of a) { actual[1].push(_); } assertEquals(actual, expected); }); Deno.test('any() x > 3', async () => { const a = iterator([1, 2, 3]); const actual: Pair<boolean, number[]> = [await a.any((e) => e > 3), []]; const expected: Pair<boolean, number[]> = [false, []]; for await (const _ of a) { actual[1].push(_); } assertEquals(actual, expected); }); Deno.test('any() empty iter', async () => { const a = iterator<number>([]); const actual: Pair<boolean, number[]> = [await a.any((e) => e > 2), []]; const expected: Pair<boolean, number[]> = [false, []]; for await (const _ of a) { actual[1].push(_); } assertEquals(actual, expected); });
syrflover/iterator-helper
src/methods/stepBy_test.ts
import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { iterator } from '../mod.ts'; Deno.test('stepBy(2)', async () => { const a = iterator([0, 1, 2, 3, 4, 5]); const actual: number[] = []; const expected = [0, 2, 4]; const it = a.stepBy(2); for await (const _ of it) { actual.push(_); } assertEquals(actual, expected); }); Deno.test('stepBy(Infinity)', async () => { const a = iterator([0, 1, 2, 3, 4, 5]); const actual: number[] = []; const expected = [0]; const it = a.stepBy(Infinity); for await (const _ of it) { actual.push(_); } assertEquals(actual, expected); }); Deno.test('stepBy() empty iter', async () => { const a = iterator<number>([]); const actual: number[] = []; const expected: number[] = []; const it = a.stepBy(2); for await (const _ of it) { actual.push(_); } assertEquals(actual, expected); });
syrflover/iterator-helper
src/lib/iterable/next_test.ts
import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { next_sync, next_async } from './mod.ts'; function* iterable(): Iterable<number> { yield 1; yield 2; yield 3; } Deno.test('prepend(0, [1])', async () => { const it = iterable(); assertEquals(next_sync(it), { done: false, value: 1 }); assertEquals(next_sync(it), { done: false, value: 2 }); assertEquals(next_sync(it), { done: false, value: 3 }); assertEquals(next_sync(it), { done: true, value: undefined }); });
syrflover/iterator-helper
deno/methods/any.ts
import type { PredicateFn } from "../types/functions/mod.ts"; import { _curry } from "../lib/utils/mod.ts"; async function _any_impl_fn<T>( fn: PredicateFn<T>, iter: AsyncIterable<T>, ): Promise<boolean> { for await (const elem of iter) { const condition = await fn(elem); if (condition) { return true; } } return false; } /* export function _any<T>(fn: PredicateFn<T>, iter: AsyncIterable<T>) { return _any_impl_fn(iter, fn); } */ export interface Any { <T>(fn: PredicateFn<T>, iter: AsyncIterable<T>): Promise<boolean>; <T>(fn: PredicateFn<T>): (iter: AsyncIterable<T>) => Promise<boolean>; } export const any: Any = _curry(_any_impl_fn);
syrflover/iterator-helper
src/methods/flatten_test.ts
import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { iterator } from '../mod.ts'; Deno.test('flatten() [1,2,3,Promise<4>,5,[Promise<6>,7],AsyncIterator_<8,9>,10]', async () => { const a = iterator([1, 2, 3, Promise.resolve(4), 5, [Promise.resolve(6), 7], iterator([8, 9]), 10]); const actual: number[] = []; const expected = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for await (const _ of a.flatten()) { actual.push(_); } assertEquals(actual, expected); }); Deno.test('flatten() [1,[2, [3]]] == [1, 2, [3]]', async () => { const a = iterator([1, [2, [3]]]); const actual: (number | number[])[] = []; const expected = [1, 2, [3]]; for await (const _ of a.flatten()) { actual.push(_); } assertEquals(actual, expected); }); Deno.test('flatten() [1,2,3] == [1,2,3]', async () => { const a = iterator([1, 2, 3]); const actual: number[] = []; const expected = [1, 2, 3]; for await (const _ of a.flatten()) { actual.push(_); } assertEquals(actual, expected); });
syrflover/iterator-helper
deno/methods/unzip.ts
import { Pair, pair } from "../types/mod.ts"; import { append, sequence } from "../lib/iterable/mod.ts"; import { fold } from "./fold.ts"; async function _unzip_impl_fn<T, U>( iter: AsyncIterable<Pair<T, U>>, ): Promise<Pair<AsyncIterable<T>, AsyncIterable<U>>> { return fold( (acc, elem) => { const [left_iter, right_iter] = acc; const [left_value, right_value] = elem; return pair( append(left_value, left_iter), append(right_value, right_iter), ); }, pair(sequence<T>([]), sequence<U>([])), iter, ); } export function unzip<T, U>( iter: AsyncIterable<Pair<T, U>>, ): Promise<Pair<AsyncIterable<T>, AsyncIterable<U>>> { return _unzip_impl_fn(iter); }
syrflover/iterator-helper
src/methods/filterMap_test.ts
<filename>src/methods/filterMap_test.ts import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { iterator } from '../mod.ts'; Deno.test('filterMap() parseInt', async () => { const a = iterator(['a', 'b', '1', '2', '3', 'c', '4', 'd']); const actual: number[] = []; const expected = [1, 2, 3, 4]; for await (const _ of a.filterMap((e) => parseInt(e, 10))) { actual.push(_); } assertEquals(actual, expected); });
syrflover/iterator-helper
src/methods/count.ts
<filename>src/methods/count.ts<gh_stars>1-10 import { getLogger } from '../logger.ts'; import { fold } from './fold.ts'; const logger = await getLogger('methods/count'); // [a] -> Int export function count<T>(iter: AsyncIterable<T>): Promise<number> { logger.trace('count()'); return fold((count_: number) => count_ + 1, 0, iter); }
syrflover/iterator-helper
deno/methods/position.ts
import type { PredicateFn } from "../types/functions/mod.ts"; import { _curry } from "../lib/utils/mod.ts"; async function _position_impl_fn<T>( fn: PredicateFn<T>, iter: AsyncIterable<T>, ): Promise<number | undefined> { let pos = 0; for await (const elem of iter) { const condition = await fn(elem); if (condition) { return pos; } pos += 1; } } export interface Position { <T>(fn: PredicateFn<T>, iter: AsyncIterable<T>): Promise<number | undefined>; <T>( fn: PredicateFn<T>, ): (iter: AsyncIterable<T>) => Promise<number | undefined>; } export const position: Position = _curry(_position_impl_fn);
syrflover/iterator-helper
bench/main.ts
<filename>bench/main.ts import { bench, runIfMain } from 'https://deno.land/std/testing/bench.ts'; import { filter_bench_0, filter_bench_1, filter_bench_2, filter_bench_3 } from './filter.ts'; const benchmarks = [filter_bench_0, filter_bench_1, filter_bench_2, filter_bench_3]; for (const fn of benchmarks) { bench(fn()); } runIfMain(import.meta, { skip: /throw/ });
syrflover/iterator-helper
src/methods/map.ts
<reponame>syrflover/iterator-helper<gh_stars>1-10 import type { MapFn } from '../types/functions/mod.ts'; import { getLogger } from '../logger.ts'; import { _curry } from '../lib/utils/mod.ts'; const logger = await getLogger('methods/map'); async function* _map_impl_fn<T, R>(fn: MapFn<T, R>, iter: AsyncIterable<T>): AsyncIterable<R> { logger.trace('map()'); for await (const elem of iter) { const mapped = await fn(elem); logger.debug('element =', elem); logger.debug('mapped =', mapped); yield mapped; } } export interface Map { <T, R>(fn: MapFn<T, R>, iter: AsyncIterable<T>): AsyncIterable<R>; <T, R>(fn: MapFn<T, R>): (iter: AsyncIterable<T>) => AsyncIterable<R>; } export const map: Map = _curry(_map_impl_fn);
syrflover/iterator-helper
src/methods/minByKey.ts
import type { CompareFn, KeyFn } from '../types/functions/mod.ts'; import { getLogger } from '../logger.ts'; import { minBy } from '../lib/compare/mod.ts'; import { next_async } from '../lib/iterable/mod.ts'; import { _curry, Curry2 } from '../lib/utils/mod.ts'; import { fold } from './fold.ts'; const logger = await getLogger('methods/minByKey'); async function _min_by_key_impl_fn<T, K>(keyFn: KeyFn<T, K>, cmpFn: CompareFn<K>, iter: AsyncIterable<T>): Promise<T | undefined> { logger.trace('minByKey()'); const { done, value } = await next_async(iter); if (done) { return; } return fold(async (acc, e) => minBy(keyFn, cmpFn, acc, e), value, iter); } export interface MinByKey { <T, K>(keyFn: KeyFn<T, K>, cmpFn: CompareFn<K>, iter: AsyncIterable<T>): Promise<T | undefined>; <T, K>(keyFn: KeyFn<T, K>, cmpFn: CompareFn<K>): (iter: AsyncIterable<T>) => Promise<T | undefined>; <T, K>(keyFn: KeyFn<T, K>): Curry2<CompareFn<K>, AsyncIterable<T>, Promise<T | undefined>>; } export const minByKey: MinByKey = _curry(_min_by_key_impl_fn);
syrflover/iterator-helper
src/methods/findMap.ts
import type { MapFn } from '../types/functions/mod.ts'; import type { Nullable } from '../types/mod.ts'; import { getLogger } from '../logger.ts'; import { isNull } from '../types/guards/mod.ts'; import { _curry } from '../lib/utils/mod.ts'; const logger = await getLogger('methods/findMap'); async function _find_map_impl_fn<T, R>(fn: MapFn<T, Nullable<R>>, iter: AsyncIterable<T>): Promise<R | undefined> { logger.trace('findMap()'); for await (const elem of iter) { const mapped = await fn(elem); logger.debug('element =', elem); logger.debug('mapped =', mapped); if (!isNull(mapped)) { return mapped; } } } export interface FindMap { <T, R>(fn: MapFn<T, Nullable<R>>, iter: AsyncIterable<T>): Promise<R | undefined>; <T, R>(fn: MapFn<T, Nullable<R>>): (iter: AsyncIterable<T>) => Promise<R | undefined>; } export const findMap: FindMap = _curry(_find_map_impl_fn);
syrflover/iterator-helper
src/types/guards/isArrayLikeOrString.ts
<filename>src/types/guards/isArrayLikeOrString.ts<gh_stars>1-10 import { isArrayLike } from './isArrayLike.ts'; import { isString } from './isString.ts'; export function isArrayLikeOrString(a: any): a is string | any[] { return isArrayLike(a) || isString(a); }
syrflover/iterator-helper
src/types/functions/scan.ts
<gh_stars>1-10 export type ScanFn<A, B> = (state: B, element: A) => B | Promise<B>; // export type ScanrFn<A, B> = (element: A, state: B) => B | Promise<B>;
syrflover/iterator-helper
src/types/global.ts
<reponame>syrflover/iterator-helper import type { EP } from './promise.ts'; import { getLogger } from '../logger.ts'; import { iterator, ToAsyncIterator } from '../mod.ts'; const logger = await getLogger('global'); declare global { interface String { iter(): ToAsyncIterator<string>; } interface Array<T> { iter(): ToAsyncIterator<EP<T>>; } interface Int8Array { iter(): ToAsyncIterator<number>; } interface Int16Array { iter(): ToAsyncIterator<number>; } interface Int32Array { iter(): ToAsyncIterator<number>; } interface Uint8Array { iter(): ToAsyncIterator<number>; } interface Uint8ClampedArray { iter(): ToAsyncIterator<number>; } interface Uint16Array { iter(): ToAsyncIterator<number>; } interface Uint32Array { iter(): ToAsyncIterator<number>; } interface Float32Array { iter(): ToAsyncIterator<number>; } interface Float64Array { iter(): ToAsyncIterator<number>; } } String.prototype.iter = function () { logger.trace('String', 'iter()'); return iterator(this); }; Array.prototype.iter = function () { logger.trace('Array', 'iter()'); return iterator(this); }; Int8Array.prototype.iter = function () { logger.trace('Int8Array', 'iter()'); return iterator(this); }; Int16Array.prototype.iter = function () { logger.trace('Int16Array', 'iter()'); return iterator(this); }; Int32Array.prototype.iter = function () { logger.trace('Int32Array', 'iter()'); return iterator(this); }; Uint8Array.prototype.iter = function () { logger.trace('Uint8Array', 'iter()'); return iterator(this); }; Uint8ClampedArray.prototype.iter = function () { logger.trace('Uint8ClampedArray', 'iter()'); return iterator(this); }; Uint16Array.prototype.iter = function () { logger.trace('Uint16Array', 'iter()'); return iterator(this); }; Uint32Array.prototype.iter = function () { logger.trace('Uint32Array', 'iter()'); return iterator(this); }; Float32Array.prototype.iter = function () { logger.trace('Float32Array', 'iter()'); return iterator(this); }; Float64Array.prototype.iter = function () { logger.trace('Float64Array', 'iter()'); return iterator(this); };
syrflover/iterator-helper
src/lib/utils/id_test.ts
import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { id } from './mod.ts'; Deno.test('id()', async () => { const actual = id(1); const expected = 1; assertEquals(actual, expected); });
syrflover/iterator-helper
src/types/guards/isFunction_test.ts
import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { isFunction } from './mod.ts'; Deno.test('isFunction() function', () => { function a() {} const actual = isFunction(a); const expected = true; assertEquals(actual, expected); }); Deno.test('isFunction() arrow function', () => { const actual = isFunction(() => {}); const expected = true; assertEquals(actual, expected); }); Deno.test('isFunction() generator function', () => { function* a() { yield 1; } const actual = isFunction(a); const expected = false; // because a.constructor is GeneratorFunction assertEquals(actual, expected); }); Deno.test('isFunction() async generator function', () => { async function* a() { yield 1; } const actual = isFunction(a); const expected = false; // because a.constructor is AsyncGeneratorFunction assertEquals(actual, expected); }); Deno.test('isFunction() undefined', () => { const actual = isFunction(undefined); const expected = false; assertEquals(actual, expected); });
syrflover/iterator-helper
deno/methods/maxBy.ts
<gh_stars>1-10 import type { CompareFn } from "../types/functions/mod.ts"; import { _curry, id } from "../lib/utils/mod.ts"; import { maxByKey } from "./maxByKey.ts"; export interface MaxBy { <T>(fn: CompareFn<T>, iter: AsyncIterable<T>): Promise<T | undefined>; <T>(fn: CompareFn<T>): (iter: AsyncIterable<T>) => Promise<T | undefined>; } export const maxBy: MaxBy = _curry( <T>(fn: CompareFn<T>, iter: AsyncIterable<T>) => { return maxByKey(id, fn, iter); }, );
syrflover/iterator-helper
src/methods/takeWhile.ts
import type { PredicateFn } from '../types/functions/mod.ts'; import { getLogger } from '../logger.ts'; import { _curry } from '../lib/utils/mod.ts'; const logger = await getLogger('methods/takeWhile'); async function* _take_while_impl_fn<T>(predicate: PredicateFn<T>, iter: AsyncIterable<T>): AsyncIterable<T> { logger.trace('takeWhile()'); for await (const elem of iter) { const condition = await predicate(elem); logger.debug('element =', elem); logger.debug('condition =', condition); if (!condition) { return; } yield elem; } } export interface TakeWhile { <T>(predicate: PredicateFn<T>, iter: AsyncIterable<T>): AsyncIterable<T>; <T>(predicate: PredicateFn<T>): (iter: AsyncIterable<T>) => AsyncIterable<T>; } export const takeWhile: TakeWhile = _curry(_take_while_impl_fn);
syrflover/iterator-helper
src/types/guards/isArrayLikeOrString_test.ts
<filename>src/types/guards/isArrayLikeOrString_test.ts<gh_stars>1-10 import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { isArrayLikeOrString } from './mod.ts'; Deno.test('isArrayLikeOrString() array', () => { const actual = isArrayLikeOrString([1, 2, 3]); const expected = true; assertEquals(actual, expected); }); Deno.test('isArrayLikeOrString() typed array', () => { const actual = isArrayLikeOrString(new Int8Array([1, 2, 3])); const expected = true; assertEquals(actual, expected); }); Deno.test('isArrayLikeOrString() string', () => { const actual = isArrayLikeOrString('abcd'); const expected = true; assertEquals(actual, expected); }); Deno.test('isArrayLikeOrString() undefined', () => { const actual = isArrayLikeOrString(undefined); const expected = false; assertEquals(actual, expected); });
syrflover/iterator-helper
src/methods/chain_test.ts
import { assertEquals } from 'https://deno.land/std/testing/asserts.ts'; import { iterator } from '../mod.ts'; Deno.test('chain() [1,2,3].chain([4,5,6])', async () => { const a = iterator([1, 2, 3]); const actual: number[] = []; const expected = [1, 2, 3, 4, 5, 6]; for await (const _ of a.chain([4, 5, 6])) { actual.push(_); } assertEquals(actual, expected); }); Deno.test('chain() [1,2,3].chain([4,Promise(5),6])', async () => { const a = iterator([1, 2, 3]); const actual: number[] = []; const expected = [1, 2, 3, 4, 5, 6]; for await (const _ of a.chain([4, Promise.resolve(5), 6])) { actual.push(_); } assertEquals(actual, expected); });
syrflover/iterator-helper
deno/lib/compare/maxBy.ts
<filename>deno/lib/compare/maxBy.ts import type { CompareFn, KeyFn } from '../../types/functions/mod.ts'; import { Ord } from '../../types/mod.ts'; export async function maxBy<T, K>(keyFn: KeyFn<T, K>, cmpFn: CompareFn<K>, a: T, b: T): Promise<T> { const key_a = await keyFn(a); const key_b = await keyFn(b); const ord = await cmpFn(key_a, key_b); switch (ord) { case Ord.Less: return b; case Ord.Greater: return a; case Ord.Equal: return b; } }
syrflover/iterator-helper
src/types/guards/mod.ts
<reponame>syrflover/iterator-helper<gh_stars>1-10 export * from './isArrayLike.ts'; export * from './isArrayLikeOrString.ts'; export * from './isAsyncIterable.ts'; export * from './isFunction.ts'; export * from './isIterable.ts'; export * from './isNull.ts'; export * from './isPromise.ts'; export * from './isString.ts';
syrflover/iterator-helper
src/types/promise.ts
export type ExtractPromise<T> = T extends Promise<infer P> ? P : T; export type EP<T> = ExtractPromise<T>;
syrflover/iterator-helper
src/methods/filter.ts
<filename>src/methods/filter.ts<gh_stars>1-10 import type { PredicateFn } from '../types/functions/mod.ts'; import { getLogger } from '../logger.ts'; import { _curry } from '../lib/utils/mod.ts'; const logger = await getLogger('methods/filter'); async function* _filter_impl_fn<T>(predicate: PredicateFn<T>, iter: AsyncIterable<T>) { logger.trace('filter()'); for await (const elem of iter) { if (await predicate(elem)) { yield elem; } } } export interface Filter { <T>(predicate: PredicateFn<T>, iter: AsyncIterable<T>): AsyncIterable<T>; <T>(predicate: PredicateFn<T>): (iter: AsyncIterable<T>) => AsyncIterable<T>; } export const filter: Filter = _curry(_filter_impl_fn);
syrflover/iterator-helper
src/methods/mod.ts
export { all } from './all.ts'; export { any } from './any.ts'; export { average } from './average.ts'; export { chain } from './chain.ts'; export { collect } from './collect.ts'; export { count } from './count.ts'; export { cycle } from './cycle.ts'; export { enumerate } from './enumerate.ts'; export { filter } from './filter.ts'; export { filterMap } from './filterMap.ts'; export { find } from './find.ts'; export { findMap } from './findMap.ts'; export { flatMap } from './flatMap.ts'; export { flatten } from './flatten.ts'; export { fold } from './fold.ts'; export { fold1 } from './fold1.ts'; export { forEach } from './forEach.ts'; export { head } from './head.ts'; export { inspect } from './inspect.ts'; export { last } from './last.ts'; export { map } from './map.ts'; export { max } from './max.ts'; export { maxBy } from './maxBy.ts'; export { maxByKey } from './maxByKey.ts'; export { min } from './min.ts'; export { minBy } from './minBy.ts'; export { minByKey } from './minByKey.ts'; export { nth } from './nth.ts'; export { nub } from './nub.ts'; export { nubBy } from './nubBy.ts'; export { partition } from './partition.ts'; export { position } from './position.ts'; export { product } from './product.ts'; export { reverse } from './reverse.ts'; export { scan } from './scan.ts'; export { scan1 } from './scan1.ts'; export { skip } from './skip.ts'; export { skipWhile } from './skipWhile.ts'; export { stepBy } from './stepBy.ts'; export { sum } from './sum.ts'; export { take } from './take.ts'; export { takeWhile } from './takeWhile.ts'; export { unzip } from './unzip.ts'; export { zip } from './zip.ts';
syrflover/iterator-helper
deno/lib/compare/max.ts
<reponame>syrflover/iterator-helper import { id } from '../utils/mod.ts'; import { compare } from './compare.ts'; import { maxBy } from './maxBy.ts'; export function max<T>(a: T, b: T): Promise<T> { return maxBy(id, compare, a, b); }
syrflover/iterator-helper
deno/lib/iterable/prepend.ts
// a -> [a] -> [a] export async function* prepend<T>(x: T, xs: Iterable<T> | AsyncIterable<T>) { yield x; yield* xs; }