The Journey of #100DaysOfCode (@henna_dev)

#Day87 of #100DaysOfCode

Adulthood is hard, adjusting to new situations is hard, and bonding with someone is sometimes hard… Lol… The only things I can think of now are the hard things… I wish life was easier :stuck_out_tongue: but then some would say, where’s the fun in that… :wink:

Today was okayish, my morning went well… I had a one-day 5:00 am club wake-up… :sunny: I was able to add more details to my presentation and I also answered a few realm queries on our forums.

I tried to understand the difference between User Objects, Custom-user-data and User meta-data. I have to say it messed up my brain. :face_with_peeking_eye:

I found out custom-user data is only a convenience thing, it pre-fetches the custom user-data object so it’s accessible from the user object in the functions, w/o having to query a realm or MongoDB Atlas. Custom user data is only refreshed when the user’s login token gets refreshed, so it can be up to 20 minutes old at any time. So, it’s better to just query MongoDB directly in the functions

I made some progress on Restaurant App, instead of using a click-listener on the marker, I will have a menu option to click and start Friends Activity. Here I will have a function to add the friend and then share the location with him.

The next part left is how will the friend receive this data and how will this be displayed on Map. It has been a good experience working on this application, but I wish I had more time to streamline my thoughts…

I am a bit exhausted today so that’s all for today.

Until tomorrow, :performing_arts:

1 Like

#Day88 of #100DaysOfCode

Today was a difficult day, most of my days are like that now… One day I am fine and the next I am not. Every day feels like a fight :frowning: I am glad to have a supportive partner…

I visited the Pet store again for my dopamine, I can’t wait to have my bunnies home… I named them as well “Onyx and Buster”, black and orange white… :heart_eyes:

Today I continued on Restaurant App, I shared the concept with John who is a genius engineer, and got some suggestions that I implemented. It will take some time to finish it completely. I feel so dumb :cry: Even the easiest of tasks appear hard to me now…

I read and documented a post on spinning up a local server. I dint test it with javascript code which I would do perhaps another day.

Until tomorrow :performing_arts:

#Day89 of #100DaysOfCode

Today was a productive day, I felt relieved after speaking my heart out to the person who actually put me in that state… Well that’s how life works :wink: The person who makes you smile is also the person who makes you cry :stuck_out_tongue:

I made good progress in Restaurant App. I completely revised the structure as John suggested. He is a genius, so what he says is always true without a doubt :smiley: I am glad I reached out in time.

Since my previous state of the app was not taking into account offline access, I restructured it to make offline access possible. I downloaded all data from Atlas and then provided dropdown boxes to select locations or cuisine from.

The next part is displaying the list of restaurants in that location or as per cuisine and then allowing the user to give rating.

