↓ Skip to main content
Web & APIs

Optimizing in JS

·2 mins
Sonic the hedgehog

You never stop learning is not just a phrase, it is something I live everyday. Today, I was just trying out my skills with JS and was solving an innocuous problem, in JS.

Pangram: A pangram is a sentence using every letter of the alphabet at least once.

E.g. The quick brown fox jumps over the lazy dog.

Like every old school programmer I was trying to solve it in the easiest of ways without breaking a sweat and the first version I could come up with was as under.

// Define an string of all Alphabets.
export const ALPHABETS = "abcedfghijklmnopqrstuvwxyz";

// isPangram allows you input a string to be validated for Pangram
export const isPangram = (pangram) => {

  if(pangram == null || pangram.length == 0) {

    return false;

  }

  pangram = pangra.toLowerCase();

  var x;

  for (x in ALPHABETS){
    if( pangram.indexOf(ALPHABETS[x]) >= 0) {
      continue;
    } else {
      return false;
    }
  }
  return true;
};

So v1 was not much fat code,  I was thinking but then the geek in me was trying to ask can it be simplified further? Optimized in a way it looks cool? and so started my struggle to better the version 1, I had just written.

Problem 1: How to generate the character set
#

So I thought, instead of having a simple constant string, how about I make it a function to first generate an Array that has all the characters from English; all from A … Z. (Some helpful link)

Array.from({length: 26}, (_, i) => { String.fromCodeCode(97 + i)});

How I used it was like this.

const Alphabets = () => Array.from({length:26}, (_, i) =>String.fromCharCode(97+i));

Now, after having this Array it was time to look for the ‘Pangram’ in the string. Another method every() and includes() came to the rescue.

V2.0
#

// isPangram allows you to look for Pangram.
export const isPangram = (pangram) => {
     var alphabets = Alphabets();
     var lowerCase = pangram.toLowerCase();
     return alphabets.every( character=>lowerCase.includes(character));
};

and Voila, I think made a better version from what I had at v1.0.

– The – End –
#
Author
Samarthya
Engineer, learner, tinkerer. This is my trophy shelf of everyday work and leisure.

Related

MySQL/MariaDB on MAC

·1 min
Challenges are plenty but outcome is always one – Learning! While trying to troubleshoot an inhouse application I had to setup a quick MySQL instance which led me to install my first instance of MariaDB on my local MAC machine.

KubeLab

