Qs: JavaScript [Live Coding]


Must Knows


What's Live Coding in JavaScript ?

It's a technical interviewing style. Your interviewer(s) watches while you code. In JavaScript.

Small projects for you to try to solve. Typically in 30 to 60min.

It then drifts into another type of interview:

  • Code Review (reasonable chance)

  • Code Quality (reasonable chance)

  • System Design (small chance)

  • LeetCode (tiny chance)


What's LeetCode ?

Think of it as going to gym: given two athletes of let's say, a football team, if both have equally talented, then the one who's trained to the gym will outcompete the other.

And as going to the gym, it may be really tough at first, but it'll get easier, and even become like a treat.


What Steps Should You Follow When Live Coding?

  1. Write pseudo code for "brute force" solution - if needed, create a diagram on draw.io

  2. Talk over your pseudo code by using mental models and analogies

  3. Write code

  4. Follow up by suggesting improvements - c.f. ideas below

Your Attitude

  • Take your time, else with time left they may ask super hard follow-up questions

  • Keep it VERY simple, else you might not have improvements to suggest

  • Say out loud "Live Coding makes me very anxious", else your interviewer might not realize it

  • Stay very serious at all time unless your interviewer is very casual

  • Feel free to suggest CodeSandBox.com, else you might be stuck using a crappy online IDE

Mental Models and Analogies

Data Structures Involved

  • Duplicate Data Structures, i.e. One is the original one, the other is for marking processed items

  • Count/Sum Data Structure, i.e. usually just a number

Utility Functions Involved

  • Transformator/Migrator, i.e. transform a 3D array into a flat array

Potential Improvements

Readability, Testability, Maintainability

  • 100% of the code must be in functions

  • self-explanatory namings

  • easy-to-digest logic

  • SRP: each function has a tiny responsibility - mention SOLID Principles

  • Pure Functions: for no side effects

Defensive Programming

  • handle errors

  • handle loading state

  • handle unexpected empty/null/undefined/0 values, provide default

  • handle unexpected type, i.e. string vs number

Upgrade Syntax

  • var -> const or let

  • let -> const (if possible)

  • buggy const (i.e. reassigned)

  • spread/rest operators

  • method chaining -> async/await

  • class component -> function component

  • regular function -> arrow functions

Optimize Loops and Data Structures

  • array -> set, or map

  • loop -> proper algorithms

  • loop -> Array Instance Methods such as reduce(), or map()

Optimize Performance

  • Caching

  • Lazy Loading


What Defensive Programming?

Software Development Practice.

  • Focus: anticipate and safely handle unexpected inputs, states, or errors.

  • Goal: make code more robust, secure, and maintainable.

Category
Details

Error handling

Use try/catch, custom error messages

Defaults

Handle undefined, null, or missing params: give fallback values

Validate inputs

Validate types, ranges, formats

Logic

Use guard clauses & early exits

Types

Use TypeScript or runtime checks

APIs

Check response validity

Security

Sanitize and validate external inputs

Mutability

Avoid modifying shared state

Comment

Add JSDoc for functions + Add relevant comments


Gotchas & Common Pitfalls


Most Common Challenges

  1. Data structure manipulation using Array Instance Methods

  2. String manipulation using Array Instance Methods

  3. Combine 1 & 2: data structure manipulation combined with String manipulation using Array Instance Methods

  4. Add method to Array Object

  5. Fetch data from API by doing 2 calls

  6. Combine promises and timeout

  7. Given "spaghetti" code snippet, review by adding comments -or- refactor the code


Fetch Data From API: Gotchas & Common Pitfalls

  1. fetch() doesn’t reject on HTTP errors - always check res.ok and handle status codes explicitly.

i.e. if (!res.ok) { throw new Error("HTTP error! status: " + res.status); }

  1. You must explicitly parse the response body - always call .json(), or .text(), or .blob(), etc

  2. No built-in timeout - always use AbortController or a timeout wrapper

  3. Security - always use https


Challenges & Solutions


Mock JSON Data And APIs

You can use free services such as :

  • https://jsonplaceholder.typicode.com/

  • https://rickandmortyapi.com/