My Activity code is as below:

   private fun searchCuisines() {
        val config = SyncConfiguration.Builder(user!!, "NewYork")
            .waitForInitialRemoteData()
            .build()

        Timber.d("Opening Realm instance Asynchronously")
        /**
         * Should print false if its opening for the first time
         */
        Timber.d("${File(config.path).exists()}")

        Realm.getInstanceAsync(config, object: Realm.Callback() {
            override fun onSuccess(realm: Realm) {

                val allData: RealmResults<Restaurant> = realm.where<Restaurant>().distinct("cuisine").findAll()
                displayCuisineDropdown(allData)
            }
        })
    }

    private fun displayCuisineDropdown(allData: RealmResults<Restaurant>) {
        Timber.d("Synced Cuisine count ${allData.size}")
        binding.progress.visibility = View.GONE
        val list = ArrayList<String?>()

        allData.forEach{
            list.add(it.cuisine)
        }
        val arrayAdapter = ArrayAdapter(this, R.layout.dropdown_cuisine, list)
        binding.autoCompleteCuisine.setAdapter(arrayAdapter)

        binding.autoCompleteCuisine.addTextChangedListener(object: TextWatcher{
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(value: CharSequence?, p1: Int, p2: Int, p3: Int) {
                val intent = Intent(applicationContext, RestaurantListActivity::class.java)
                intent.putExtra("CUISINE",value.toString()!!)
                intent.putExtra("FLAG","cuisine")
                startActivity(intent)
            }

            override fun afterTextChanged(p0: Editable?) {

            }
        })
    }

    private fun searchLocations() {

        val config = SyncConfiguration.Builder(user!!, "NewYork")
            .waitForInitialRemoteData()
            .build()

        Timber.d("Opening Realm instance Asynchronously")
        /**
         * Should print false if its opening for the first time
         */
        Timber.d("${File(config.path).exists()}")

        Realm.getInstanceAsync(config, object: Realm.Callback() {
            override fun onSuccess(realm: Realm) {

                val allData: RealmResults<Restaurant> = realm.where<Restaurant>().distinct("borough").findAll()
                displayLocationDropdown(allData)

            }
        })
    }

    private fun displayLocationDropdown(allData: RealmResults<Restaurant>) {
        Timber.d("Synced Location count ${allData.size}")
        binding.progress.visibility = View.GONE
        val list = ArrayList<String?>()

        allData.forEach{
            list.add(it.borough)
        }
        val arrayAdapter = ArrayAdapter(this, R.layout.dropdown_location, list)
        binding.autoCompleteLocation.setAdapter(arrayAdapter)

        binding.autoCompleteLocation.addTextChangedListener(object: TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(value: CharSequence?, p1: Int, p2: Int, p3: Int) {
                val intent = Intent(applicationContext, RestaurantListActivity::class.java)
                intent.putExtra("LOCATION",value.toString()!!)
                intent.putExtra("FLAG","location")
                startActivity(intent)
            }

            override fun afterTextChanged(p0: Editable?) {
            }

        })
    }

The UI looks as below

Until tomorrow… :performing_arts:

#Day90 of #100DaysOfCode

Today was a productive Saturday… We had a good breakfast, I made good progress on my Restaurant app. I was hoping I would finish it but I got stuck at the last logic… but I am hopeful I will be able to finish it tomorrow :crossed_fingers:

I also visited PetStore to check my bunnies… but one of them got a stomach infection and they were all in quarantine, now we will have to wait for another week. So we are getting this black and white pair… :heart_eyes:

I made Restaurant List Activity and Restaurant Detail, I am left with implementing the logic of rating.

  val extras = intent.getStringExtra("FLAG")

        Timber.d("Getting Realm config ")
        val config = SyncConfiguration.Builder(newYorkApp.currentUser()!!, "NewYork")
            .build()

        if(extras.equals("location")){
            val location = intent.getStringExtra("LOCATION")
            title =  location!!
            displayRestaurantAt(location, config)
            
        }else {
            val cuisine = intent.getStringExtra("CUISINE")
           title = cuisine!!
            displayRestaurantWith(cuisine, config)
        }

        Timber.d("partition is $extras")
        recyclerView = binding.rvList
        recyclerView.layoutManager = LinearLayoutManager(this)
    }

    private fun displayRestaurantWith(cuisine: String, config: SyncConfiguration) {

        Realm.getInstanceAsync(config, object: Realm.Callback() {
            override fun onSuccess(realm: Realm) {

                val restaurantList: RealmResults<Restaurant> = realm.where<Restaurant>()
                    .equalTo("cuisine", cuisine).findAll()
                updateUI(restaurantList)
            }
        })
    }

    private fun displayRestaurantAt(location: String, config: SyncConfiguration) {

        Realm.getInstanceAsync(config, object: Realm.Callback() {
            override fun onSuccess(realm: Realm) {

                val restaurantList: RealmResults<Restaurant> = realm.where<Restaurant>()
                    .equalTo("borough", location).findAll()
                updateUI(restaurantList)
            }
        })
    }

    private fun updateUI(restaurantList: RealmResults<Restaurant>) {

        Timber.d("Synced restaurants count ${restaurantList.size}")
        binding.progress.visibility = View.GONE

        //Timber.d(restaurantList.asJSON())

        adapter = RestaurantAdapter(restaurantList)
        recyclerView.adapter = adapter
        recyclerView.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
    }

