Day 4 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did: https://www.codewars.com/kata/begin-your-day-with-a-challenge-but-an-easy-one/javascript

Time: 40 minutes

What I’ve learnt: OK, so this was a 2 AM challenge! Implementing the simple one digit part, took about 6 minutes. I returned the default value of [0, 0] so that would not have to run through the rest of the code as I did on the past.

But it literally took me like 25 minutes to figure out what they wanted on the multiple digits. After about 10 minutes, I decided to press “Attempt” and not just keep looking at that 1 sample test, and then I was on the road to cracking the puzzle. It was enjoyable to have this mystery included in the code 🙂

I also recently realized I can add elements directly to an index of an array, so did that for the fun of it!

Here was my solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function oneTwoThree(n) {
    // justDoIt!!
    
    if (n === 0) return ['0', '0']
    
    const array = ["", ""]
    
    function addNums(condition, arrayI, num){
      for (let i = 0; i < condition; i++){
         array[arrayI] += num
       }
    }
    
    addNums(n, 1, 1)
     
    if (n % 9 === 0){
      addNums((parseInt(n)/9), 0, 9)
    } else {
      addNums(Math.floor(parseInt(n)/9), 0, 9)
      array[0] += parseInt(n) % 9
    }
    
    return array
}

 

What I learned from other people’s code:

I did not know there was a repeat method built into Javascript. I’m very excited to have seen that!

It was amazing how people used logic to avoid an iterator.

Array.prototype.fill() is also a super handy new method I learned from seeing other people’s solutions.

Now gotta start using it so I don’t lose it!

Day 3 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did:  https://www.codewars.com/kata/consecutive-strings/javascript

Time: 20 minutes

What I’ve learnt: I was able to implement manipulating a for loop, by adjusting the value of i, instead of just setting ` i = 0`.  I always feel so in control of my loop when I’m able to implement this. 😉

Since there were certain conditions I can automatically know what it returns (if the second value is greater than the string arrays length, or if the second value is 0 or less), I avoided the iteration and set the return right away. (This is what we learned from yesterday’s challenge!)

Here was my solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function longestConsec(strarr, k) {
    let greatestWordComboLength = 0
    let finalString = ""
    
    if (k > strarr.length || k < 1) return ""
    
    for (let i = k-1; i < strarr.length; i++){
      
      let currentComboLength = 0
      let currentCombinedString = []
      
      for (let w = 0; w < k; w++){
        currentComboLength = currentComboLength + strarr[i - w].length
        currentCombinedString.unshift(strarr[i - w])
      }     

      if (currentComboLength > greatestWordComboLength){
        greatestWordComboLength = currentComboLength
        finalString = currentCombinedString.join("")
      } 
    }
    return finalString
}

 

What I learned from other people’s code:

 

Slice is something I see very often in other people’s code. It is something I have to get more comfortable with. It will help to manipulate the array on the spot, so I don’t have to make a new array the way I want it to return.

NOTE TO SELF: Start using slice!!

See you tomorrow!!

Day 2 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did https://www.codewars.com/kata/5898b4b71d298e51b600014b

Time: 25 minutes

I’ve used slice today!  It really helped keep this concise without having to keep creating variables, since slice does not mutate the original.

Here was my solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function sortTheInnerContent(words) {
  
  return words.split(' ').map(word => {
    let newWord = word[0]
    word.length > 2 ? newWord += word.slice(1,word.length-1).split('').sort().reverse().join('') : null
    if (word.length > 1) newWord += word[word.length-1]
    
    return newWord
  }).join(' ');
}

 

What I learned from other people’s code:

I really have to start getting more comfortable with regex. It’s amazing how you can do so much with it. Although I do find it harder for the next dev to jump right into the code.

I see people use .substr which is not something I have seen yet. That is another nice way to non-destructively grab a part out your string.

const string = “Hello”

string.substr(2, 2) // “ll”

string // “Hello”

Ready for the next Kata!!

Day 1 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did https://www.codewars.com/kata/scrabble-best-word/javascript

Time: 33 minutes

What I’ve learnt: It’s important to read the instructions! I spent 15 minutes solving the problem, than another 15 wondering why it was not working until a friend said they want the highest rated word — not the lowest rated one!

So then I spent another 3 minutes moving around my greater than and less than signs 🙂

