Showing posts sorted by relevance for query javascript. Sort by date Show all posts
Showing posts sorted by relevance for query javascript. Sort by date Show all posts

Saturday, May 25, 2019

Javascript Basics


Javascript Basics

JavaScript presentation

Why Study JavaScript?

JavaScript is one of the 3 languages all web developers must learn:

   1. HTML to define the content of web pages
   2. CSS to specify the layout of web pages
   3. JavaScript to program the behavior of web pages

Web pages are not the only place where JavaScript is used. Many desktop and server programs use JavaScript. Node.js is the best known. Some databases, like MongoDB and CouchDB, also use JavaScript as their programming language.



Sunday, August 13, 2017

jQuery Presentation


jQuery Basics



What is Jquery?

Fast and ConsiseJavascriptLibrary created by John Resigin 2006

jQuery is a JavaScript library designed to simplify HTML DOM tree traversal and manipulation, as well as event handling, CSS animation, and Ajax. It is free, open-source software using the permissive MIT License. As of May 2019, jQuery is used by 73% of the 10 million most popular websites. Web analysis indicates that it is the most widely deployed JavaScript library by a large margin, having 3 to 4 times more usage than any other JavaScript library


Friday, August 23, 2019

Create a Digital Clock using HTML and JavaScript

Create a Digital Clock using HTML and JavaScript 




<!DOCTYPE html>
<html>
<head>

<script>
function startTime() {
  var today = new Date();
  var h = today.getHours();
  var m = today.getMinutes();
  var s = today.getSeconds();
  m = checkTime(m);
  s = checkTime(s);
  document.getElementById('txt').innerHTML =
  h + ":" + m + ":" + s;
  var t = setTimeout(startTime, 500);
}
function checkTime(i) {
  if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
  return i;
}
</script>

<style>
#txt{
color:white;
background-color:rgb(60, 60, 60);
padding:20px;
text-align: center;
margin: 60px;

}
</style>
</head>

<body onload="startTime()">

<div id="txt">  </div>

</body>
</html>



 



Monday, September 28, 2026

Median Of Two Sorted Arrays

 

🚀 LeetCode Hard #1
Median Of Two Sorted Arrays

📌 Problem

Given two sorted arrays nums1 and nums2, return median of combined sorted array. Time Complexity Required: O(log(min(n,m)))

🔥 Intuition

Interviewers are testing if you understand Binary Search on partition instead of merging.

Naive thinking:

Merge arrays
Sort
Return Median

O(n+m)

But interview demands:

O(log(min(n,m)))

✅ Core Idea


A Left Part | A Right Part

B Left Part | B Right Part

Need:

Max(Left)
<=
Min(Right)

🎯 Dry Run


nums1 = [1,3]

nums2 = [2]

Partition gives:

1 | 3

2 |

Left = [1,2]

Right = [3]

Median = 2

☕ Java Solution


public double findMedianSortedArrays(
int[] nums1,
int[] nums2) {

 if(nums1.length > nums2.length)
    return findMedianSortedArrays(
           nums2,nums1);

 int x = nums1.length;
 int y = nums2.length;

 int low=0;
 int high=x;

 while(low<=high){

   int partitionX =
       (low+high)/2;

   int partitionY =
      (x+y+1)/2 - partitionX;

   int maxLeftX =
      partitionX==0?
      Integer.MIN_VALUE:
      nums1[partitionX-1];

   int minRightX =
      partitionX==x?
      Integer.MAX_VALUE:
      nums1[partitionX];

   int maxLeftY =
      partitionY==0?
      Integer.MIN_VALUE:
      nums2[partitionY-1];

   int minRightY =
      partitionY==y?
      Integer.MAX_VALUE:
      nums2[partitionY];

   if(maxLeftX<=minRightY &&
      maxLeftY<=minRightX){

      if((x+y)%2==0){

         return (
           Math.max(
             maxLeftX,
             maxLeftY
           )
          +
           Math.min(
              minRightX,
              minRightY
           )
         )/2.0;
      }

      return Math.max(
             maxLeftX,
             maxLeftY);
   }

   else if(maxLeftX >
           minRightY){

      high=
      partitionX-1;
   }
   else{

      low=
      partitionX+1;
   }
 }

 return 0;
}