The UI looks like the below, the detail screen is still WIP

Until Tomorrow… :performing_arts:

#Day91 of #100DaysOfCode

Today was an amazing day. I wrapped up my Restaurant App and am pretty much happy with what I have implemented and my nervousness is piling up for my talk next week… :grimacing:

We visited Sunday Market, had a coffee with cheese onion, and cinnamon twisters, and visited Petstore to see our bunnies :orange_heart: fills my heart with so much love looking at them :smiling_face_with_three_hearts: I really need to pay more attention to other better things and get less attached to work… :stuck_out_tongue:

So I modified Restaurant Detail Activity, I also did error handling today and got to know soo much about Realm… I am last bit stuck on updating my embedded document. I will either have to create a new collection or will have to wait for the engineer to give me a resolution because I don’t know… :-/

So my Detail Activity looks as below:


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityRestaurantDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)

         restID = intent.getStringExtra("RESTID")

         Timber.d("Setting Realm instance again")
        config = SyncConfiguration.Builder(newYorkApp.currentUser()!!, "NewYork")
            .build()

        binding.addReviewBtn.setOnClickListener{
            val input = EditText(this)
            val dialogBuilder = AlertDialog.Builder(this)
            dialogBuilder.setMessage("Add a review for this restaurant:")
                .setCancelable(true)
                .setPositiveButton("Add"){dialog, _->
                    val review = input.text.toString()
                    dialog.dismiss()
                    addReviewToDatabase(review)
                }
                .setNegativeButton("Cancel"){dialog, _ ->
                    dialog.cancel()
                }
            val dialog = dialogBuilder.create()
            dialog.setView(input)
            dialog.setTitle("Add Restaurant Review")
            dialog.show()
        }
        recyclerView = binding.rvReviews
    }

    private fun addReviewToDatabase(userReview: String) {

        val review = Reviews(review = userReview, userid = newYorkApp.currentUser()!!.id, username = newYorkApp.currentUser()!!.profile.name)

    }

    override fun onStart() {
        super.onStart()
        getRestDetail(config)
    }

    private fun getRestDetail(config: SyncConfiguration) {

        Realm.getInstanceAsync(config, object: Realm.Callback() {
            override fun onSuccess(realm: Realm) {

              val restaurant = realm.where<Restaurant>()
                    .equalTo("restaurant_id", restID).findFirst()
                reviewRealm = realm
                title = restaurant?.name
                binding.tvName.text = restaurant?.name
                 stringBuilder.append(restaurant?.address?.building).append(" ").append(restaurant?.address?.street).append(" ").append(restaurant?.address?.zipcode)
                binding.tvAddress.text = stringBuilder
                if(restaurant?.reviews?.size==0){
                    binding.tvNoReview.visibility = View.VISIBLE
                    binding.progress.visibility = View.GONE
                }else {
                    displayReviewAdapter(restaurant)
                }
            }
        })

    }

    private fun displayReviewAdapter(restaurant: Restaurant?) {
        adapter = ReviewsAdapter(restaurant!!.reviews)
        binding.tvNoReview.visibility = View.GONE
        setUpRecyclerView()
    }

    private fun setUpRecyclerView() {
        binding.progress.visibility = View.GONE

        recyclerView.layoutManager = LinearLayoutManager(this@RestaurantDetailActivity)
        recyclerView.adapter = adapter
        recyclerView.setHasFixedSize(true)
        recyclerView.addItemDecoration(DividerItemDecoration(this@RestaurantDetailActivity, DividerItemDecoration.VERTICAL))
    }

    override fun onDestroy() {
        super.onDestroy()
        recyclerView.adapter = null
        // if a user hasn't logged out when the activity exits, still need to explicitly close the realm
        reviewRealm.close()
    }