String Manipulation: Check If Char Is Number

How do check if a character is a number?

!isNaN(char)


String Manipulation: Default Value Assignment

How do give a default value assignment "hello" when: a string is falsy (empty) ?

const greeting = myString || "hello";

How do give a default value assignment when: an array item is falsy (empty string, or 0, or null, or undefined)

const currItem = myArray[i] || 1;


String Manipulation: Iterate Over Chars In String

How do you iterate over characters of a string?


String Manipulation: Add Numbers In Text

Create the function addNbInTxt so that it matches the expected outputs

SOLUTION


Reduce: Sum Of Numbers In Array

Calculate the sum of all numbers in an array with reduce().

SOLUTION


Reduce: Count Occurrences

Count how many times each element appears in an array with reduce().

SOLUTION


Reduce: Flatten a Nested Array

Turn a nested array into a single-level array with reduce().

SOLUTION


Nested reduce() To Calculate Total

Use nested reduce() to calculate the total sum of all numbers across all sub-arrays.

SOLUTION


Nested reduce() To Flatten and Count Letters

Use nested reduce() to:

  • Flatten all the words into an array of individual characters.

  • Count how many times each letter appears (return an object like { h: 1, i: 1, t: 1, e: 2, ... }).

SOLUTION


Nested reduce() To Sum All Scores

You have a list of players, each with scores across different games.

Use nested reduce() to compute the total score of all players combined.

SOLUTION


Add Method last() To Array Object

Add method last() to Array so that it matches the expected outputs.

SOLUTION


Add Method multiplyBySelf() To Array Object

Add method multiplyBySelf() to Array so that it matches the expected outputs.

SOLUTION


Promise Method Chaining To Async/Await Code

Turn the above getData() function to use async/await syntax. Do not modify fakeFetchData().

SOLUTION


Function Adding-Up Elements In Array And Returns With Delay

Write a function in Javascript or Typescript that simulates asynchronous behavior using Promises. The function should take an array of numbers as input and return a Promise that resolves with the sum of all the numbers after a 1-second delay. Example:

  • Input: [1, 2, 3, 4, 5]

  • Output: Promise resolved with 15 after a 1-second delay

SOLUTION


Promises and Timeout: Combined

SOLUTION


Promises: then/catch: Part 1

Guess the output.


Promises: then/catch: part 2

Guess the output.


Add Method To Array Object: Pollyfill Reduce

Implement your own version of the Array.reduce method. Let's call it Array.myReduce.

The Array.reduce method is a built-in JavaScript method that takes a callback function and an initial value as arguments, and returns a single reduced value.

A reduced value is created by applying the following operation:

  • val = fn(init, arr[0])

  • val = fn(val, arr[1])

  • val = fn(val, arr[2])

  • ... until every element in the array has been processed.

The final value of val is returned. If the length of the array is 0, it should return init.

SOLUTION


Remove HTML Tags From String

SOLUTION


Call Once Function

Given a function fn, return a new function that is identical to the original function except that it ensures that fn can be called at most once.

The first time the returned function is called, it should return the same result as the original fn.

Every subsequent time it is called, it should return undefined.

SOLUTION


Wrap A Function In A Timeout - Basic Version

SOLUTION


Wrap A Function In A Timeout - Advanced Version

SOLUTION


Random Chuck Norris Images

Being given these 2 APIs

  • https://api.chucknorris.io/ - The Internet Chuck Norris Database

  • https://developers.giphy.com/docs/ - Giphy API

Select one random Chuck Norris joke and look for a matching GIF by using the first 3 words from the joke. The result should be displayed with the image on the left side and the text on the right side, positioned in the vertically in the middle.

Whenever the image is clicked, a new gif will be loaded.

Caveat: the Giphy API will return the same set of images for a given string, so in order to produce an observable change, the application needs to request more images on the first load and cache them internally.

const GIPHY_API_KEY = "2cZkiFTqyiS79UdSapL6LHWlublpl7iy"; const DEFAULT_GIF = "https://media.giphy.com/media/l3q2K5jinAlChoCLS/giphy.gif";

SOLUTION


Bind Polyfill

