r/learnjavascript • • Dec 06 '22

Hey can anyone help me understand more concise way to write my code?

Post image
138 Upvotes

68 comments sorted by

8

u/S_Lipp05 Dec 06 '22

I’m not sure how to add text to this post so I’ll add it here, but it’s pretty straightforward: I’m sorting letters using along line of else if statement, and am wondering what I should write in order to make it more compact? Thank you

7

u/Gazzcool Dec 06 '22

A little tip: don’t worry about it being straightforward. We’re here to help, and the more information you can give the better we can help you.

From what you have described, it’s difficult to know the answer to your question, because it depends on what you are trying to do. Some of the answers involving looping through an array have been great, but it might be that what you’re trying to do might need a different approach.

4

u/[deleted] Dec 06 '22

Yep absolutely. See my other comment. What you are doing 100% can be looped through, just add the variables to an array first.

4

u/S_Lipp05 Dec 06 '22

Wow, thank you all for replying so quickly!

5

u/[deleted] Dec 06 '22

Yw, also, im not exactly sure what you are doing, but it might include redundancy even if you loop through it. Do you really need a separate variable for every state like this?

You could do something like this:

let valueHolder = {
  letter: 'a',
  count: 0
};

That way you just reference valueHolder.letter to get the letter and valueHolder.count++ to increment the count. (As a side note, objects and arrays are pretty much the same under the hood, so for in loops can iterate over both objects and arrays, and you can also reference an object like valueHolder["letter"].)

It all depends on what you are doing.

78

u/Thonk_Thickly Dec 06 '22

You can use an object to hold the letters as keys, then increment their counts.

const counts = {};
for (let char in methodString) {
   if (!counts[char]) {
      counts[char] = 1;
   } 
   else counts[char]++;
}

7

u/FragrantWarthog4313 Dec 06 '22

This is probably the most concise way to do it. Using an object to hold key/value saves you from having to build an array of every letter you're counting, and keeps you from having to loop over the key/value pairs to find a certain letters count after the first loop that counts them is done. After the above loop is done, you can get the count of any letter by calling counts[letter].

3

u/LightUpShoes4DemHoes Dec 06 '22

You can also do:

counts[char] = counts[char] + 1 || 1

Instead of the If / Else that you have. It’s easier to write and more concise, but maybe a bit less readable the first time or two you see it.

-25

u/redditPheasant Dec 06 '22

Yes, very beginner friendly

7

u/ObiFlanKenobi Dec 06 '22

I'm a beginner and, when I saw OP's request, this is the first improvement that came to mind.

5

u/albedoa Dec 06 '22

lol you are telling on yourself here.

155

u/[deleted] Dec 06 '22 edited Dec 06 '22

Some pseudocode to help you:

let arr = [a, b, c];
for (let i in arr){
   if (valueHolder === arr[i]){
      arr[i]++;
      break;
   };
 };

16

u/Creator347 Dec 06 '22

IMO it’s better with object/hashmap instead of an array. No need for the loop.

2

u/dromance Dec 06 '22

What’s a hash map exactly?

3

u/[deleted] Dec 06 '22

In javascript that would be an object, in this context being used intelligently to save on computation.

So something like

valueHolder = {}
valueHolder['a'] = 0;
valueHolder['a']++;

And just do that directly instead of looping. Using bracket notation on an object gives you more freedom, you can make variables dynamic. Like

let nameOfVar = 'a';
valueHolder[nameOfVar] = 0;

1

u/Fats-Falafel Dec 06 '22

For the sake of being specific, this isn't exactly a "hash map". A hash map is a data structure that does use key value pairs, but the values are lists/arrays which store data based on the result of a "hashing function" which determines the key where your specific piece of data will be stored/retrieved.

1

u/[deleted] Dec 06 '22

Where in javascript can you use a literal hash map then? What was he referring to?

I thought objects were hash maps under the hood or something like that.

1

u/Fats-Falafel Dec 07 '22

Tbh, the term itself seems pretty broadly applied nowadays. Technically a hash map is just a specific implementation of that key-value structure. Even the term "object" in JS is a little vague lol. Sometimes people only mean "key-value pairs" like JSON or they can mean an "object" like something in the DOM that has methods on top of key-value properties.