The UI is also better than before:

I also spent time updating my presentation. But I will take another day to finish, perhaps will wake up early morning tomorrow.

Until next update… :performing_arts:

#Day92 of #100DaysOfCode

Today was a tiring day. I spent a lot of time fixing errors I was getting in my application. Once again, many thanks to @ChristanMelchior for all his help in resolving these errors.

I absolutely had a lot of fun creating this app and dove deeper into realm. I also worked on my presentation. I am very nervous about my presentation… This happens every time I participate in a talk :-/

Some of the errors I solved:

Caused by: java.lang.IllegalArgumentException: Configurations cannot be different
 if used to open the same file.

Caused by: java.lang.IllegalArgumentException: Embedded objects cannot be 
copied into Realm by themselves. They need to be attached to a parent object


java.lang.IllegalStateException: Only use this adapter with managed RealmCollection,

The app working is as below

Until tomorrow :performing_arts:

1 Like

#93Day of #100DaysOfCode

The morning started stressful as I didn’t feel too prepared for my presentation, but all fell into place by the afternoon. I had 4 practice sessions, got good feedback from 3 amazing people, and solo practice.

As it was almost 50 min talk, I got too exhausted after all the practice and I went out for a big feast to fill my stomach :wink:

Today I am doing some funny codewars.

Problem Description

Timmy & Sarah think they are in love, but around where they live, they will only know once they pick a flower each. If one of the flowers has an even number of petals and the other has an odd number of petals it means they are in love.

Write a function that will take the number of petals of each flower and return true if they are in love and false if they aren’t.

Solution

(I did the stupidest solution :stuck_out_tongue: )

function lovefunc(flower1, flower2){
  // moment of truth
  if(flower1%2==0 && flower2%2>0 || flower2%2==0 && flower1%2>0){
    return true
  }else {
    return false
  }
}

Best Solutions

function lovefunc(flower1, flower2){
  return flower1 % 2 !== flower2 % 2;
}

function lovefunc(flower1, flower2){
  return (flower1 + flower2) % 2 === 1

Return a Negative

In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative?

makeNegative(1);    // return -1
makeNegative(-5);   // return -5
makeNegative(0);    // return 0
makeNegative(0.12); // return -0.12

Solution

I can’t believe I was doing string concatenation on this… Thats the sign of exhausted brain :stuck_out_tongue:

function makeNegative(num) {
  // Code?
  if(num<=0){
    return num
  }else {
    return num * -1
  }
}

Last Problem of the Day

Description

Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives.

invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5]
invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5]
invert([]) == []

Solution

function invert(array) {
  
  let array1 =[]

  for(let i=0; i<array.length; i++){
    array1[i] = array[i] * -1
  }
  return array1
}

I am traveling to London tomorrow, so see you from there… :wink:

Cheers, :performing_arts:

#Day94 of #100DaysOfCode

Today was an amazing day… :smiling_face_with_three_hearts: I came to London for my Devoxx Talk and we had Speakers Dinner tonight and I met such an amazing group of people :orange_heart: who were soooooo friendly and I got soo much help on my Community Program Strategies… and I cant wait to start things…

I am a bit tired so will continue some codewars… Tomorrow will be a day of sessions… so will write about them.

Problem Description

Create a function with two arguments that will return an array of the first (n) multiples of (x).

Assume both the given number and the number of times to count will be positive numbers greater than 0.

Return the results as an array.

Examples:

countBy(1,10) === [1,2,3,4,5,6,7,8,9,10]
countBy(2,5) === [2,4,6,8,10]

Solution

I know this can be much better presented, but this is my first attemp

function countBy(x, n) {
  let i=0;
  let k=1;
  let z =[];
  
  for(let j=0; j<n;j++){
    z[i] = x * k;
    i++;
    k++;
  }

  return z;
}

Better Solutions