Add a simplified bindPolyfill method to all functions.

bindPolyfill takes an object obj and returns a new function.

When this new function is invoked, it should call the original function with its this value set to obj.

When the bindPolyfill method is called with obj argument, it should return a function that has obj as its "this" context.

Requirements:

  • the bindPolyfill method should always receive a non-null object

  • you should not use the built-in Function.bind or Function.apply methods

  • the bindPolyfill method should return a new function

Examples

SOLUTION

The above version has one major issue though:

  • collisions are guaranteed if you bind more than one function to the same object.

  • Every time you call .bindPolyfill, it assigns the function to the same property ("binding") on the target object.

  • That means the previous binding is overwritten.


Curry Function

Requirements:

  • Given a function fn, return a curried version of it

  • The curried function should accept fewer than or equal to the number of parameters as the original function

  • If enough arguments are provided, it should return the final result

  • If not enough arguments are provided, it should return another function waiting for the remaining arguments

Example behavior: If you have an original function sum(a, b, c) that takes 3 arguments, after currying it to csum, you can call it in multiple ways:

  1. csum(1)(2)(3) - one argument at a time

  2. csum(1)(2, 3) - one argument, then two arguments

  3. csum(1, 2)(3) - two arguments, then one argument

  4. csum(1, 2, 3) - all three arguments at once

Do you understand the problem? Really?

The above hints to the problem to be solved, turn any of the following:

  1. csum(1)(2)(3) - one argument at a time

  2. csum(1)(2, 3) - one argument, then two arguments

  3. csum(1, 2)(3) - two arguments, then one argument Into the last:

  4. csum(1, 2, 3) - all three arguments at once

The key insight is that we need to accumulate arguments across multiple function calls until we have enough to execute the original function.

Think of it like filling a bucket - each time the curried function is called, we add more water (arguments) to the bucket. Once the bucket is full (we have all required arguments), we can pour it out (execute the original function).

To achieve this behavior, we need:

  • A way to remember previously passed arguments - This naturally suggests using closures, where inner functions can access variables from outer scopes

  • A way to check if we have enough arguments - JavaScript functions have a length property that tells us how many parameters they expect

  • A recursive structure - If we don't have enough arguments yet, we need to return another function that continues the same pattern

SOLUTION 1: ITERATIVE

SOLUTION 2: RECURSIVE

EXPLANATION

  • if (args.length === fn.length) Condition to break out of recursion

  • return (...nextArgs) => { return helper(...args,...nextArgs) } Creates and returns a new function that expects additional arguments

  • (...nextArgs) Accepts additional arguments

  • nextArgs is not coming from anywhere "magical." It’s just the rest parameter of the arrow function you return inside helper.

  • (...args, ...nextArgs) Combines them with the previously collected ones

  • helper is a recursive call curried with the combined arguments

EXAMPLES

How this curry implementation handles arguments one at a time, or in groups.

  1. Example 1: one arg at the time

  1. Example 2: multiple args at once

  1. Example 3: multiple args at once in other brackets

Links

  • Leetcode Curry: Explained https://algo.monster/liteproblems/2632

  • Leetcode Curry: Explanation on Iterative and Recursive Solutions https://www.youtube.com/watch?v=pi4kqMWQXxA


Throttle Function

  1. Implement a simple delay


Anagram Challenge

You are given an array of strings, text.

Two strings are considered anagrams if they contain exactly the same characters, just in i different order.

For example, "aaagmnrs" is an anagram of "anagrams"".

Your task is to process the array by removing any string that is an anagram of a string that appears earlier in the array. After removal, return the remaining strings in sorted order.

Example