🐍 Python


def findMedianSortedArrays(A,B):

 if len(A)>len(B):
   A,B=B,A

 x=len(A)
 y=len(B)

 low=0
 high=x

 while low<=high:

  px=(low+high)//2
  py=(x+y+1)//2-px

  maxLX=float('-inf') \
       if px==0 else A[px-1]

  minRX=float('inf') \
       if px==x else A[px]

  maxLY=float('-inf') \
       if py==0 else B[py-1]

  minRY=float('inf') \
       if py==y else B[py]

  if maxLX<=minRY \
     and maxLY<=minRX:

      if (x+y)%2==0:
         return (
            max(maxLX,maxLY)
            + min(minRX,minRY)
         )/2

      return max(maxLX,maxLY)

  elif maxLX>minRY:
      high=px-1
  else:
      low=px+1

⚡ JavaScript


function median(A,B){

 if(A.length>B.length)
   return median(B,A);

 let low=0;
 let high=A.length;

 while(low<=high){

  let px=Math.floor(
    (low+high)/2);

  let py=Math.floor(
   (A.length+B.length+1)/2)-px;

  let maxLX=
   px===0?
   Number.MIN_SAFE_INTEGER:
   A[px-1];

  let minRX=
   px===A.length?
   Number.MAX_SAFE_INTEGER:
   A[px];

  let maxLY=
   py===0?
   Number.MIN_SAFE_INTEGER:
   B[py-1];

  let minRY=
   py===B.length?
   Number.MAX_SAFE_INTEGER:
   B[py];

  if(maxLX<=minRY &&
     maxLY<=minRX){

    if((A.length+B.length)%2===0){

      return (
        Math.max(maxLX,maxLY)
       +
        Math.min(minRX,minRY)
      )/2;
    }

    return Math.max(
      maxLX,maxLY);
  }

  if(maxLX>minRY)
      high=px-1;
  else
      low=px+1;
 }

 return -1;
}

🎤 Interview Follow-Ups

  • Why not merge arrays?
  • Why binary search only smaller array?
  • How partition works?
  • How handle odd length?
  • How handle duplicates?
  • Can you derive solution mathematically?
✅ Pattern: Binary Search + Partition

Saturday, November 4, 2023