function countBy(x, n) {
    var z = [];
    for (i = 1; i <= n; i++) {
        z.push(x * i);
    }
    return z;
}

const countBy = (x, n) => Array.from({length: n}, (v, k) => (k + 1) * x)

Abbreviate a two word name

Write a function to convert a name into initials. This kata strictly takes two words with one space in between them.

The output should be two capital letters with a dot separating them.

It should look like this:

Sam Harris => S.H

patrick feeney => P.F

Solution

function abbrevName(name){

    // code away
  let space = name.indexOf(" ")
  let firstChar = name[0]
  let secondChar = name[space+1]
  return firstChar.toUpperCase() + "." + secondChar.toUpperCase()
}

That’s all today. Until tomorrow :performing_arts:

1 Like

#Day95 of #100DaysOfCode

Another tiring day but full of networking and meeting amazing folks. I had the bestest day of my life… :smiling_face_with_three_hearts: I met leaders of Dublin and London Java groups and I look forward to collaborating with them for our mobile talks… :heart_eyes:

Another session of codewars

Problem Description

Complete the square sum function so that it squares each number passed into it and then sums the results together.

For example, for [1, 2, 2] it should return 9 because 1^2 + 2^2 + 2^2 = 9

Solution

function squareSum(numbers){

  let array =  numbers.map(number => number * number)
  
  return array.reduce((one, two) => one + two, 0)
}

Sample Tests

describe("Tests", () => {
  it("test", () => {
Test.assertEquals(squareSum([1,2]), 5)
Test.assertEquals(squareSum([0, 3, 4, 5]), 50)
Test.assertEquals(squareSum([]), 0)
});
});

Problem Description

Can you find the needle in the haystack?

Write a function findNeedle() that takes an array full of junk but containing one "needle"

After your function finds the needle it should return a message (as a string) that says:

"found the needle at position " plus the index it found the needle, so:

findNeedle(['hay', 'junk', 'hay', 'hay', 'moreJunk', 'needle', 'randomJunk'])

Solution

function findNeedle(haystack) {
  // your code here
  
let index = haystack.indexOf("needle");

return "found the needle at position " + index;
}

Sample Tests

describe("Tests", () => {
  it("test", () => {
var haystack_1 = ['3', '123124234', undefined, 'needle', 'world', 'hay', 2, '3', true, false];
var haystack_2 = ['283497238987234', 'a dog', 'a cat', 'some random junk', 'a piece of hay', 'needle', 'something somebody lost a while ago'];
var haystack_3 = [1,2,3,4,5,6,7,8,8,7,5,4,3,4,5,6,67,5,5,3,3,4,2,34,234,23,4,234,324,324,'needle',1,2,3,4,5,5,6,5,4,32,3,45,54];

Test.assertNotEquals(findNeedle(haystack_1), undefined, "Your function didn't return anything");
Test.assertEquals(findNeedle(haystack_1), 'found the needle at position 3')
Test.assertEquals(findNeedle(haystack_2), 'found the needle at position 5') 
Test.assertEquals(findNeedle(haystack_3), 'found the needle at position 30')
  });
});

Problem Description

Very simple, given an integer or a floating-point number, find its opposite.

Examples:

1: -1
14: -14
-34: 34

Solution

function opposite(number) {
  //your code here
  return number * -1
}

Sample Tests

describe("Tests", () => {
  it("test", () => {
Test.assertEquals(opposite(1), -1,)
  });
});

That is all for today…

1 Like

#Day96 of #100DaysOfCode

Today was the D day of the talk… It was a great first experience… I wish the wifi was not that bad and then it would have gone fine… but it was cool… I got some great suggestions from people of the community and for that I am sooooo happy :orange_heart:

For all those, who will drop by 100DaysOfCode, below is the link to the Restaurant App, I will upload the slides as well

Today I also studied Asynchronous Operations in JavaScript and how to construct Promise… :smiley: while waiting at the airport :wink:

