Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0125· OpenAIAi2 WildChat-4.8M (AI2)

Create a TS code for stack data structure

  1. User

    User: Create a TS code for stack data structure Assistant: class Stack {
    private items: any[];

    constructor() {
    this.items = [];
    }

    push(item: any): void {
    this.items.push(item);
    }

    pop(): any {
    if (this.isEmpty()) {
    return null;
    }
    return this.items.pop();
    }

    peek(): any {
    if (this.isEmpty()) {
    return null;
    }
    return this.items[this.items.length - 1];
    }

    isEmpty(): boolean {
    return this.items.length === 0;
    }

    size(): number {
    return this.items.length;
    }

    clear(): void {
    this.items = [];
    }
    }

    // Usage example
    const stack = new Stack();

    stack.push(1);
    stack.push(2);
    stack.push(3);

    console.log(stack.peek()); // Outputs: 3

    console.log(stack.pop()); // Outputs: 3

    console.log(stack.size()); // Outputs: 2

    stack.clear();

    console.log(stack.isEmpty()); // Outputs: true User: Could you rename the class to StackDs Assistant: class StackDs {
    private items: any[];

    constructor() {
    this.items = [];
    }

    push(item: any): void {
    this.items.push(item);
    }

    pop(): any {
    if (this.isEmpty()) {
    return null;
    }
    return this.items.pop();
    }

    peek(): any {
    if (this.isEmpty()) {
    return null;
    }
    return this.items[this.items.length - 1];
    }

    isEmpty(): boolean {
    return this.items.length === 0;
    }

    size(): number {
    return this.items.length;
    }

    clear(): void {
    this.items = [];
    }
    }

    // Usage example
    const stack = new StackDs();

    stack.push(1);
    stack.push(2);
    stack.push(3);

    console.log(stack.peek()); // Outputs: 3

    console.log(stack.pop()); // Outputs: 3

    console.log(stack.size()); // Outputs: 2

    stack.clear();

    console.log(stack.isEmpty()); // Outputs: true User: very good Assistant:

  2. Assistant

    Thank you! If you have any more questions or need further assistance, feel free to ask.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.