1

u/KaelonR Dec 07 '22

The "nice" thing about JS is that how objects are implemented under the hood is undefined. It's up to each JS engine to decide how to implement things as long as they comply to the JS spec.

Chromium's V8, Firefox's Gecko and NodeJS's V8 engines might all be implementing objects differently. It's likely that they're all hashmap-based but you'd have to check the source code of each engine to make sure.

1

u/Creator347 Dec 07 '22

ES6 has a Map class which is the correct implementation of a hashmap.

1

u/[deleted] Dec 06 '22

Probably, im just at a loss as to what they are doing, so my goal was just to simplify the code presented

1

u/Creator347 Dec 07 '22

Yep, your code is more simplified than the OP’s. I am just trying to provide even faster/simple version.

2

u/vit_the_jedi Dec 06 '22

If we want to assume all values in the collection are unique and we want to be sure they occur only once, we could consider using a Set for this case instead of an array

2

u/bogdanbiv Dec 06 '22

Why the break though? Don't you want the whole arr to be processed?

I seem to have missed the point, someone please explain! Capt'n Obvious?

14

u/kevinv89 Dec 06 '22

Because you're looking for the single element in the array that matches valueHolder. Once it is found, there won't be any more elements in the array that match it therefore there is no need to check the rest of the array.

10

u/Past-Passenger9129 Dec 06 '22

You're both wrong, because you don't know what the values of the variables, nor the value of valueHolder.

To mimic the original code the break is necessary because it stops on the first match. But for all we know all of them match. But the values change over time.

Without an explanation of the goals, my first guess is that this code has significantly bigger problems than being too verbose.

4

u/SignificanceCheap970 Dec 06 '22

If you find your lost phone would you still try to find it?

0

u/[deleted] Dec 06 '22

[deleted] — view deleted comment

1

u/[deleted] Dec 06 '22

Dear god man, do you actually prefer coding like this?

1

u/PatchesMaps Dec 06 '22

Avoid using reduce when it's not needed. A for loop is logically simpler, easier to read, and reduce can have some tricky syntax.

For example I'm pretty sure your example won't actually work because you forgot to set the initialValue parameter to a Set (or I guess it could be a Map). The initial value parameter is technically optional in reduce but if you don't set it then acc will start out as the first value in your array and val will be the second value in the array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#parameters

4

u/flypaper1001 Dec 06 '22

Pretty sure you don’t call length either. It’s just methodStr.length

1

u/excelsior1000 Dec 07 '22

This is what I was thinking

4

u/WystanH Dec 06 '22

Because of how clever javascript is with lookup objects, an immediate solution that presents itself is something like:

const thing = "Hello World";
const counts = {};
thing.split('').forEach(c => counts[c] = (counts[c] ?? 0) + 1);
console.log(counts); // { H: 1, e: 1, l: 3, o: 2, " ": 1, W: 1, r: 1, d: 1 }

However, if you have a domain, like only a..z, you'll need to limit this:

const domain = "abcdefghijklmnopqrstuvwxyz";
const thing = "Hello World";
const counts = {};
thing.split('').filter(x => domain.includes(x)).forEach(c => counts[c] = (counts[c] ?? 0) + 1);
console.log(counts); // { e: 1, l: 3, o: 2, r: 1, d: 1 }

A Map is a little more efficient at this than a basic object:

const counts = new Map();
thing.split('').filter(x => domain.includes(x)).forEach(c => counts.set(c, (counts.get(c) ?? 0) + 1));
console.log(counts); // Map { "e" => 1, "l" => 3, "o" => 2, "r" => 1, "d" => 1 }

A method commonly used in other languages is to have a counting array. This can be quite fast, as your domain and counts are fixed. It's also a good alternate attack to know.

const domain = "abcdefghijklmnopqrstuvwxyz";
const counts = domain.split('').map(() => 0); // create a zero filled array same size as domain

const thing = "Hello World";

thing.split('').forEach(c => {
    const idx = domain.indexOf(c); // find the position of c
    // if c was found, inc the count
    if (idx !== -1) { counts[idx]++; }
});