That’s all today…

Cheers :performing_arts:

1 Like

#Day97 of #100DaysOfCode

A sunny day spent out with friends and drinks and a good breakfast and walk.

It took me a long time to solve this codewar. I used both forEach and map method and I did not get the correct results. Took steps and then console.log everything. The problem is uploaded to Github with details.

I also studied setTimeout() function of Node used in Promises that takes time to resolve or reject. Will write more on this tomorrow.

Cheers, :performing_arts:

1 Like

#Day98 of #100DaysOfCode

Today was cleaning and cooking day :wink: It’s been a while since I cooked… I was relaxed a bit after the Devoxx talk… I was soo nervous about it. I woke up at 3:30 am in the morning on the day and could not go back to sleep… :stuck_out_tongue:
I look forward to finishing some more tasks this week, but let’s write on the 98th day. In continuation of Javascript Promise, which I did 2 days ago, it’s important to know how to consume and use the promises.

The Node setTimeout() Function

It is important to know how to handle Promise objects returned as a result of an asynchronous operation. setTimeout() is a Node API that uses callback functions to schedule tasks to be performed after a delay.

setTimeout() has two parameters: a callback function and a delay in milliseconds.

const delayedHello = () => {
  console.log('Hi! This is an asynchronous greeting!');
};
 
setTimeout(delayedHello, 2000);

This delay is performed asynchronously and does not stop executing the rest of the program. Asynchronous JavaScript uses something called the event-loop. After two seconds, delayedHello() is added to a line of code waiting to be run. Before it is run, the synchronous code in the program continues to run. This also means it might take more than 2 seconds.

Executing the following code by calling node app.js will give an idea

console.log("This is the first line of code in app.js.");

const usingSTO = () => {
  console.log("This is STO inside")
}

setTimeout(usingSTO, 2500)

console.log("This is the last line of code in app.js.");

Consuming Promises

The initial state of an asynchronous promise is pending but it eventually settles. Promise objects come with an aptly named .then() method. It allows to say, “I have a promise, when it settles, then here’s what I want to happen…”

.then() is a higher-order function— it takes two callback functions as arguments. These callbacks are called handlers. When the promise settles, the appropriate handler is invoked with the settled value.

  • The first handler, called onFulfilled , is a success handler, and contains the logic for the promise resolving.

  • The second handler, called onRejected , is a failure handler, and contains the logic for the promise rejecting.

If the appropriate handler is not provided, instead of throwing an error, .then() returns a promise with the same settled value as the promise it was called on. One important feature of .then() is that it always returns a promise.

Will continue on the Success and Failure Callback Functions tomorrow.

I also did one codewar today. I am trying to make this habit of solving one everyday :smiley:

Cheers, :performing_arts:

2 Likes

#Day99 of 100daysofcode

Today has been a busy day at work. After a long time, I feel relaxed, satisfied, and at peace :smiling_face: with my work self and I look forward to doing exciting things :orange_heart:

Let’s continue further on JavaScript Promises.

Success and Failure Callback Functions

To handle a “successful” promise, or a promise that resolved, we invoke .then() on the promise, passing in a success handler callback function:

const prom = new Promise((resolve, reject) => {
  resolve('Yay!');
});
 
const handleSuccess = (resolvedValue) => {
  console.log(resolvedValue);
};
 
prom.then(handleSuccess); // Prints: 'Yay!'

In the code, prom is a promise that will resolve to “Yay!”. handleSuccess is a function that logs the argument passed to it. The function is passed to the prom’s .then() function and is invoked when prom resolves logging Yay! to the console.

In a practical promise consumption, a promise can resolve or reject so it’s useful to provide logic in either case. Both the success and failure callback can be passed to .then()

let prom = new Promise((resolve, reject) => {
  let num = Math.random();
  if (num < .5 ){
    resolve('Yay!');
  } else {
    reject('Ohhh noooo!');
  }
});
 