I was not happy I had two loops within each other (O^2), but I was not sure if I should worry more about the time to completion or the actual code (as I am preparing for interviews). So I went with trying to keep the solving time lower than the processing time.

Here was my solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
function getBestWord(points,words){
  let highestValueWord = 0
  let highestIndex = ""
  
  for (let i = 0; i < words.length; i++){
    
    let wordValue = 0
    
    words[i].split("").forEach(letter => {
      wordValue += points[(letter.charCodeAt() - 65)]
    })
    
    if (wordValue > highestValueWord){
      highestValueWord = wordValue
      highestIndex = i
    } else if (wordValue === highestValueWord && words[i].length < words[highestIndex].length){
      highestValueWord = wordValue
      highestIndex = i
    }
  }
  return highestIndex
}

 

I do realize I could have saved my else if and the extra code by placing that condition in an || after the first if.

 

What I learned from other people’s code:

More or less everyone needed 2 loops, but they did not keep them inside the next, they kept them one below the other in order to keep the exponential growth away, and has 0*2.

There were no one line solutions that make me wonder why I have so many lines 🙂

charCodeAt()-65 was commonly used across other solutions.

No new functions I was not aware of, just different ways to implement the logic (mostly with sort, split,  map, and reduce).

Getting ready for Day 2!

Dispatching Redux

When I think of redux this is what comes to mind:

And that’s not because I was ready to have my brain checked when starting to learn React/Redux 🙂

I am writing this post to explain to you how I think of React/Redux, and how it helped me better understand it, and I hope it can help you too!

This is not a detailed walk through, for tutorials on React/Redux I can recommend:

Among many of the fabulous resources out there people have taken the time out to help us understand this framework.

So now back to my ambulances…

If we want to have a function that will not be called on load, but rather upon an action — for example an onClick function, we cannot put the () after the function as that will call it as soon as the page loads it. We can’t put the function without the () because that will just show what’s contained in the function instead of ever running it. We need to somehow bind that function to the event so it can be triggered exactly when we want it to with the applicable event/data.

In redux to accomplish this we  dispatch the function. Here is a code example from my repo – https://github.com/mxdavis/timer-billing-client/

import {removeTask} from '../../redux/actions/tasks/tasks'

....

  handleDelete = event => {
    event.preventDefault();
    ...
    this.props.removeTask(this.state)
}

render(){
  return(
     ...
      <div className="uk-width-2-2 uk-text-center">
         <button
           onClick={this.handleDelete} 
           type="delete"
           value="Delete Task"
           >X</button>
        </div>
      ...
   )
}

...

const mapDispatchToProps = dispatch => {
  return bindActionCreators(
    { fetchClients, addTask, removeTask }, dispatch);
};

export default connect(mapStateToProps, mapDispatchToProps)(AddTask);

 

Here we have the a delete button that dispatches an action removeTask onClick. Since I use mapDispatchToProps I do not need to put dispatch(removeTask(this.state)) instead if I use this.props.removeTask(this.state), the mapDispatchToProps already bound dispatch to removeTask and I can access it through props.

This function is an action and looks like so:

export function removeTask(task){
  return {
    type: 'REMOVE_UNBILLED_TASK',
    task
  }
}

The file was able to find it, because I had imported it previously (see the top line of the previous code snippet). I could have had this function locally in the folder, but to keep the file from getting too heavy I put it in an actions folder.

Now this action is being dispatched from the emergency call center to all the medics who have their radios always on waiting to accept the signal. And the medic in the right area that fits the type needed responds to the action and does what it is told to do.

This is where the reducers come in.

The reducers are set up in the store (normally through a combinedReducers, as there are frequently more than one reducer). Here is an example of my file that sets up redux store:

import {createStore, applyMiddleware, combineReducers } from 'redux'
import thunk from 'redux-thunk'

import clients from '../reducers/clients/clients'
import tasks from '../reducers/tasks/tasks'
import fetchingData from '../reducers/fetchingData'

const reducers = combineReducers({
  tasks, clients, fetchingData
})

const middleware = [thunk]

export default createStore(
  reducers, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(), 
  applyMiddleware(...middleware)
)

 

The combineReducers is combining all my reducers, and we pass this into createStore.

What this does is give the reducers each their own radio that is turned on and ready to listen when an action is being called just like when a person starts working as a medic he is given a radio that he needs to leave on and always listen to.

