Interview & Machine Coding Arena
Real-world coding questions, polyfills, SDK architectures, and UI component tasks calibrated for SDE-1, SDE-2, and Senior Software Engineer technical rounds.
Ceaser Cipher
Caesar Cipher: An earlier encryption technique which used to substitute the current alphabets with alphabet after a number of count. Implement an algorithm to solve the ceaser cipher. Input: text = ABCD , Key = 13 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 13 shift to A is N 13 shift to B is O 13 shift to C is P 13 shift to D is Q Output: NOPQ Input: console.log(ceaserCipher('ATTACKATONCE', 13)); console.log(ceaserCipher('prashantyadav', 13)); Output: "NGGNPXNGBAPR" "cenfunaglnqni"
Check performance of async and sync functions
This question was asked in Atlassian’s principal engineer interview (P60) and Razorpay's Interview. Create an async function measurePeformance() that will take the function (async or sync) as input whose performance has to be evaluated. Example sync function Input: // normal function const syncFunction = () => { let sum = 0; for (let i = 0; i < 1000000; i++) { sum += i; } return sum; }; // measure performance of the normal function measurePerformance(syncFunction, { name: 'Sync Calculation', iterations: 5, warmup: true }); Output: "Performance Results for Sync Calculation:" "----------------------------------------" "Type: Sync" "Iterations: 5" "Average: 10.00ms" "Min: 9.00ms" "Max: 11.00ms" "----------------------------------------" Example async Function Input: // async function const asyncFunction = async () => { await new Promise(resolve => setTimeout(resolve, 100)); return 'done'; }; // measure performance of the async function measurePerformance(asyncFunction, { name: 'Async Calculation', iterations: 5, warmup: true }); Output: "Performance Results for Async Calculation:" "----------------------------------------" "Type: Async" "Iterations: 5" "Average: 105.60ms" "Min: 104.00ms" "Max: 107.00ms" "----------------------------------------" The measurePeformance() will take following props as input: other props like: - name: The name of the function or the default alias for the anonymous functions. - iterations: Number of time the function should be invoked, helps to get the average computation time with high and low time. - warmup: This flag will be used to run the function once to make sure it is not throwing any error before starting the performance test. - logResults: This flag will be used to determine if we have to log the results or not. Compare performance of two or more functions Extend the measurePerformance function and create a comparePerformance function that will take two or more functions and compare there performance. Testcase Input: // async function const asyncFunction = async () => { await new Promise(resolve => setTimeout(resolve, 100)); return 'done'; }; // normal function const syncFunction = () => { let sum = 0; for (let i = 0; i < 1000000; i++) { sum += i; } return sum; }; // compare two functions comparePerformance([ { fn: syncFunction, name: 'Sync Calculation' }, { fn: asyncFunction, name: 'Async Operation' } ], { iterations: 5, warmup: true }); Output: "Performance Results for Sync Calculation:" "----------------------------------------" "Type: Sync" "Iterations: 5" "Average: 2.40ms" "Min: 2.00ms" "Max: 3.00ms" "----------------------------------------" "Performance Results for Async Operation:" "----------------------------------------" "Type: Async" "Iterations: 5" "Average: 104.40ms" "Min: 100.00ms" "Max: 113.00ms" "----------------------------------------" "Performance Comparison:" "----------------------------------------" "1. Sync Calculation:" " Average: 2.40ms" " Min: 2.00ms" " Max: 3.00ms" "2. Async Operation:" " Average: 104.40ms" " Min: 100.00ms" " Max: 113.00ms" "----------------------------------------" Note: You have to implement the functions measurePeformance() and comparePerformance() that solves the problem. There are no testcases to this. Test it yourself using the sample testcases. Related Link - https://leetcode.com/discuss/post/6769058/atlassian-principal-frontend-engineer-p6-b0h2/
Create a function to truncate string
This question was asked in Birdeye's frontend interview. It was asked to create a function to truncate the string and end it with the ellipses characters ... at the end. Create a function truncate(str, maxlength) that checks the length of the given str and if it exceeds maxlength, replaces the end of str with the ellipsis character ... , to make its length equal to maxlength. Example Input: truncate("What I'd like to tell on this topic is:", 20) Output: "What I'd like to tel..." Note: You have to implement the solution that solves the problem. There are no test cases to this. Test it yourself using the sample testcases.
Create a sampling function
This question was asked in ZETA's SDE1 Frontend interview. Create a function in JavaScript that accepts a function as input and a count and executes that input function once for a given count of calls. Known as sampling function. function message(){ console.log("hello"); } const sample = sampler(message, 4); sample(); sample(); sample(); sample(); // this will be executed sample(); sample(); sample(); sample(); // this will be executed Note: You have to implement a function sampler that evaluates the above expression. There are no test cases to this. Test it yourself with different values. Related Links - https://www.linkedin.com/posts/prakharchauhan281098_opentowork-frontenddevelopment-javascript-share-7281324741347430400-6sx1/?utm_source=share&utm_medium=member_desktop
Create a Sampling Functon
Problem Statement: Create a function in JavaScript that accepts a function as input and a count and executes that input function once for a given count of calls. Known as sampling function. function message(){ console.log("hello"); } const sample = sampler(message, 4); sample(); sample(); sample(); sample(); // this will be executed sample(); sample(); sample(); sample(); // this will be executed
Create a School using OOPs Principle
It is unusual to ask OOPs question in the frontend interviews but Intuit is exception. It is known to ask atleast one OOPs question to the software engineers irrespective frontend or backend. This is the question that was asked for SDE2 frontend role in Intuit. Problem – Create Student and Teacher classes with some shared and some unique properties. Required functionalities: getTotalStrength() getStudentInfo() getTeacherSubjects() And a few more operations. To simplify the problem and provide a better understanding, please create a School class with Students and Teachers that should have additional properties as you can see in the example. Example Input: const school = new School("Learnersbucket High School"); // Create students const student1 = new Student("Harry Potter", 16, "S001", "harry@learnersbucket.com", "10th", "R001"); const student2 = new Student("Hermione Granger", 17, "S002", "hermione@learnersbucket.com", "11th", "R002"); const student3 = new Student("Ron Weasely", 15, "S003", "ron@learnersbucket.com", "9th", "R003"); // Create teachers const teacher1 = new Teacher("Mr. Rubeus Hagrid", 35, "T001", "rubeus@learnersbucket.com", "Mathematics", 10, 50000); const teacher2 = new Teacher("Mr. Albus Dumbledore", 28, "T002", "albus@learnersbucket.com", "English", 5, 45000); // Add students student1.enrollInSubject("Mathematics"); student1.enrollInSubject("Physics"); student1.addMark("Mathematics", 85); student1.addMark("Mathematics", 92); student1.addMark("Physics", 78); student1.updateAttendance(95); student2.enrollInSubject("English"); student2.enrollInSubject("History"); student2.addMark("English", 88); student2.addMark("History", 82); student2.updateAttendance(87); // Add teachers teacher1.assignSubject("Mathematics"); teacher1.assignSubject("Physics"); teacher1.assignStudent("S001"); teacher1.assignStudent("S003"); teacher2.assignSubject("English"); teacher2.assignSubject("Literature"); teacher2.assignStudent("S002"); // Enroll into school school.addStudent(student1); school.addStudent(student2); school.addStudent(student3); school.addTeacher(teacher1); school.addTeacher(teacher2); // Test the functionalities console.log("--- TOTAL STRENGTH ---"); console.log(school.getTotalStrength()); console.log("--- STUDENT INFO ---"); console.log(student1.getStudentInfo()); console.log("--- TEACHER SUBJECTS ---"); console.log(teacher1.getTeacherSubjects()); console.log("--- ADDITIONAL OPERATIONS ---"); console.log("School Stats:", school.getSchoolStats()); console.log("Teacher Info:", teacher2.getTeacherInfo()); console.log("Teacher Workload:", teacher1.getWorkload()); console.log("Students in 10th grade:", school.getStudentsByGrade("10th").map(s => s.name)); Output: "--- TOTAL STRENGTH ---" // [object Object] { "totalStudents": 3, "totalTeachers": 2, "totalStrength": 5, "inactiveMembers": 0 } "--- STUDENT INFO ---" // [object Object] { "name": "Harry Potter", "age": 16, "id": "S001", "email": "harry@learnersbucket.com", "isActive": true, "grade": "10th", "rollNumber": "R001", "subjects": [ "Mathematics", "Physics" ], "averageMarks": 85, "attendance": 95, "performance": "Good" } "--- TEACHER SUBJECTS ---" // [object Object] { "teacherId": "T001", "teacherName": "Mr. Rubeus Hagrid", "department": "Mathematics", "subjects": [ "Mathematics", "Physics" ], "totalSubjects": 2, "experience": 10 } "--- ADDITIONAL OPERATIONS ---" "School Stats:" // [object Object] { "schoolName": "Learnersbucket High School", "totalStudents": 3, "totalTeachers": 2, "totalStrength": 5, "inactiveMembers": 0, "averageStudentAge": 16, "averageTeacherExperience": 7.5, "studentTeacherRatio": 1.5 } "Teacher Info:" // [object Object] { "name": "Mr. Albus Dumbledore", "age": 28, "id": "T002", "email": "albus@learnersbucket.com", "isActive": true, "department": "English", "experience": 5, "salary": 45000, "subjects": [ "English", "Literature" ], "studentsCount": 1, "workload": { "subjects": 2, "students": 1, "totalWorkload": 2 } } "Teacher Workload:" // [object Object] { "subjects": 2, "students": 2, "totalWorkload": 4 } "Students in 10th grade:" // [object Array] (1) ["Harry Potter"] Related Links - https://leetcode.com/discuss/post/6770567/intuit-senior-frontend-engineer-by-anony-x1a5/
Create a toggle function
Problem Statement - Create a toggle function in JavaScript that accepts a list of arguments and toggles each of them when invoked in a cycle. Example: let hello = toggle("hello"); hello() // "hello"; hello() // "hello"; let onOff = toggle("on", "off"); onOff() // "on" onOff() // "off" onOff() // "on"
Create a Toggle Function
Create a toggle function in JavaScript that accepts a list of arguments and toggles each of them when invoked in a cycle. Example let hello = toggle("hello"); hello() // "hello"; hello() // "hello"; let onOff = toggle("on", "off"); onOff() // "on" onOff() // "off" onOff() // "on" Note: You have to implement a function that evaluates the above expression. There are no test cases to this. Test it yourself with different values.
Create an analytics SDK
This is a Swiggy frontend interview question. Implement an analytics SDK that exposes log events, it takes in events and queues them, and then starts sending the events. The SDK should adhere the following properties. Send each event after a delay of 1 second and this logging fails every n % 5 times. Send the next event only after the previous one resolves. When the failure occurs attempt a retry. Input: const sdk = new SDK(); sdk.logEvent("event 1"); sdk.logEvent("event 2"); sdk.logEvent("event 3"); sdk.logEvent("event 4"); sdk.logEvent("event 5"); sdk.logEvent("event 6"); sdk.logEvent("event 7"); sdk.logEvent("event 8"); sdk.logEvent("event 9"); sdk.logEvent("event 10"); sdk.send(); Output: "Analytics sent event 1" "Analytics sent event 2" "Analytics sent event 3" "Analytics sent event 4" "-----------------------" "Failed to send event 5" "Retrying sending event 5" "-----------------------" "Analytics sent event 5" "Analytics sent event 6" "Analytics sent event 7" "Analytics sent event 8" "-----------------------" "Failed to send event 9" "Retrying sending event 9" "-----------------------" "Analytics sent event 9" "Analytics sent event 10" Related Link - https://leetcode.com/discuss/post/1857338/swiggy-phone-design-analytics-sdk-sde2-b-ustr/
Create Analytics SDK
This is a Swiggy frontend interview question. Implement an analytics SDK that exposes log events, it takes in events and queues them, and then starts sending the events. The SDK should adhere the following properties. • Send each event after a delay of 1 second and this logging fails every n % 5 times. • Send the next event only after the previous one resolves. • When the failure occurs attempt a retry. Input: const sdk = new SDK(); sdk.logEvent("event 1"); sdk.logEvent("event 2"); sdk.logEvent("event 3"); sdk.logEvent("event 4"); sdk.logEvent("event 5"); sdk.logEvent("event 6"); sdk.logEvent("event 7"); sdk.logEvent("event 8"); sdk.logEvent("event 9"); sdk.logEvent("event 10"); sdk.send(); Output: "Analytics sent event 1" "Analytics sent event 2" "Analytics sent event 3" "Analytics sent event 4" "-----------------------" "Failed to send event 5" "Retrying sending event 5" "-----------------------" "Analytics sent event 5" "Analytics sent event 6" "Analytics sent event 7" "Analytics sent event 8" "-----------------------" "Failed to send event 9" "Retrying sending event 9" "-----------------------" "Analytics sent event 9" "Analytics sent event 10"
Create composeAsync function with chaining support
This question was asked in Adobe’s SDE2 frontend interview. The problem statement reads as – Create composeAsync function that will compose async function with chaining support. These interviews questions evaluate when your understanding of closure and the async operations. Example Input: function a(x, y) { return new Promise(resolve => setTimeout(() => resolve(x * y), 100)); } function b(z) { return new Promise((resolve, reject) => setTimeout(() => resolve(z + 5), 100)); } function c(r) { return new Promise(resolve => setTimeout(() => resolve(r / 10), 100)); } // create this function composeAsync(c, b, a)(5, 3).then(result => { console.log(result); }).catch(console.error); Output: // 2 Related Link - https://leetcode.com/discuss/post/6938276/adobe-mts-2-interview-experience-fe-by-a-5h33/
Currying - Part 1
- Write a Javascript function that returns sum of the previous values. - We will see how to create a Javascript function that will remember its previously passed values and return the sum of the current and previous value. - Here is an example of what the output should be like. sum(5); // 5 sum(3); // 8 sum(4); // 12 sum(0); // 12 - As the 5 is the first value so the first function returned 5. As 3 is passed as the input to the second function the output is 5 + 3 = 8. - To create such functions we should know how the javascript function works. Javascript functions have access to the state (properties & methods) of its parent function even after it is executed. - So to create a function that will return the sum of the previous values in javascript we will use this technique of closure.
Currying - Part 2
- Currying in JavaScript is a concept of functional programming in which we can pass functions as arguments (callbacks) and return functions without any side effects (Changes to program states). # What is currying? - In simple terms, in currying we return a function for each function invoked which excepts next argument inline. With the help of currying we can transform a function with multiple arguments into a sequence of nesting functions. # Example //normal function sum(1, 2, 3) //should return 6 //currying function sum(1)(2)(3) //should return 6 - If you notice in the currying function for each function call sum(1) we are returning a function which accept next argument sum(1)(2) and it again returns a function which accepts argument sum(1)(2)(3) and so on. - There is no specified limit it to it how many times you return a function, also there are different variations to currying like the first function will accept the 2 arguments and the next function can accept any number of arguments and so. //variations of currying sum(1)(2)(3) sum(1, 2)(3) sum(1)(2, 3) sum(1, 2, 3) //all of them should return same output //6 - //variations of currying sum(1)(2)(3) sum(1, 2)(3) sum(1)(2, 3) sum(1, 2, 3) //all of them should return same output - Now you may be wondering each function call returns a new function then how the value is returned from it. Well for that we have to decide a base condition in which should return the output like if no argument is passed in the next function call then return the value or if we have reached 5 arguments then return the value, etc. sum(1)(2)(3)() sum(1, 2)(3)() sum(1)(2, 3)() sum(1, 2, 3)() //all of these should return 6 //OR //when we reach 5 arguments then return the value rather than new function sum(1, 2, 3, 4, 5) sum(1, 2)(3, 4, 5) sum(1)(2, 3, 4, 5) sum(1, 2, 3)(4, 5) sum(1)(2)(3)(4)(5) sum(1, 2, 3, 4)(5) //all should return 15 - I was recently asked this question in interview to implement the same currying function for 4 arguments. When we have reached the limit return the value. Note:- Maximum 4 arguments will only be passed. sum(1, 2, 3, 4) sum(1)(2)(3)(4) sum(1, 2)(3, 4) sum(1, 2, 3)(4) sum(1)(2, 3, 4) //all should return 10 sum(1, 2, 3, 4) sum(1)(2)(3)(4) sum(1, 2)(3, 4) sum(1, 2, 3)(4) sum(1)(2, 3, 4) - lets start implementing this. - First, lets handle the base case. - When the function is invoked in normal style sum(1, 2, 3, 4). In this all we have to do is check the number of arguments passed, if it is same as the limit provided return the sum of them.
Currying – part 3 (Infinite curry sum)
Write a function add() that satisfies the following. Example add(1)(2).value() = 3; add(1, 2)(3).value() = 6; add(1)(2)(3).value() = 6; add(1)(2) + 3 = 6; The add() method can accept any number of arguments and processed value is returned only when .value() method is invoked or operation with any primitive value is being done as you can see in the example. Followup: The add() method can take single argument add(1) or an array of arguments add([1, 2, 3, 4]).
Currying Part 1
This question was asked in Impact Analytic's SSE frontend interview. Create a JavaScript function that returns the sum of the previous values. Example const sum = curry(); sum(5); // 5 sum(3); // 8 sum(4); // 12 sum(0); // 12 Related Links - https://leetcode.com/discuss/post/8139832/senior-software-engineer-frontend-impact-32zc/
Deboucing - Part 1
Implement a debounce function that will invoke the function once in the specified duration.
Editable ToDo List
Machine coding challenge implementation and test cases.
Filter array of objects on value or index
Implement a function in JavaScript that filters an array of objects based on the value or index. Example Input: const arr = [ { name: "Amir", id: "1" }, { name: "Samlan", id: "2" }, { name: "Shahrukh", id: "0" }, ]; console.log(filterObject(arr, 0)); // { name: "Amir", id: "1" } console.log(filterObject(arr, "Amir")); // { name: "Amir", id: "1" } console.log(filterObject(arr, "0")); // { name: "Shahrukh", id: "0" } Note: You have to treat numeric values as index.
Filter Nested Object
This question was asked in Amazon's frontend interview Create a function in javascript which will take a nested object and a filter function as input and return the filtered object. Input: const obj = { a: 1, b: { c: "Hello World", d: 2, e: { f: { g: -4, }, }, h: "Good Night Moon", }, }; const filter = (s) => typeof s === "string"; Output: { b: { c: "Hello World", h: "Good Night Moon", } }; Related Link - https://leetcode.com/discuss/post/328553/amazon-phone-screen-deep-filter-by-anony-77xv/
Find Digital Root of a Number
Problem Statement: Write an algorithm to find the digital root of a given number. Digital root is the sum of the all the digits of the number till there is only digit left. Input: 5674 493193 Output: 4 // 5 + 6 + 7 + 4 = 22 = 2 + 2 = 4 2 // 4 + 9 + 3 + 1 + 9 + 3 = 29 = 2 + 9 = 11 = 1 + 1 = 2 Related Links - https://www.linkedin.com/posts/prakharchauhan281098_opentowork-frontenddevelopment-javascript-share-7281324741347430400-6sx1/?utm_source=share&utm_medium=member_desktop
Find highest commodity price under a timestamp
Machine coding challenge implementation and test cases.
Flatten a deeply nested object using dot notation
This question was asked in Adobe's SDE2 frontend interview and Impact Analytic's SSE frontend interview. Given an nested object which can have any type of value, deep flatten it on the dot notation and return the new object. Example Input: const nested = { A: "12", B: 23, C: { P: 23, O: { L: 56 }, Q: [1, 2] } }; console.log(flatten(nested)); Output: { "A": "12" "B": 23, "C.O.L": 56, "C.P": 23, "C.Q.0": 1, "C.Q.1": 2, }
Flatten an Array
Write a polyfill without using ES6 features to flatten an N depth array. Flattening an array is simple process of merging different N dimensional sub arrays to form a single array. Example: Input: [[[1, [1.1]], 2, 3], [4, 5]] Output: [1, 1.1, 2, 3, 4, 5]
Flatten An Array
This question was asked in the Meta’s frontend interview and Thoughtspot's frontend interview and MakeMyTrip's frontend interview and JobTwine's frontend interview. Write a polyfill without using ES6 features to flatten an N depth array. Flattening an array is simple process of merging different N dimensional sub arrays to form a single array. Example: Input: [[[1, [1.1]], 2, 3], [4, 5]] Output: [1, 1.1, 2, 3, 4, 5] Related Links - https://leetcode.com/discuss/post/5027017/meta-ic5-e5-frontend-london-rejected-by-m7988/ - https://leetcode.com/discuss/post/4867656/ThoughtSpot-MTS-Frontend-Role-Interview-Experience/ - https://leetcode.com/discuss/post/7150898/mmt-sse-2frontend-interview-experience-b-vwdg/ - https://leetcode.com/discuss/post/7258044/interview-experience-of-frontend-develop-lcjj/
Functional Modal Component
Machine coding challenge implementation and test cases.
Get object value from string path
This question was asked in Amazon's frontend interview. Implement a method in Javascript that will take an object and a string or array of strings as a path and return the value at that path. If nothing is found return undefined. Polyfill for lodash._get(). Example Input: const obj = { a: { b: { c: [1,2,3] } } }; console.log(get(obj, 'a.b.c')); console.log(get(obj, 'a.b.c.0')); console.log(get(obj, 'a.b.c[1]')); console.log(get(obj, 'a.b.c[3]')); Output: // [1,2,3] // 1 // 2 // undefined Related Link - https://leetcode.com/discuss/post/776553/amazonaws-fee-phone-interview-august-how-899j/
Implement a generator function promiseAccumulation()
Implement a generator function promiseAccumulation() that receives an arbitrary number of promises, then: - If the promise is resolved, it yields the returned value. - If the promise is rejected, it yields -1 and stops yielding values.
Implement an engine that process async callbacks
Machine coding challenge implementation and test cases.
Implement an Router middleware
/baz", "bar") // router.callRoute("/bar/a/baz") -> "bar" // if input is this - // router.addRoute("/foo/baz", "foo") // router.addRoute("/foo/*", "bar") // Give two different solutions to priortize // - Absolute path over wildcard path // - Return the result in the order the paths are added // Related Link - https://leetcode.com/discuss/post/5994275/atalassian-sde2-reject-by-anonymous_user-zv6c/ class Router { constructor() { this.routes = new Map(); } addRoute(route, result) { this.routes.set(route, result); } callRoute(route) { const valueOnPath = this.routes.get(route) ?? null; if (valueOnPath) return valueOnPath; const keys = this.routes.keys(); for (let key of keys) { if (this.wildcardMatch(key, route)) { return this.routes.get(key); } } } wildcardMatch(text, pattern) { const regexPattern = new RegExp( "^" + pattern.replace(/\\?/g, ".").replace(/\\
Implement deque data structure
Question: What is a deque data structure? Answer: Deque or Double-ended queue is a generalized version of queue in which data can be added and removed from both the ends. It performs both the combined operations of stack and queue together and can be used as any of them. Question: Why is deque data structure needed? Answer: It supports clockwise and anti-clockwise rotations in O(1) time which can be very useful in certain applications and also the problem where elements need to be removed and added from both the ends can be solved easily. # Example Input: let deque = new Deque(); deque.insertBack(5); deque.insertBack(10); console.log(deque.getBack()); deque.removeBack(); console.log(deque.getBack()); deque.insertFront(15); console.log(deque.getFront()); deque.removeFront(); console.log(deque.getFront()); Output: 10 5 15 # List of operations performed on Deque insertFront(): Inserts an element at the front. insertBack(): Inserts an element at the back. removeFront(): Removes an element from the front. removeBack(): Removes an element from the back. getFront(): Returns the element at the front. getBack(): Returns the element at the back. isEmpty(): Checks if the deque is empty or not. size(): Returns the size of the deque. clear(): Clears the deque. toString(): Returns all the elements concatenated as a string from front to back. Implement all of them.
Implement store class (hashSet) in JavaScript
Machine coding challenge implementation and test cases.
Implement two stack with an array
Create a data structure called twoStacks which will be using only a single array to store the data but will act as two different stacks. Example Input: let stack = new twoStacks(10); //Push data in first stack stack.push1('Prashant'); //Push data in second stack stack.push2('Yadav'); //Pop data from first stack console.log(stack.pop1()); //Pop data from second stack console.log(stack.pop2()); Output: "Prashant" "Yadav" The twoStacks data structure will perform following operations: push1(elm): This will add data in the first stack push2(elm): This will add data in the second stack pop1(): This will remove the data from the first stack pop2(): This will remove the data from the second stack
Method Chaining - Part 1
Explain method chaining in JavaScript by implementing a calculator that performs the basic actions like add, subtract, divide, and multiply. A similar question was asked in Birdeye's SSE frontend interview. Example 1 calculator.add(10).subtract(2).divide(2).multiply(5); console.log(calculator.total); //20 Example 2 const sum = read(10, 5).sum(); console.log(sum); // 15 const multiply = read(10, 5).multiply(); console.log(multiply); // 50 Note: You have to implement the solution that solves the problem. There are no test cases to this. Test it yourself using the example test cases.
Method Chaining - Part 1
Explain method chaining in JavaScript by implementing a calculator that performs the basic actions like add, subtract, divide, and multiply. Example calculator.add(10).subtract(2).divide(2).multiply(5); console.log(calculator.total); //20
Method Chaining - Part 2
This question was asked in NAVI's SDE2 frontend interview. Showcase a working demo of method chaining in JavaScript by implementing the following example. Example Input: computeAmount().lacs(15).crore(5).crore(2).lacs(20).thousand(45).crore(7).value(); Output: 143545000 Related Link - https://leetcode.com/discuss/post/2569900/navi-ui-engineer-2-bangalore-july-2022-o-b7ar/
Observer Design Pattern
This question was asked in Uber's frontend interview and Birdeye's SSE frontend interview. Create a simple Observable class that implements the observer pattern. The class should: - Allow subscribing to data changes via a subscribe method - Notify all subscribers when data changes via a fire method - Allow unsubscribing from updates - Maintain a list of subscriber callbacks const observable = new Observable(); // Subscribe to changes const subscription = observable.subscribe(data => { console.log('Received:', data); }); // Notify subscribers observable.fire('Hello!'); // logs: "Received: Hello!" // Unsubscribe subscription.unsubscribe(); // No longer logs anything observable.fire('Hello again!');
Piping - 1
Given an object which can have a function as a value at a nested level, create a function that will accept arguments as input and pass it through all the functions in the input object and return the computed value. Example Input: { a : { b : (a,b,c) => a+b+c, c : (a,b,c) => a+b-c, }, d : (a,b,c) => a-b-c } const output = pipe(obj)(1,1,1); console.log(output); Output: { a : { b : 3, c : 1 }, d: -1 }
Piping - 2
Create a function pipe that accepts multiple functions as an argument and a value and run this value through each function and return the final output. Input: const val = { salary: 10000 }; const getSalary = (person) => person.salary const addBonus = (netSalary) => netSalary + 1000; const deductTax = (grossSalary) => grossSalary - (grossSalary * .3); const result = pipe( getSalary, addBonus, deductTax )(val); Output: 7700
Polyfill for Array.filter()
It is extremely common question in JavaScript interviews where it is asked to implement polyfill for the filter() method. It was asked in Birdeye's SSE frontend interview. A polyfill is a browser fallback, made in JavaScript, that allows functionality you expect to work in modern browsers to work in older browsers. JavaScript array has an inbuilt method filter() which takes a callback function as input and returns a new array with the all elements the has passed the test implemented in the callback function. Example const arr = [1, 2, 3, 4, 5, 6]; const filtered = arr.filterPolyfill((e) => e % 2 === 0); console.log(filtered); //[2, 4, 6] Array.filter polyfill should have these three functionalities. - The filter() function should take an callback function as an argument. - Current element, its index, and the context should be passed as an argument to the callback function. - All the elements which pass text implemented in this callback function should be returned in a new array.
Polyfill for Array.map()
It is extremely common question in JavaScript interviews where it is asked to implement polyfill for the Array.map() method. It was asked in Birdeye's SSE frontend interview. A polyfill is a browser fallback, made in JavaScript, that allows functionality you expect to work in modern browsers to work in older browsers JavaScript array has an inbuilt method map() which takes a callback function as input and returns the processed data from this function in a new array. Example const arr = [1, 2, 3]; const multipliedArr = arr.mapPolyfill((e) => e * 2); console.log(multipliedArr); //[2, 4, 6] Array.map polyfill should have these two functionalities. - The map() function should take an callback function as an argument. - Current element, its index, and the context should be passed as an argument to the callback function.
Polyfill for useMemo() hook
Machine coding challenge implementation and test cases.
Preview selected color from swatches
Machine coding challenge implementation and test cases.
Promise.all() Polyfill
Promise.all() - It accepts an array of promises and returns a promise that resolve when all of the promises in the array are fullfilled or when the iterable contains no promises. It rejects with the reason of the first promise that rejects.
Promise.allSettled() Polyfill
Promsise.allSettled() - The Promise.allSettled() method returns a promise that fulfills after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise.
Promise.any() Polyfill
Promise.any() - It takes an iterable of Promise objects. It returns a single promise that fulfills as soon as any of the promises in the iterable fulfills, with the value of the fulfilled promise. if no promise in the iterable fulfill (if all of the given promises are rejected), then the returned promise is rejected with an Aggeregate Error, a new subclass of Error that groups together individual errors.
Promise.race() Polyfill
Promise.race() - it is a method that returns a promise that fulfills or rejects as soon as one of the promises is an iterable fulfills or rejects, with the value or reason from that promise.
Publisher Subscriber - 1
Observer design pattern in JavaScript, Also known as pub/sub pattern short for publication/subscription. It is clear from the name itself that if you are subscribed to the publication and if something is published in the publication it will notify the subscriber. A subscription model in which an object subscribes to a host and the host notifies the object whenever an event occurs is known as the observer pattern. It is one of the important pillars of event-driven programming and JavaScript is one of the most popular event-driven programming languages. This pattern promotes loose coupling facilitating good object-oriented design. JavaScript is the most avid user follower observer pattern and we use it almost regularly while building web apps. We write event handlers by creating event listeners that listen to an event and notify them every time the event is fired with some additional details of the event. For example, when a click event is triggered you can access the event object to get all the event details about the click like its position on the screen, etc. You can also remove the listener (unsubscribe) to stop listening if you want. Implementation To create the observer design pattern, we need to have two types of participants. 1.Hosts 1.It will maintain the list of observers. 2.Provides option to subscribe and unsubscribe to the observers. 3.Notifies the observer when state changes. 2.Observer 4.Has a function that gets called/invoked every time a state changes. Keeping these two things in mind, we can create the Observer design pattern in JavaScript.
Publisher Subscriber - 2
This is an advanced version of problem based on the publisher-subscriber pattern, this question was asked to me in the Coursera's frontend interview. Problem statement Implement the pub-sub pattern in JavaScript that has following methods: subscribe, subscribeOnce, and subscribeOnceAsync. •subscribe(name, callback): Will take the name of the event and assign a callback to it. This callback will be invoked when the event is published. It returns a remove() method to unsubscribe the event. •subscribeOnce(name, callback): Will take the name of the event and assign a callback to it. This event will be published only once. •subscribeOnceAsync(name): Will take the name of the event and returns a promise that is settled or fullfilled when the event is published. •publish(name, data): Publish a single event and pass the data to the callback of each events. If the event is subscribed only once, it should not invoke twice. •publishAll(name): Publishes all events and passes the data to the callback of each events. If the event is subscribed only once, it should not invoke twice.
Publisher-Subscriber - Part 1
This question was asked in Uber's screen interview and Livespace SDE2 interview. Create a simple Observable class that implements the observer pattern. The class should: - Allow subscribing to data changes via a subscribe method - Notify all subscribers when data changes via a notify method - Allow unsubscribing from updates - Maintain a list of subscriber callbacks const observable = new Observable(); // Subscribe to changes const subscription = observable.subscribe(data => { console.log('Received:', data); }); // Notify subscribers observable.notify('Hello!'); // logs: "Received: Hello!" // Unsubscribe subscription.unsubscribe(); // No longer logs anything observable.notify('Hello again!');
Related Links
Machine coding challenge implementation and test cases.
Remove Cycle from the object
Machine coding challenge implementation and test cases.
Sampling Function
Problem Statement: Create a function in JavaScript that accepts a function as input and a count and executes that input function once for a given count of calls. Known as sampling function. function message(){ console.log("hello"); } const sample = sampler(message, 4); sample(); sample(); sample(); sample(); // this will be executed sample(); sample(); sample(); sample(); // this will be executed
Sorting a Linked List
Problem Statement: Write an algorithm to sort a linked list.
Sum of all the resolved promises
Problem Statement -> An array of promises will be given that will either resolve (with number) or reject, If all the promises reject -> reject, else resolve with the sum of all resolved promises.
Sum up functions return value running in parallel and in sequence
This interview question was asked in Intuit’s SDE2 frontend interview, where the user was asked to run functions in parallel and in sequence and evaluate there performance. The problem statement reads as: Write two functions: A() returns 2 after 2 seconds B() returns 3 after 3 seconds Return their sum in two ways: Parallel execution → Total time: 3 seconds Sequential execution → Total time: 5 seconds
Sum up functions return value running in parallel and in sequence
This interview question was asked in Intuit’s SDE2 frontend interview, where the user was asked to run functions in parallel and in sequence and evaluate there performance. The problem statement reads as: Write two functions: A() returns 2 after 2 seconds B() returns 3 after 3 seconds Return their sum in two ways: Parallel execution → Total time: 3 seconds Sequential execution → Total time: 5 seconds Testcase const A = async () => { ... your code } const B = async () => { ... your code } const series = async () => { ... your code return resultA + resultB; } const parallel = async () => { ... your code return resultA + resultB; } const evaluate = async (fn, label) => { const startTime = performance.now(); console.log(`Executing ${label} task starts...`); let result = await fn(); const endTime = performance.now(); console.log(`Task ${label} finished in ${ Number.parseInt(endTime - startTime) } milliseconds with sum:`, result); } Input: evaluate(series, 'sequential'); evaluate(parallel, 'parallel'); Output: "Task sequential starting..." "Task parallel starting..." "Task parallel finished in 3029 milliseconds with," sum "Task sequential finished in 5011 milliseconds with," sum Related Link - https://leetcode.com/discuss/post/6770567/intuit-senior-frontend-engineer-by-anony-x1a5/