·3 mins
Kubernetes cloud_user@ip-10-0-1-101:~$ kubectl version Client Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.3", GitCommit:"721bfa751924da8d1680787490c54b9179b1fed0", GitTreeState:"clean", BuildDate:"2019-02-01T20:08:12Z", GoVersion:"go1.11.5", Compiler:"gc", Platform:"linux/amd64"} Server Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.11", GitCommit:"25074a190ef2a07d8b0ed38734f2cb373edfb868", GitTreeState:"clean", BuildDate:"2019-09-18T14:34:46Z", GoVersion:"go1.11.13", Compiler:"gc", Platform:"linux/amd64"} cloud_user@ip-10-0-1-101:~$ kubectl api-resources NAME SHORTNAMES APIGROUP NAMESPACED KIND bindings true Binding componentstatuses cs false ComponentStatus configmaps cm true ConfigMap endpoints ep true Endpoints events ev true Event limitranges limits true LimitRange namespaces ns false Namespace nodes no false Node persistentvolumeclaims pvc true PersistentVolumeClaim persistentvolumes pv false PersistentVolume pods po true Pod podtemplates true PodTemplate replicationcontrollers rc true ReplicationController resourcequotas quota true ResourceQuota secrets true Secret serviceaccounts sa true ServiceAccount services svc true Service mutatingwebhookconfigurations admissionregistration.k8s.io false MutatingWebhookConfiguration validatingwebhookconfigurations admissionregistration.k8s.io false ValidatingWebhookConfiguration customresourcedefinitions crd,crds apiextensions.k8s.io false CustomResourceDefinition apiservices apiregistration.k8s.io false APIService controllerrevisions apps true ControllerRevision daemonsets ds apps true DaemonSet deployments deploy apps true Deployment replicasets rs apps true ReplicaSet statefulsets sts apps true StatefulSet tokenreviews authentication.k8s.io false TokenReview localsubjectaccessreviews authorization.k8s.io true LocalSubjectAccessReview selfsubjectaccessreviews authorization.k8s.io false SelfSubjectAccessReview selfsubjectrulesreviews authorization.k8s.io false SelfSubjectRulesReview subjectaccessreviews authorization.k8s.io false SubjectAccessReview horizontalpodautoscalers hpa autoscaling true HorizontalPodAutoscaler cronjobs cj batch true CronJob jobs batch true Job certificatesigningrequests csr certificates.k8s.io false CertificateSigningRequest leases coordination.k8s.io true Lease events ev events.k8s.io true Event daemonsets ds extensions true DaemonSet deployments deploy extensions true Deployment ingresses ing extensions true Ingress networkpolicies netpol extensions true NetworkPolicy podsecuritypolicies psp extensions false PodSecurityPolicy replicasets rs extensions true ReplicaSet networkpolicies netpol networking.k8s.io true NetworkPolicy poddisruptionbudgets pdb policy true PodDisruptionBudget podsecuritypolicies psp policy false PodSecurityPolicy clusterrolebindings rbac.authorization.k8s.io false ClusterRoleBinding clusterroles rbac.authorization.k8s.io false ClusterRole rolebindings rbac.authorization.k8s.io true RoleBinding roles rbac.authorization.k8s.io true Role priorityclasses pc scheduling.k8s.io false PriorityClass storageclasses sc storage.k8s.io false StorageClass volumeattachments storage.k8s.io false VolumeAttachment cloud_user@ip-10-0-1-101:~$ kubectl get cm NAME DATA AGE fruit-service-ambassador-config 1 5m49s Basic Commands (Beginner): create Create a resource from a file or from stdin. expose Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service run Run a particular image on the cluster set Set specific features on objects Basic Commands (Intermediate): explain Documentation of resources get Display one or many resources edit Edit a resource on the server delete Delete resources by filenames, stdin, resources and names, or by resources and label selector Deploy Commands: rollout Manage the rollout of a resource scale Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job autoscale Auto-scale a Deployment, ReplicaSet, or ReplicationController Cluster Management Commands: certificate Modify certificate resources. cluster-info Display cluster info top Display Resource (CPU/Memory/Storage) usage. cordon Mark node as unschedulable uncordon Mark node as schedulable drain Drain node in preparation for maintenance taint Update the taints on one or more nodes Troubleshooting and Debugging Commands: describe Show details of a specific resource or group of resources logs Print the logs for a container in a pod attach Attach to a running container exec Execute a command in a container port-forward Forward one or more local ports to a pod proxy Run a proxy to the Kubernetes API server cp Copy files and directories to and from containers. auth Inspect authorization Advanced Commands: diff Diff live version against would-be applied version apply Apply a configuration to a resource by filename or stdin patch Update field(s) of a resource using strategic merge patch replace Replace a resource by filename or stdin wait Experimental: Wait for a specific condition on one or many resources. convert Convert config files between different API versions Settings Commands: label Update the labels on a resource annotate Update the annotations on a resource completion Output shell completion code for the specified shell (bash or zsh) Other Commands: api-resources Print the supported API resources on the server api-versions Print the supported API versions on the server, in the form of "group/version" config Modify kubeconfig files plugin Provides utilities for interacting with plugins. version Print the client and server version information Usage: kubectl [flags] [options]

Spring Data-LDAP

·7 mins
I have a small problem at hand which girdles around learning Angular, with a Spring enabled Rest endpoints which uses a DB to store data and have security layer in between that should interact with a LDAP for authentication and authorization and finally the application should run as one smooth unit. It will be too much to cover in single blog so I will be writing multiple blogs in continuation to this one.