const handleSuccess = (resolvedValue) => {
  console.log(resolvedValue);
};
 
const handleFailure = (rejectionReason) => {
  console.log(rejectionReason);
};
 
prom.then(handleSuccess, handleFailure);
  • prom is a promise that will randomly either resolve with 'Yay!' or reject with 'Ohhh noooo!' .

  • Two handler functions are passed to .then() . The first will be invoked with 'Yay!' if the promise resolves, and the second will be invoked with 'Ohhh noooo!' if the promise rejects.

Note: The success callback is sometimes called the “success handler function” or the onFulfilled function. The failure callback is sometimes called the “failure handler function” or the onRejected function.

Problem Description

Write a success and failure handlers for Inventory Function defined in library.js file

library.js

const inventory = {
  sunglasses: 1900,
  pants: 1088,
  bags: 1344
};

const checkInventory = (order) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let inStock = order.every(item => inventory[item[0]] >= item[1]);
      if (inStock) {
        resolve(`Thank you. Your order was successful.`);
      } else {
        reject(`We're sorry. Your order could not be completed because some items are sold out.`);
      }
    }, 1000);
  })
};

module.exports = { checkInventory };

Solution in app.js

const {checkInventory} = require('./library.js');

const order = [['sunglasses', 1], ['bags', 2]];

// Solution  code below:

const handleSuccess = (resolvedValue) => {
 console.log(resolvedValue)
}

const handleFailure = (rejectedValue) => {
 console.log(rejectedValue)
}

checkInventory(order).then(handleSuccess, handleFailure)

Solved another codewar on getting the longest string from two strings.

Tomorrow will write about using catch() with Promises.

Cheers, :performing_arts:

1 Like

#Day100 of #100DaysOfCode

Today was a busy day with multiple things to finish and I also presented a talk to the team about MongoDB and Realm which was fun. :star_struck: and today is the final day. I finished 100-day streak, I cant believe it…
It was such an amazing experience :orange_heart:

I studied further on JavaScript Promises

Using catch() with Promises

It’s always helpful to debug code when the code is organised into distinct sections each handling a specific task. Instead of passing both handlers into one .then() , we can chain a second .then() with a failure handler to a first .then() with a success handler and both cases will be handled.

prom
  .then((resolvedValue) => {
    console.log(resolvedValue);
  })
  .then(null, (rejectionReason) => {
    console.log(rejectionReason);
  });

To create more readable code, A different promise function: .catch() can be used.

The .catch() function takes only one argument, onRejected . In the case of a rejected promise, this failure handler will be invoked with the reason for rejection. Using .catch() accomplishes the same thing as using a .then() with only a failure handler.

prom
  .then((resolvedValue) => {
    console.log(resolvedValue);
  })
  .catch((rejectionReason) => {
    console.log(rejectionReason);
  });
  • If the promise rejects, .then() will return a promise with the same rejection reason as the original promise and .catch() ‘s failure handler will be invoked with that rejection reason.

The same previous code with catch() can be written as

checkInventory(order).then(handleSuccess).catch(handleFailure)

I solved an easy codewar today.

Is this a Triangle?

Given 3 sides of a triangle, return true if a triangle can be formed or otherwise false.

Solution

Applying Triangle Inequality Theorem, the sum of 2 sides must be greater than the third side

function isTriangle(a,b,c)
{
   if(a+b>c && a+c>b && b+c >a) return true
  else return false
}

Sample Tests

const { assert } = require("chai")

describe("Public tests", () => {
  it("Testing for fixed tests", () => {
    assert.strictEqual(isTriangle(1,2,2), true);
    assert.strictEqual(isTriangle(7,2,2), false);
  });
})

With this, I finish the 100 day marathon and now I am gonna go and enjoy some CTR car racing on PS4 :stuck_out_tongue: :wink:

Until we start next time… :tada: :wave: :kissing_heart:

2 Likes

This topic was automatically closed after 180 days. New replies are no longer allowed.