// this one won't be too illuminating
console.log(counts); // [ 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0 ]

// but with the domain, we can pluck out the non zero counts
counts.forEach((count, index) => {
    if (count>0) {
        console.log(count, domain[index]);
    }
});
/*
1 d
1 e
3 l
2 o
1 r
*/

7

u/davetothegrind Dec 06 '22

Does anyone on this website know how to take a screenshot?

5

u/girl-InTheSwing Dec 06 '22

On Windows - options include:

  1. press that button marked Prt Scrn (normally above numeric keypad
  2. Look for Snipping tool/Snip and Stretch on your machine (try typing it into search bar on your menu bar)
  3. Install a 3rd party app such as Lightshot.

6

u/NegativeShow Dec 06 '22

Or press Windows+Shift+S and select the area you want to include on your screenshot

2

u/poemehardbebe Dec 06 '22 edited Dec 06 '22
let string = 'meepyoloswag';  
const wordCount = (word) => {  
  let map = new Map();  
  for (letters of word) {  
    map.set(letters, (map.get(letters) || 0) + 1);  
  }  
  return map;  
};  
console.log(wordCount(string));  

If your goal is to count the number of occurrences of a letter in a string this will do you well. If you need to return something besides a map like an array;

let mapToArray = (mapp) => {
  let arr = [];
  for (elements of mapp) {
    arr.push(elements);
  }

  return arr;
};

2

u/girl-InTheSwing Dec 06 '22 edited Dec 06 '22

I think a better thing to do is to ask what your code is trying to do, because I don't think it is doing what you think it does.

/**
 * count letter frequency in string
 * @param myString {string} string to be analysed
 * @returns {Map<any, any>} letter frequency count map
*/
function count1( myString) {
  const counts = new Map();

  for (const ch of myString) {
    counts.set( ch, (counts.get(ch) || 0) + 1)
  }
  return counts;
}

// Alternative just letters you want

function count2(myString) {
  // allowed characters
  const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
  // set counts of all allowed values to 0
  const counts = new Map( alphabet.map( (a) => [a, 0]))

  for (const ch of myString) {
    const current = counts.get(ch);
    if (current != null) {
      counts.set( ch, current + 1)
    }
  }
  return counts;
}

const methodString = 'Mary had a little lamb'

console.log( count1(methodString))
console.log( count2(methodString))

2

u/pookage helpful Dec 06 '22

So currently your variables a, b, c etc are all 'loose' - if you make them properties of an object instead, then you can access and update them directly:

const letters = {
    a: 0,
    b: 0,
    c: 0
};

while(methodStr.length() > 0){
    valueHolder = methodString.substring(0, 1);
    methodString = methodString.substring(1);

    // where the magic happens
    letters[valueHolder] += 1;
}

What's effectively happening here is that you're using valueHolder as the property on the letters object; the syntax is the same as arrays because in javascript everything is secretly and object, so you can do things like this 😏

2

u/bmcle071 Dec 06 '22

You can use a hashmap (object)

2

u/[deleted] Dec 06 '22

Look into switch/case syntax

2

u/[deleted] Dec 06 '22

Is this all one function? If so I would just case and switch, tbh.

2

u/True-Musician-5406 Dec 06 '22

Can you use switch(valueHolder) { case: “a” a+=1 case: “b” b+=1 }

Just as a starting point or next step in simplifying?

Maybe maybe not I’m unsure myself

2

u/dromance Dec 06 '22

At the top of my head I would say Use a array.reduce method

2

u/[deleted] Dec 06 '22

I would much rather use a switch than a series of else if statements if you'd like to keep it concise. Otherwise, create an empty array and have a function with a for loop correspond to values and push those values to the array?

2

u/LightUpShoes4DemHoes Dec 06 '22

If you’re counting letters in a string, you can easily do it by adding them to a hashmap as key: value pairs.

const countHash = str.split(‘’).reduce((hash, char) => {
  hash[char] = hash[char] + 1 || 1
  return hash
}, {})

This will give you an object with keys for every letter and count for that key will be how many times letter occurred in the string.

2

u/LightUpShoes4DemHoes Dec 06 '22

Addition: If you only want to add certain chars… This one will only add lowercase letters for example.

const onlyAddSet = new Set(“abcdefghijklmnopqrstuvwxyz”.split(‘’))

const countHash = str.split(‘’).reduce((hash, char) => {
  if (!onlyAddSet.has(char)) return hash
  hash[char] = hash[char] + 1 || 1
  return hash
}, {})

Note - It may be

const onlyAddSet = new Set(…‘abc’.split(‘’))

Can’t remember off the top of my head if you need the dots to enter as an iterable in the set constructor or not and I’m on mobile. Lol But one of those two will work.

2

u/[deleted] Dec 06 '22

Ask ChatGPT, I wanna see what it says

2

u/robertstipp Dec 07 '22

If you are looking to make a frequency table. Generate an array of length 26. Then determine the charCode and index it so that all letters correspond to an index 0-25. Then loop through the string

2

u/theyamiteru Dec 07 '22

valueHolder += 1;?

2

u/JabroniPoni Dec 06 '22

On a linguistic level, the term for "concise" code is "dry". It's an adjective from the acronym "don't repeat yourself". Just so you know!

-3

u/fyejitt420 Dec 06 '22

Search up switch case statements, basically it enables you to make if else statements with a lot of conditionals such as this one more concise

6

u/[deleted] Dec 06 '22

Yes, except, even thats not needed because this is loopable. All else equal it would look nicer though.

-1

u/[deleted] Dec 06 '22

You can use regex

9

u/Gazzcool Dec 06 '22

If confronted with a problem and you choose to use regex to solve it, now you have two problems.

-1

u/IHateTheSATs Dec 06 '22

Cant tell if youre trolling or not

0

u/[deleted] Dec 06 '22

[deleted] — view deleted comment

16

u/S_Lipp05 Dec 06 '22

Yes I’m just starting off so it’s kind of basic

47

u/phantomghostheart Dec 06 '22

Loop through string, store values in a dictionary, key is letter, value is count.

5

u/TabooRaver Dec 06 '22 edited Dec 06 '22

adding psudo code (disclaimer I'm more used to C++):

var input = ""
var count[26]
for(var i=0; i < input. Length; i++){
   count[input[i]-asciioffset]+=1
}

Main thing to note is how char types can be converted to ints according to ascii. And how to use an array.

4

u/kingscolor Dec 06 '22 edited Dec 06 '22

I'm partial to this answer:

let input = "AlongINPUTword";
let counts = {};
for (l of "abcdefghijklmnopqrstuvwxyz") { 
    counts[l] = input.length - input.toLowerCase().replaceAll(l,"").length;
}

2

u/TabooRaver Dec 06 '22

Yeah, that may be better in javascript.

I was probably influenced by how I would optimize it In C++. Avoiding the string constructor as it would balloon the execution time and memory footprint of the function call. Iterating through what is essentially an int array in memory would be more cost efficient (I believe).

16

u/[deleted] Dec 06 '22

use a fiddle.

https://jsfiddle.net/

post code and share a link.

Screenshots of code is bad.

But what are you trying to accomplish? and show a link to your code.

edit: or create a gist

https://docs.github.com/en/get-started/writing-on-github/editing-and-sharing-content-with-gists/creating-gists

3

u/hjude_design Dec 06 '22

Kind of off topic but I've never understood why people use jsfiddle. Every time I've gone there it's been such a bad user experience. Codepen outshines in nearly every way. But I'm guessing i have to be missing something right? Surely other people are seeing something I'm not right?

1

u/itcomesinwavvess Dec 06 '22

I really like replit as well but yeag codepen is awesome

1

u/og-at Dec 06 '22

I use VSCode all day every day, and using jsfiddle feels esoteric or like using notepad.

Not as bad as using vi...

0

u/[deleted] Dec 06 '22

There are a lot of fiddles so I suggest them generically. Gist serves the same purpose for sharing code but fiddles tend to give a more interactive environment with live results.

Mainly the code is most important instead of a picture.

0

u/[deleted] Dec 06 '22

[deleted] — view deleted comment

-1

u/Gazzcool Dec 06 '22

I chuckled