Sorting on the basis of multiple fields

 function sortObjects(arr) {

arr.sort(function(a, b) { if (a.adviserid < b.adviserid) { return -1; } else if (a.adviserid > b.adviserid) { return 1; } else { if (a.cutomer_id < b.cutomer_id) { return -1; } else if (a.cutomer_id > b.cutomer_id) { return 1; } else { if (a.account_id < b.account_id) { return -1; } else if (a.account_id > b.account_id) { return 1; } else { if (a.product_type === b.product_type) { if (a.account_id > b.account_id) { return -1; } else if (a.account_id < b.account_id) { return 1; } } return 0; } } } }); // Group the array by adviserid var groupedArr = []; var currentAdviserId = null; for (var i = 0; i < arr.length; i++) { var obj = arr[i]; if (obj.adviserid !== currentAdviserId) { currentAdviserId = obj.adviserid; groupedArr.push([]); } groupedArr[groupedArr.length - 1].push(obj); } return groupedArr; }

Here's how you would use this function:

// Example array of objects var arr = [ { adviserid: 1, cutomer_id: "abc", account_id: 10, product_type: "A" }, { adviserid: 1, cutomer_id: "abc", account_id: 20, product_type: "A" }, { adviserid: 1, cutomer_id: "def", account_id: 30, product_type: "B" }, { adviserid: 2, cutomer_id: "ghi", account_id: 40, product_type: "A" } ]; // Call the function to sort the array var sortedArr = sortObjects(arr); // Print the sorted array console.log(sortedArr);

In this example, the arr array contains four objects with adviserid, cutomer_id, account_id, and product_type properties. The sortObjects function sorts the array based on the three fields you specified (in ascending order), and then groups the sorted array by adviserid. The sorted and grouped array is then printed to the console.

In the sorting logic, the function first sorts by adviserid, then by cutomer_id, and then by account_id. If two objects have the same product_type, they are sorted by account_id in descending order. If two objects have the same adviserid, they are grouped together in the output array.




Sure, here's an example JavaScript function that sorts an array of objects based on the three fields you specified:

function sortObjects(arr) { arr.sort(function(a, b) { if (a.adviserId < b.adviserId) { return -1; } else if (a.adviserId > b.adviserId) { return 1; } else { if (a.priority < b.priority) { return -1; } else if (a.priority > b.priority) { return 1; } else { if (a.accountId < b.accountId) { return 1; } else if (a.accountId > b.accountId) { return -1; } else { return 0; } } } }); return arr; } // Example array of objects var arr = [ { adviserId: 2, priority: 1, accountId: 10 }, { adviserId: 1, priority: 2, accountId: 20 }, { adviserId: 1, priority: 2, accountId: 30 }, { adviserId: 2, priority: 1, accountId: 40 } ]; // Print the input array console.log("Input: ", arr); // Call the function to sort the array var sortedArr = sortObjects(arr); // Print the sorted array console.log("Output: ", sortedArr);

In this example, the arr array contains four objects with adviserId, priority, and accountId properties. The sortObjects function sorts the array based on the three fields you specified, with priority being sorted in ascending order. If two objects have the same priority, they are sorted by accountId in descending order. The input and output arrays are then printed to the console.

The output of this function will be:

Input: [ { adviserId: 2, priority: 1, accountId: 10 }, { adviserId: 1, priority: 2, accountId: 20 }, { adviserId: 1, priority: 2, accountId: 30 }, { adviserId: 2, priority: 1, accountId: 40 } ] Output: [ { adviserId: 1, priority: 2, accountId: 30 }, { adviserId: 1, priority: 2, accountId: 20 }, { adviserId: 2, priority: 1, accountId: 40 }, { adviserId: 2, priority: 1, accountId: 10 } ]

Monday, August 17, 2026

Java 8 Complete Reference

Complete tutorial with examples and interview guidance

Java 8 Complete Feature Guide

A practical, detailed guide to the release that changed modern Java development. Learn lambdas, functional interfaces, streams, Optional, the Date and Time API, CompletableFuture, collection enhancements, common mistakes, and senior-level interview questions.

Lambda ExpressionsStream APIOptionaljava.timeCompletableFutureMap API

1What Changed in Java 8?

Java 8 brought functional-style programming to Java while retaining its object-oriented foundation. The major changes include lambda expressions, method references, functional interfaces, default methods, streams, Optional, a modern Date and Time API, and asynchronous composition through CompletableFuture.

Collection data→Stream pipeline→Result
Important mental model: A collection stores data. A stream does not normally store data; it describes operations to perform on a source.

2Lambda Expressions

A lambda expression provides an implementation for the single abstract method of a functional interface.

(parameters) -> expression
(parameters) -> {
    statements;
}

Before Java 8

Collections.sort(employees, new Comparator<Employee>() {
    @Override
    public int compare(Employee first, Employee second) {
        return first.getName().compareTo(second.getName());
    }
});

Using a lambda

employees.sort((first, second) ->
    first.getName().compareTo(second.getName()));

Variable capture

int minimumSalary = 50_000; // Effectively final

employees.stream()
    .filter(employee -> employee.getSalary() > minimumSalary)
    .forEach(System.out::println);
A local variable captured by a lambda must be final or effectively final. Avoid modifying shared state inside lambdas, especially in parallel execution.

3Functional Interfaces

@FunctionalInterface
interface SalaryRule {
    boolean test(Employee employee);
}
InterfaceInput and outputMethodUse
Predicate<T>T to booleantest()Filtering
Function<T,R>T to Rapply()Transformation
Consumer<T>T to voidaccept()Performing an action
Supplier<T>No input to Tget()Lazy object creation
UnaryOperator<T>T to Tapply()Same-type transformation
BinaryOperator<T>T and T to Tapply()Combining values
Predicate<Employee> highPaid =
    employee -> employee.getSalary() > 100_000;

Function<Employee, String> employeeName = Employee::getName;
Consumer<Employee> printEmployee = System.out::println;
Supplier<List<Employee>> listFactory = ArrayList::new;

Predicate<Employee> highPaidITEmployee = highPaid.and(
    employee -> "IT".equals(employee.getDepartment()));
Performance tip: Primitive specializations such as IntPredicate, IntConsumer and ToIntFunction can reduce boxing and unboxing.

4Method and Constructor References

Static method

numbers.stream()
    .reduce(Integer::sum);

Bound instance method

employees.forEach(
    System.out::println);

Unbound instance method

employees.stream()
    .map(Employee::getName);

Constructor reference

Supplier<List<Employee>> factory =
    ArrayList::new;
A method reference is shortened lambda syntax. Use it when it makes the intention clearer, not simply because it is shorter.

5Default and Static Interface Methods

interface Auditable {

    default String auditMessage() {
        return "Audited at " + Instant.now();
    }

    static boolean isValid(String value) {
        return value != null && !value.trim().isEmpty();
    }
}

Conflict-resolution rules

  1. A concrete class method wins over an interface default method.
  2. A method from a more specific child interface wins over its parent interface.
  3. If unrelated interfaces declare conflicting defaults, the implementing class must override the method.
interface A {
    default void print() { System.out.println("A"); }
}

interface B {
    default void print() { System.out.println("B"); }
}

class Example implements A, B {
    @Override
    public void print() {
        A.super.print();
    }
}

6Stream API Deep Dive

Source→Intermediate operations→Terminal operation
List<String> names = employees.stream()
    .filter(employee -> employee.getSalary() > 80_000)
    .sorted(Comparator.comparing(Employee::getSalary).reversed())
    .map(Employee::getName)
    .collect(Collectors.toList());

Stateless

filter, map and flatMap process elements independently.

Stateful

distinct and sorted may retain information about previously seen elements.

Terminal

collect, reduce, count, match, find and forEach trigger execution.

map() versus flatMap()

List<String> uniqueSkills = employees.stream()
    .flatMap(employee -> employee.getSkills().stream())
    .map(String::toUpperCase)
    .distinct()
    .sorted()
    .collect(Collectors.toList());

reduce()

double totalSalary = employees.stream()
    .map(Employee::getSalary)
    .reduce(0.0, Double::sum);

int total = IntStream.rangeClosed(1, 100).sum();

Short-circuit operations

boolean anyHighPaidEmployee = employees.stream()
    .anyMatch(employee -> employee.getSalary() > 200_000);

Optional<Employee> firstITEmployee = employees.stream()
    .filter(employee -> "IT".equals(employee.getDepartment()))
    .findFirst();
Lazy execution: Intermediate operations do not run until a terminal operation requests results. Short-circuiting can prevent the entire source from being processed.

7Collectors and Employee Examples

Group by department

Map<String, List<Employee>> byDepartment =
    employees.stream().collect(Collectors.groupingBy(
        Employee::getDepartment));

Count per department

Map<String, Long> countByDepartment =
    employees.stream().collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.counting()));