If you put a debugger in a reducer, you will see that it is called each time the page/app renders, even if the action never called that particular one, or if even any action is called at all.

Reducers are case statements looking for a string that matches the action.type that the action sent out.

With each state update, it checks to see if the action.type has been called, and if it does it will run the code inside.

Back to our analogy, when a medic’s radio hits based on certain criteria, he will receive the follow up instructions, while everyone else’s radio will stay silent as they do not need to be disturbed yet. If we had all our medics responding to every call they would be running all over the place, and not actually showing up to anyone on time and in an efficient manner. And not to mention, they’d probably all quit, and work for a more efficient team that knew how to alert only medics in the vicinity or medics with the equipment necessary for the call…

Here is what my reducer looks like that will match the string ‘REMOVE_UNBILLED_TASK’:

export default function tasks(state = {
    unbilled_tasks: [], 
    billed_tasks: []
}, action) {
  switch (action.type) {
  ...
    case 'REMOVE_UNBILLED_TASK':
      const tasksWithoutDeletedTask = state.unbilled_tasks.filter(t => t.task_id !== action.task.task_id)
      return Object.assign({}, state, {unbilled_tasks: tasksWithoutDeletedTask})
    default:
      return state;
  }
};

 

Always remember that since every reducer function gets called with each render we need to include a default option in our case statement that returns the current state, so that we do not end up with an empty state each time the page updates.

Keep this in mind when creating your reducers.

So to sum up my analogy, our medics/reducers always have their radios on waiting to be called, and this we set up by creating the redux store with our combinedReducers (unless we have only one reducer then we just put that one reducer in the store). The functions from the component dispatch actions only when they are triggered, and not upon load of the page (like onClick, or onChange..), which our component (medical center) sends the action.types to the correct (medic) reducer (instead of running all actions on load, and sending all medics on every call which would be extremely inefficient and time consuming!).

I hope I was able to help some people better understand the redux cycle. This was my first react/redux project and this concept really helped getting me started.

Implemented Javascript into my Recipes App

I implemented some asynchronous requests on my Recipes app so the user does not have to reload the page when they do something small such as favorite a recipe or add a comment.

To allow users to favorite their recipes I hijacked the click with jquery, sent a get request to my server to get back the favorite JSON (I was able to use the nested route of recipe with the data from the link, because it was embedded in a recipe), and if the data retrieved was NULL then we know that this recipe had not been previously favorited by this user. I created a Class Object Favorite with the JSON received if it was not null, and if it was null I just added the Recipe ID we already have :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$.get("/recipes/" + recipeId + "/favorite.json", function(favorite) {
      if (favorite == null){
        f = new Favorite(recipeId)
      }else{
        f = new Favorite(recipeId, favorite.data.attributes["user-id"], favorite.data.id)
      }
      dom.currentTarget.children["0"].innerHTML = f.changeHeart()
      dom.currentTarget.className = f.changeClass()

      $.post("/recipes/" + recipeId + "/favorite", f)

    });

Here’s my Class Object

1
2
3
4
5
6
7
class Favorite {
  constructor(recipeId, userId, id) {
    this.recipeId = recipeId
    this.userId = userId
    this.id = id
  }
}

Once in the database, I was able to check if the favorite existed already, and either create or delete it depending on what existed already. But in the DOM I needed to update the class and picture, as well as the object in case the user toggled back and forth before a refresh, it should still work. I created two methods on the prototype to handle this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
Favorite.prototype.changeClass = function(){
  if(this.id){
    return 'favorites favorite'
  } else {
    return 'favorites favorited'
  }
}

Favorite.prototype.changeHeart = function(){
  if(this.id){
    return '<img src="/assets/heart.png" alt="Heart">'
  } else {
    return '<img src="/assets/heart-red.png" alt="Heart">'
  }
}

And then called it on the object which was tied to a variable called c, which was set at the top of the file so it would be available globally

1
2
      dom.currentTarget.children["0"].innerHTML = f.changeHeart()
      dom.currentTarget.className = f.changeClass()

Implementing Javascript to my app has been quite the ride. Handling one small click, could take hours of time just to end up with 7 lines of code. But it makes the user experience that much better, and isn’t that who we are developing for?

Copyright Loving to Code 2025
Tech Nerd theme designed by Siteturner