Posts

Showing posts from December, 2024

Javascript Challenge 1

# Javascript Challenges ## Challenge 1 - Try to guess what the below code prints. - Fix the code ``` let person = { name: 'John Doe', getName: function() { console.log(this.name); } }; setTimeout(person.getName, 1000); ``` Lets do some analysis ### When Method is in an Object: - The method `getName` is initially defined as part of the `person` object. - When you call `person.getName()`, the `this` keyword refers to the `person` object. So `this.name` would correctly return 'John Doe'. ### The Issue with `setTimeout` - However, when a function is passed as a callback (like `person.getName` in this case), it loses its context (i.e., the reference to the person object). - Instead, the value of `this` inside `getName` changes to the global object (window in browsers, or global in Node.js). - In non-strict mode, the global object (`window `in browsers) doesn't have a name property, so `this.name` becomes `undefined`. ### How `this` changes in `setTi...

Java8 Stream Examples

In this post, we'll discuss some common Stream Operations - collect(Collectors.toList()) This is a *eager* operation. Below is one such example ``` List<String> collected = Stream.of("a","b","c").collect(Collectors.toList()); assertEquals(Arrays.asList("a","b","c"),collected); ``` We convert the values from Stream to List. - Convert Strings to uppercase - Java7 way ``` List<String> collected = new ArrayList<>(); for (String string : asList("a","b","hello")){ String upperCase = string.toUpperCase(); collected.add(upperCase); } ``` - Java8 way ``` List<String> collected = Stream .of("a","b","hello") .map( string -> string.toUpperCase()) .collect(toList()); ``` - Identify strings starting with a number - Java7 way ``` ...

Java8 Introduction

# Getting Started Consider the following snippet ``` button.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e){ System.out.println("Button Clicked"); } } ) ``` As we can see, there are few observations - Lots of *boilerplate* code - It obscures the Programmer's intent - We are giving button an object that represents an action ( we are using code as data) Now, consider the following declaration ``` button.addActionListener( event -> System.out.println("Button Clicked")); ``` It does the same job as before but we can see the following: - Block of code - a function without a name - event is the name of the parameter - Instead of an object that implements an interface, we are passing in a *block of code*. - We don't provide the 'type' for event, *javac* infers it as an Action Event. Congrats! you've written your first *lambda* expression! ## Different ways o...