Maximum salary employee

Map<String, Optional<Employee>> highestPaid =
    employees.stream().collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.maxBy(Comparator.comparing(
            Employee::getSalary))));

Average salary

Map<String, Double> averageSalary =
    employees.stream().collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.averagingDouble(
            Employee::getSalary)));

Third-highest distinct salary, department-wise

employees.stream()
    .collect(Collectors.groupingBy(Employee::getDepartment))
    .forEach((department, employeeList) -> {

        Double salary = employeeList.stream()
            .map(Employee::getSalary)
            .distinct()
            .sorted(Comparator.reverseOrder())
            .skip(2)
            .findFirst()
            .orElse(null);

        System.out.println(department + " -> " + salary);
    });

Why distinct? The third-highest salary normally means the third distinct salary. Duplicate salary values should share the same rank.

toMap() with duplicate-key handling

Map<String, Employee> employeeByName = employees.stream()
    .collect(Collectors.toMap(
        Employee::getName,
        Function.identity(),
        BinaryOperator.maxBy(
            Comparator.comparing(Employee::getSalary))));
When two elements produce the same map key, toMap() requires a merge function. Without it, a duplicate-key exception is thrown.

8Parallel Streams and Spliterator

double totalSalary = employees.parallelStream()
    .mapToDouble(Employee::getSalary)
    .sum();

