I'm baffled by how the community response is implemented in this particular TypeScript exercise on Exercism

I am currently learning TypeScript from scratch by working on exercises available on exercism

Successfully completed the 5th exercise on Pangram.

Below is my solution:

class Pangram {

     alphabet = "abcdefghijklmnopqrstuvwxyz"

    constructor(private pangram:string) {
        this.pangram = pangram.toLowerCase().normalize()
    }

    isPangram():boolean{
        for( let letter of this.alphabet){
            if(this.pangram.indexOf(letter) < 0) 
                return false 
        }
        return true;
    }
}

export default Pangram

To enhance my skills, I am reviewing other solutions to learn more. One particular solution caught my attention because it involves regex, which I'm not yet proficient in:

class Pangram {
    constructor(private text:string) {
    }

    isPangram():boolean {
        var set = new Set(this.text.toLowerCase().replace(/[^A-Za-z]/g, ''))
        return set.size == 26        
    }
}

export default Pangram

I'm a bit confused about how the second solution works. Initially, I thought it would replace all letters with empty characters, hence having a size of zero. However, it checks for a size of 26. Without knowing how to debug, I can only run tests to confirm its accuracy, which has been successful so far.

If anyone could explain what's happening in the second solution, I'd appreciate it!

For those curious, I've included the unit tests used for this assignment:

import Pangram from './pangram'

describe('Pangram()', () => {
  // Test cases here...
})

Thank you!

Answer №1

The following code snippet...

const set = new Set(this.text.toLowerCase().replace(/[^A-Za-z]/g, ''))

This regular expression filters out all non-alphabetic characters from the input string by converting them to lowercase and storing only unique alphabetic characters in a Set. For example, new Set("pangram") will result in a set with elements "p", "a", "n", "g", "r", and "m".

A Set constructor iterates through its parameter, adding distinct elements. With the basic Latin alphabet having 26 distinct letters, a string passed to the constructor must have a size less than or equal to 26. If the size is exactly 26, then it is a pangram (contains all letters). Otherwise, it lacks at least one letter.

Hence,

str => new Set(str.toLowerCase().replace(/[^a-z]/g,'')).size === 26
efficiently checks if an input string is a pangram. Remember, balance conciseness with readability when coding!

Hope this explanation proves helpful for your coding endeavors. Happy coding!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for specifying the required type of an Object literal in Typescript

Let's analyze a straightforward code snippet interface Foo{ bar:string; idx:number; } const test1:Foo={bar:'name'}; // this is highly recommended as it includes all required fields const test2={bar:'name'} as Foo; // this is ...

Implementing an All-Routes-Except-One CanActivate guard in Angular2