input: ["code", "doce", "ecod", "framer", "frame""]

Processing steps:

  • "code" and "doce" are anagrams. Remove "doce" keep "code".

  • "code" and "ecod" are anagrams. Remove "ecod" and keep "code".

  • "code" and "framer" are not anagrams. Keep both strings.

  • "framer" and "frame" are not anagrams due to the extra "r" in "framer". Keep both strings.

Return: ["code", "frame", "framer"]

Function Description:

Complete the function funWithAnagrams in the editor withthe following parameters: string text[n]: an array of strings

Returns: string[]: the remaining strings in ascending alphabetical order

Constraints

  • 0 <= n <= 1000

  • 1 <= length of text[i] <= 1000

  • Each string text[i]: made up of lowercase English letters, ascii[a-z].

Example 1:

  • input: ["code","aaagmnrs", "anagrams", "doce"]

  • expected output: ["aaagmnrs", "code"]

Example 12:

  • input: ["poke", "pkoe", "okpe", "ekop"]

  • expected output:["poke"]

SOLUTION 1

SOLUTION 2

Possible Optimisation: Use Set to store result, this will give:

  • Fast lookups

  • No duplicates automatically


Dial Speed Calculator

Calculate the minimum time needed to type a string of digits on a numeric keypad where the key positions are mixed up.

Rules:

  • it takes 0 seconds to move to the first key that you press.

  • it takes 0 seconds to press the key where your finger is currently located.

  • Moving to an adjacent key (including diagonals) takes 1 second.

  • Moving to a non-adjacent key requires a series of moves to adjacent keys.

Your task is to find the most efficient path to type the given string and return the minimum time required.

Example

Distances from 5: 9 2 3 8 5 7 6 1 4

9(1) 2(1) 3(1) 8(1) 5(0) 7(1) 6(1) 1(1) 4(1)

Distances from 9: 9 2 3 8 5 7 6 1 4

9(0) 2(1) 3(2) 8(1) 5(1) 7(2) 6(2) 1(2) 4(2)

This diagram depicts the minimum amount of time it takes to move from the current location to all other locations on the keypad.

Function Description

Complete the function entryTime in the editor with the following parameter(s):

  • string s: the string to type

  • string keypad: a string of 9 digits where each group of 3 digits represents a row on the keypad, in order Returns:

  • int : integer denoting the minimum amount of time it takes to type the string s

Constraints

  • 1 <= length of s <= 10^5

  • length of keypad = 9

  • keypad[i] is in the range 11-91

Sample Input 0:

  • string s = "423692"

  • string keypad = "923857614"

Sample Output 0: 8

Explanation 0

The keypad looks like this:

9 2 3 8 5 7 6 1 4

Calculate the time it takes to types = "423692" as follows:

  • 4: Start here, so it takes 0 seconds.

  • 2: It takes 2 seconds to move from 4 -> 2

  • 3: It takes second to move from 2 -> 3

  • 6: it takes 2 seconds to move from 3 -> 6

  • 9: it takes 2 seconds to move from 6 -> 9

  • 2: It takes 1 second to move from 9 -> 2

The total time is 2 + 1 + 2 + 2 + 1 = 8.

Sample Case 1

Sample Input 1

  • string S = "5111"

  • string keypad "752961348"

Sample Output 1 1

Explanation 1

The keypad looks like this:

7 5 2 9 6 1 3 4 8

Calculate the time it takes to type 5 = "5111" as follows:

  • 5: Start here, so it takes O seconds, and totalTime = 0.

  • 1: it takes 1 second to move from 5 -> 1

  • 1: it takes 0 seconds to move from 1 -> 1

  • 1: it takes O seconds to move from 1 -> 1

The total time is 0 + 1 + 0 + 0 = 1.

Sample Case 2

Sample Input 2

  • string s = "91566165"

  • string keypad = "639485712"

Sample Output 2 11

Explanation 2

The keypad looks like this:

6 3 9 4 8 5 7 1 2

Calculate the time it takes to types = "91566165° as follows:

  • 9: Start here, so it takes 0 seconds.

  • 1: It takes 2 seconds to move from 9->1

  • 5: takes 1 second to move from 1 -> 5

  • 6: It takes 2 seconds to move from 5 -> 6

  • 6: It takes 0 seconds to move from 6 -> 6

  • 1: it takes 2 seconds te move from 6 -> 1

  • 6: it takes 2 seconds to move from 1 -> 6

  • 5: It takes 2 seconds to move from 6 -> 5.

The total time is 0 + 2 + 1 + 2 + 0 + 2 + 2 + 2 = 11.

SOLUTION


Bucket Fill Challenge

Digital graphics tools often make available a "bucket fill" tool that will only paint adjacent cells.

In one fill, a modified bucket tool recolors adjacent cells (connected horizontally or vertically but not diagonally) that have the same color.

Given a picture represented as a 2-dimensional array of letters representing colors.

Find the minimum number of fills to completely repaint the picture.

Example

picture = ["aabba", "aabba", "aaacb"]

Each string represents a row of the picture and each letter represents a cell's color.

The diagram below shows the 5 fills needed to repaint the picture.

It takes two fills each for a and b, and one for c. The array picture is shown below.

[c.f. illustration in attached screenshot]

Function Description

Complete the function strokes Required in the editor below.

strokesRequired has the follawing parameter(s):

  • string picture[h]: an array of strings where each string represents one row of the picture to be painted Output:

  • int: the minimum number of fills required to repaint the picture

Constraints

  • h and w refer to height and width of the graph.

  • 1 <= h <= 10^5

  • 1 <= w <= 10^5

  • 1 <= h*w <= 10^5

  • length(picture(i)) = w (where 0 <= 1 <= h)

  • picture[i][j] is in the set ['a', 'b', 'c'] (where 0 <= i < h and 0 ≤ j < w)

Input Format For Custom Testing

The first line contains an integer. h that denotes the height of the picture and the number of elements in picture.

Each line / of the h subsequent lines (where 0 < i < h) contains a string that describes picture [i].

Sample Case 0

Sample Input For Custom Testing

picture[] size h = 3 picture = ["aaaba" , "ababa" , "aaaca"]

Sample Output 5

Explanation

[c.f. illustration in attached screenshot]

Letter a takes 2 fills, b takes 2 fills and c takes 1 fill for a total of 5.

Sample Case 1

Sample Input For Custom Testing

picture[]] size h = 4