Consider parallel streams when

  • The dataset is large and in memory.
  • Work is CPU-intensive and independent.
  • The source can be split efficiently.
  • Reduction is associative.

Avoid them when

  • Operations perform blocking I/O.
  • The collection is small.
  • Shared mutable state is involved.
  • Ordering costs dominate.
  • Common-pool contention is risky.

Spliterator supports both traversal and partitioning. Characteristics such as ORDERED, DISTINCT, SORTED, SIZED and SUBSIZED help the stream framework understand a data source.

Interview point: Parallel does not automatically mean faster. Benchmark using realistic data and workload.

9Optional

Optional<Employee> employeeOptional = repository.findById(id);

String name = employeeOptional
    .filter(employee -> employee.getSalary() > 50_000)
    .map(Employee::getName)
    .orElse("Unknown");

orElse()

value.orElse(createDefault());
// createDefault() is called eagerly

orElseGet()

value.orElseGet(this::createDefault);
// Supplier runs only when empty

Flatten nested Optional values

Optional<String> city = employeeOptional
    .flatMap(Employee::getAddress)
    .map(Address::getCity);
Use Optional mainly as a return type. Avoid calling get() without checking, and generally avoid Optional fields, parameters and collections of Optional.

10Modern Date and Time API

TypePurpose
LocalDateDate without time or zone
LocalTimeTime without date or zone
LocalDateTimeDate and time without a zone
InstantA point on the UTC timeline
ZonedDateTimeDate and time with a region-based zone
OffsetDateTimeDate and time with a numeric UTC offset
PeriodDate-based amount
DurationTime-based amount
LocalDate joiningDate = LocalDate.of(2020, Month.JANUARY, 15);
long years = ChronoUnit.YEARS.between(
    joiningDate, LocalDate.now());

DateTimeFormatter formatter =
    DateTimeFormatter.ofPattern("dd-MM-yyyy");
String formattedDate = joiningDate.format(formatter);

Instant currentInstant = Instant.now();
ZonedDateTime indiaTime = currentInstant.atZone(
    ZoneId.of("Asia/Kolkata"));
The central java.time classes are immutable and thread-safe. LocalDateTime is not a global timestamp because it contains no time-zone or offset information.

11CompletableFuture

CompletableFuture<Employee> employeeFuture =
    CompletableFuture.supplyAsync(
        () -> loadEmployee(id), executor);

CompletableFuture<String> result = employeeFuture
    .thenApply(Employee::getName)
    .exceptionally(exception -> "Unknown");

Combine independent calls

CompletableFuture<Profile> profileFuture =
    CompletableFuture.supplyAsync(this::loadProfile, executor);

CompletableFuture<Salary> salaryFuture =
    CompletableFuture.supplyAsync(this::loadSalary, executor);

CompletableFuture<EmployeeView> viewFuture =
    profileFuture.thenCombine(
        salaryFuture, EmployeeView::new);
MethodPurpose
thenApply()Transform a completed result
thenCompose()Chain and flatten a dependent future
thenCombine()Combine two independent results
allOf() / anyOf()Coordinate multiple futures
handle()Process either a result or exception
exceptionally()Recover from a failure
In server applications, use a suitably configured executor. Blocking the shared common pool can affect unrelated operations.

12Collection, Map and Comparator Improvements

Collection operations

employees.forEach(System.out::println);
employees.removeIf(employee -> !employee.isActive());
employees.replaceAll(this::normalize);

Map operations

employeeMap.forEach((id, employee) ->
    System.out.println(employee));

Employee employee = employeeMap.getOrDefault(id, defaultEmployee);
employeeMap.putIfAbsent(id, newEmployee);

departmentEmployees
    .computeIfAbsent(department, key -> new ArrayList<>())
    .add(employee);

wordCount.merge(word, 1, Integer::sum);

Put Map values into another list