In order to group routes within a module, I am aware that it can be done like this: canActivate: [AuthGuard], children: [ { path: '', children: [ { path: 'crises', component: ManageCrisesComponent }, ...

Struggling to chart out the post response in Angular 7

I am facing an issue while setting up a service on Angular version 7. The problem arises with the res.json() method, throwing an error stating Property 'json' does not exist on type 'Object'. Below is my service's code: import {In ...

Having trouble retrieving data from a JSON file within an Angular application when utilizing Angular services

This JSON file contains information about various moods and music playlists. {mood: [ { "id":"1", "text": "Annoyed", "cols": 1, "rows": 2, "color": "lightgree ...

Increasing the number of service providers in Angular2-4 directives

Is there a way to apply both * to a string? Below is the code snippet I am working with: <a class="sidenav-anchor" *ngIf="!item.hasSubItems()" md-list-item md-ripple [routerLink]="[item.route]" routerLinkActive="active" [routerLinkActiveOptions]="{ex ...

Metronome in TypeScript

I am currently working on developing a metronome using Typescript within the Angular 2 framework. Many thanks to @Nitzan-Tomer for assisting me with the foundational concepts, as discussed in this Stack Overflow post: Typescript Loop with Delay. My curren ...

Creating a setup with Angular 2+ coupled with Webpack and a Nodejs

I have successfully configured Angular2+webpack along with NodeJs for the backend. Here is a basic setup overview: webpack.config.js: var webpack = require('webpack') var HtmlWebpackPlugin = require('html-webpack-plugin') var Extract ...

How to effectively handle null in Typescript when accessing types with index signatures unsafely

Why am I getting an error that test might be potentially undefined even though I've enabled strictNullCheck in my tsconfig.json file? (I'm unsure of the keys beforehand) const a: Record<string, {value: string}> = {} a["test"].va ...

Unexpected TypeScript issue: Unable to access the 'flags' property of an undefined entity

Upon creating a new project and running the serve command, I encountered the following error: ERROR in TypeError: Cannot read property 'flags' of undefined Node version: 12.14 NPM version: 6.13 Contents of package.json: { "name": "angular-t ...

Tips for constructing node.js projects using local versions of the dependencies?

Recently, I've been tackling a rather intricate node.js project (find it at https://github.com/edrlab/thorium-reader/) while trying to incorporate local versions of certain dependencies. Surprisingly, I can successfully build and execute the project ...

The message "Expected a string literal for Angular 7 environment variables" is

I'm currently working on setting up different paths for staging and production environments in my Angular project, following the documentation provided here. I have a relative path that works perfectly fine when hardcoded like this: import json_data f ...

PHP: Finding a solution for escaping characters reserved for RegEx - Can anyone pinpoint the issue here?

Currently, I am attempting to escape regex-reserved characters by using a backslash (please don't ask why -- let's just say it has nothing to do with parsing HTML :)) However, I seem to be encountering something strange. $regex_chars = array(&ap ...

Using Angular 7 to set the value of an object returned by an observable to a variable

I encountered an issue while trying to assign the return value from a service to a component. ngOnInit() { this.getInspectionData(); } getInspectionData() { this.auctionService.getInspectionResult(`df570718-018a-47d8-97a2-f943a9786536`) ...

Modify the ShortDate formatting from "2020/06/01" to "2020-06-01"

I am looking to modify the shortDate format in my template file. Currently, when I try to change it to use "-", it still displays the date with "/". What I actually want is for the output to be formatted as yyyy-MM-dd. <ngx-datatable-column name="C ...

Incorporating type declarations for a basic function that returns a wrapper function for other functions

In my vanilla JS code, I have a sophisticated function that is exported and I am attempting to create a .d.ts file for it. Unfortunately, my previous attempts at writing the .d.ts file have not been successful in passing the types from one stage of the fu ...

Guide on integrating react-tether with react-dom createPortal for custom styling of tethered components based on their target components

Within a Component, I am rendering buttons each with its own tooltip. The challenge is to make the tooltip appear upon hovering over the button since the tooltip may contain more than just text and cannot be solely created with CSS. The solution involves ...

Is there a way to determine if a string is empty, even if it contains hard returns?

I am currently working on a function that checks if a string is empty or not, but it seems to be missing the detection of new lines. export const isStrEmpty = function(text: string): boolean { return !text || text.match(/^ *$/) !== null; }; I attempted ...

A Typescript Function for Generating Scalable and Unique Identifiers

How can a unique ID be generated to reduce the likelihood of overlap? for(let i = 0; i < <Arbitrary Limit>; i++) generateID(); There are several existing solutions, but they all seem like indirect ways to address this issue. Potential Solu ...

Can an Angular application be developed without the use of the app-root tag in the index.html file?

I'm a newcomer to Angular and I'm trying to wrap my head around how it functions. For example, if I have a component named "login", how can I make Angular render it directly? When I try to replace the app-root tag with app-login in index.html, n ...

What is the correct way to format React's dispatch function in order to utilize a "then" method similar to a Promise?

I'm working on a simple app that dispatches an action upon first load to populate the store. However, I'm facing an issue with trying to run a then method on dispatch, as typescript is throwing errors. (As per redux's documentation, the ret ...