picture = ["bbba", "abba", "acaa" "aaac"]

Sample Output

4

Explanation

[c.f. illustration in attached screenshot]

Letters a and b each take / fill and letter c takes 2 fills.

SOLUTION

  1. Problem Restatement

We are given a 2D grid (list of strings) where each cell is a color represented by a lowercase letter ('a', 'b', 'c').

We need to find the minimum number of fills (connected color regions) required to repaint the picture. Cells are connected horizontally or vertically (not diagonally).

Each “fill” corresponds to one connected component of the same color.

  1. Approach

This is a connected components problem in a grid. We can use DFS or BFS to count how many connected regions exist.

Steps:

Iterate through each cell (i, j) in the grid.

If the cell hasn’t been visited:

Start a DFS/BFS to mark all connected cells of the same color as visited.

Increment the counter (fills += 1).

Continue until all cells are processed.

  1. Code


E-Shop Spaghetti Code Refactor

The given function retrieves the items in a cart and its shipping costs to calculate the total to pay.

The current code is hard to understand and maintain due to spaghetti code.

Now the requirements have changed and we need to return the total instead of printing it to console.

Refactor the function so it applies best practices.

SOLUTION


Code Review This Snippet

Review this code. Leave comments where appropriate.


TODO

Fundamentals:

3 mini exercises (without showing solution) for:

  • var vs let vs const

3 mini exercises (without showing solution) for each array instance method:

  • slice

  • filter

  • map

  • flat

  • reduce

  • sort

  • flatMap

  • closure

3 mini exercises (without showing solution) using prototype methods

  • class

  • class inheritance

  • class instantiation

  • object inheritance

  • Constructor Function

  • Class

  • Class vs Constructor Function

  • Polymorphism

3 mini exercises (without showing solution) using prototype methods

  • add method to a Array Object

3 mini exercises (without showing solution) using promises

  • build promises

  • consume promises

  • consume promises: migrate from method chaining to async/await

  • add timeout to returned promise

JS Live Coding :

https://www.codewars.com/kata/search/javascript?q=&beta=false&order_by=popularity%20desc

https://www.hackerrank.com/domains/algorithms

https://leetcode.com/problemset/javascript/

TS Live Coding :

https://www.codewars.com/kata/search/typescript?q=&beta=false&order_by=popularity%20desc

Last updated