List<Employee> employeeList =
    new ArrayList<>(employeeMap.values());

Comparator composition

Comparator<Employee> employeeComparator =
    Comparator.comparing(Employee::getDepartment)
        .thenComparing(
            Employee::getSalary,
            Comparator.reverseOrder())
        .thenComparing(
            Employee::getName,
            Comparator.nullsLast(
                String.CASE_INSENSITIVE_ORDER));

HashSet.add() return value

Set<Integer> seen = new HashSet<>();

numbers.stream()
    .filter(number -> !seen.add(number))
    .forEach(System.out::println);

HashSet.add() returns true when the element is inserted and false when an equal element already exists. Therefore, !seen.add(number) selects duplicates.

13Other Important Java 8 Features

Base64

String encoded = Base64.getEncoder()
    .encodeToString("Java 8".getBytes(
        StandardCharsets.UTF_8));

String decoded = new String(
    Base64.getDecoder().decode(encoded),
    StandardCharsets.UTF_8);

StringJoiner

StringJoiner joiner =
    new StringJoiner(", ", "[", "]");

joiner.add("Java").add("Spring");

Repeatable annotations

@Repeatable(Roles.class)
@interface Role { String value(); }

@interface Roles { Role[] value(); }

@Role("ADMIN")
@Role("AUDITOR")
class UserService {}

Files.lines()

try (Stream<String> lines =
         Files.lines(logFilePath)) {

    long errors = lines
        .filter(line -> line.contains("ERROR"))
        .count();
}
  • Metaspace: Native-memory Metaspace replaced PermGen for class metadata.
  • Target-type inference: Generic type inference was improved in more invocation contexts.
  • Parameter names: Reflection can read parameter names when compiled using -parameters.
  • Concurrency: Java 8 added classes such as StampedLock, LongAdder and LongAccumulator.
  • Nashorn: Java 8 included a JavaScript engine, but it should not be chosen for modern application designs.

14Common Java 8 Mistakes

Reusing a stream

A stream is consumed after a terminal operation and cannot be reused.

Shared mutation

Avoid updating external mutable collections from a stream pipeline.

Optional.get()

Prefer map, flatMap, orElseGet or orElseThrow.

Assuming null safety

Streams do not make null elements or mappers automatically safe.

Incorrect time type

Do not use LocalDateTime when you need a global timestamp.

Blind parallelization

Measure before using parallel streams and avoid blocking calls.

15Java 8 Interview Questions

Why can a functional interface contain default and static methods?

The single-abstract-method rule counts abstract instance methods. Default and static methods already have implementations.

What is the difference between a collection and a stream?

A collection stores elements and supports repeated traversal. A stream is a consumable, normally lazy computation pipeline using internal iteration.

What is the difference between map() and flatMap()?

map() transforms each input into one result. flatMap() transforms inputs into streams and flattens those streams into one pipeline.

Why must reduce operations be associative?

Parallel execution can combine partitions in different groupings. Associativity ensures those groupings produce the same result.

findFirst() versus findAny()?

findFirst() respects encounter order. findAny() allows more freedom and may be useful when any matching result is acceptable.

orElse() versus orElseGet()?

orElse() evaluates its argument eagerly. orElseGet() invokes its supplier only when the Optional is empty.

thenApply() versus thenCompose()?

thenApply() maps a value to another value. thenCompose() chains a function that returns a future and flattens the nested future.

Why can parallelStream() be risky in a web application?

It commonly uses the shared ForkJoin common pool. Blocking work, request concurrency, small tasks and ordering requirements can create unpredictable performance.

What is the difference between intermediate and terminal stream operations?

Intermediate operations return another stream and are normally lazy. Terminal operations produce a result or side effect and trigger execution.

What happens when toMap() receives duplicate keys?

It throws an exception unless a merge function is supplied to decide how duplicate values should be combined or selected.

Java 8 Complete Guide
Save this post for revision and practice each example with your own Employee data.

Create a Digital Clock using HTML and JavaScript

Create a Digital Clock using HTML and JavaScript  <! DOCTYPE html> < html > < head > ...

Followers

Search This Blog

Popular Posts