avatarTechVirtuoso τεχνολογία

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

7742

Abstract

="hljs-regexp">/^[object (.+)]/</span>, <span class="hljs-string">'1'</span>) .<span class="hljs-title function_">toLowerCase</span>(); }</pre></div><p id="20bd"><b>Explanation</b>: The <code>deepClone</code> function recursively clones objects and arrays, preventing circular references using a <code>clonedMap</code>.</p><h1 id="38c9">10. Function Currying</h1><p id="4a08"><b>Question</b>: Implement an <code>add</code> function to achieve <code>1 + 2 + 3</code> as <code>add(1)(2)(3)</code>.</p><div id="3cea"><pre><span class="hljs-keyword">var</span> a = <span class="hljs-keyword">add</span>(<span class="hljs-number">1</span>)(<span class="hljs-number">2</span>)(<span class="hljs-number">3</span>)(<span class="hljs-number">4</span>); <span class="hljs-comment">// 10</span> <span class="hljs-keyword">var</span> b = <span class="hljs-keyword">add</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>); <span class="hljs-comment">// 10</span> <span class="hljs-keyword">var</span> c = <span class="hljs-keyword">add</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>); <span class="hljs-comment">// 10</span> <span class="hljs-keyword">var</span> d = <span class="hljs-keyword">add</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)(<span class="hljs-number">4</span>); <span class="hljs-comment">// 10</span>

console.log(a + <span class="hljs-number">10</span>); <span class="hljs-comment">// 20</span></pre></div><p id="d9da"><b>Answer</b>:</p><div id="f999"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">add</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">var</span> _args = [].<span class="hljs-property">slice</span>.<span class="hljs-title function_">call</span>(<span class="hljs-variable language_">arguments</span>);

<span class="hljs-keyword">var</span> _adder = <span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) {
    _args.<span class="hljs-title function_">push</span>(...<span class="hljs-variable language_">arguments</span>);
    <span class="hljs-keyword">return</span> _adder;
};

_adder.<span class="hljs-property">toString</span> = <span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) {
    <span class="hljs-keyword">return</span> _args.<span class="hljs-title function_">reduce</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params">a, b</span>) {
        <span class="hljs-keyword">return</span> a + b;
    });
}

<span class="hljs-keyword">return</span> _adder;

}

<span class="hljs-keyword">var</span> a = <span class="hljs-title function_">add</span>(<span class="hljs-number">1</span>)(<span class="hljs-number">2</span>)(<span class="hljs-number">3</span>)(<span class="hljs-number">4</span>); <span class="hljs-comment">// 10</span> <span class="hljs-keyword">var</span> b = <span class="hljs-title function_">add</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>); <span class="hljs-comment">// 10</span> <span class="hljs-keyword">var</span> c = <span class="hljs-title function_">add</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>); <span class="hljs-comment">// 10</span> <span class="hljs-keyword">var</span> d = <span class="hljs-title function_">add</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)(<span class="hljs-number">4</span>); <span class="hljs-comment">// 10</span>

<span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(a + <span class="hljs-number">10</span>); <span class="hljs-comment">// 20</span></pre></div><p id="456b"><b>Explanation</b>: The <code>add</code> function uses currying to allow both <code>(1)(2)(3)</code> and <code>(1, 2, 3)</code> syntax, achieving a flexible and expressive API.</p><h1 id="2bc9">11. Promise.all Implementation</h1><p id="3ef8"><b>Question</b>: Implement a <code>myAll</code> method similar to <code>Promise.all</code>.</p><div id="9695"><pre><span class="hljs-title function_">myAll</span>([ myPromise1, myPromise2 ]).<span class="hljs-title function_">then</span>(<span class="hljs-function">(<span class="hljs-params">[res1, res2]</span>) =></span> { <span class="hljs-comment">//...</span> })</pre></div><p id="7439"><b>Answer</b>:</p><div id="1912"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">myAll</span>(<span class="hljs-params">promises</span>) { <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> { <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Array</span>(promises.<span class="hljs-property">length</span>); <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>;

promises.<span class="hljs-title function_">forEach</span>(<span class="hljs-function">(<span class="hljs-params">p, index</span>) =&gt;</span> {
  p.<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> {
    result[index] = res;
    count++;
    <span class="hljs-keyword">if</span> (count === promises.<span class="hljs-property">length</span>) {
      <span class="hljs-title function_">resolve</span>(result);
    }
  })
  .<span class="hljs-title function_">catch</span>(reject);
});

}); }</pre></div><p id="04ec"><b>Explanation</b>: The <code>myAll</code> function mimics the behavior of <code>Promise.all</code>, resolving an array of results when all promises are fulfilled.</p><h1 id="18ce">12. Implementation of ‘instanceof’ Operator</h1><p id="74c9">Question: Implement an <code>instanceof</code> operator.</p><p id="d892"><b>Answer</b>:</p><div id="4195"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">myInstanceof</span>(<span class="hljs-params">left, right</span>) { <span class="hljs-keyword">if</span> (<span class="hljs-variable language_">arguments</span>.<span class="hljs-property">length</span> !== <span class="hljs-number">2</span>) { <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">"myInstanceof requires exactly two arguments."</span>); }

<span class="hljs-keyword">if</span> (left === <span class="hljs-literal">null</span>) { <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; }

<span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> left !== <span class="hljs-string">"object"</span>) { <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; }

<span class="hljs-keyword">let</span> proto = <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">getPrototypeOf</span>(left); <span class="hljs-keyword">while</span> (proto !== <span class="hljs-literal">null</span>) { <span class="hljs-keyword">if</span> (right.<span class="hljs-property"><s

Options

pan class="hljs-keyword">prototype</span></span> === proto) { <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>; } proto = <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">getPrototypeOf</span>(proto); }

<span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>; }</pre></div><p id="d70c"><b>Explanation</b>: The <code>myInstanceof</code> function checks if an object <code>left</code> is an instance of a constructor function <code>right</code> by traversing the object's prototype chain.</p><h1 id="7c6b">13. Debounce Function Implementation</h1><p id="ecde"><b>Question</b>: Implement a <code>debounce</code> function.</p><div id="0c05"><pre><span class="hljs-keyword">const</span> debouncedFn = <span class="hljs-title function_ invoke__">debounce</span>(<span class="hljs-keyword">fn</span>, <span class="hljs-number">1000</span>); <span class="hljs-keyword">const</span> cancel = <span class="hljs-title function_ invoke__">debouncedFn</span>();</pre></div><p id="e673"><b>Answer</b>:</p><div id="15d5"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">debounce</span>(<span class="hljs-params">fn, delay = <span class="hljs-number">500</span></span>) { <span class="hljs-keyword">let</span> timer;

<span class="hljs-keyword">return</span> <span class="hljs-keyword">function</span>(<span class="hljs-params">...args</span>) { <span class="hljs-built_in">clearTimeout</span>(timer);

timer = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
  fn.<span class="hljs-title function_">apply</span>(<span class="hljs-variable language_">this</span>, args);
}, delay);

<span class="hljs-comment">// Return a function to cancel the debounce</span>
<span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">clearTimeout</span>(timer);
}

} }</pre></div><p id="8246"><b>Explanation</b>: The <code>debounce</code> function delays the invocation of <code>fn</code> until a specified time has passed without additional calls. It returns a function to cancel the debounce.</p><h1 id="eae3">14. Implementation of ‘JSONP’ Function</h1><p id="b1eb"><b>Question</b>: Implement a JSONP cross-origin request function.</p><div id="0909"><pre><span class="hljs-title function_ invoke__">jsonp</span>(<span class="hljs-string">'/api/data'</span>, { <span class="hljs-attr">params</span>: { <span class="hljs-attr">name</span>: <span class="hljs-string">'jsonp'</span> }
})</pre></div><p id="9a49"><b>Answer</b>:</p><div id="3d51"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">jsonp</span>(<span class="hljs-params">url, options</span>) { <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> { <span class="hljs-keyword">const</span> script = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">createElement</span>(<span class="hljs-string">'script'</span>); <span class="hljs-keyword">const</span> callbackName = <span class="hljs-string">jsonpCallback_<span class="hljs-subst">${<span class="hljs-built_in">Date</span>.now()}</span>_<span class="hljs-subst">${<span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * <span class="hljs-number">10000</span>)}</span></span>;

<span class="hljs-keyword">const</span> timer = <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-title function_">cleanup</span>();
  <span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'JSONP request timeout'</span>));
}, options.<span class="hljs-property">timeout</span> || <span class="hljs-number">5000</span>);

<span class="hljs-keyword">function</span> <span class="hljs-title function_">cleanup</span>(<span class="hljs-params"></span>) {
  <span class="hljs-keyword">delete</span> <span class="hljs-variable language_">window</span>[callbackName];
  <span class="hljs-built_in">clearTimeout</span>(timer);
  script.<span class="hljs-title function_">remove</span>();
}

<span class="hljs-variable language_">window</span>[callbackName] = <span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>) {
  <span class="hljs-title function_">cleanup</span>();
  <span class="hljs-title function_">resolve</span>(data);
};

options.<span class="hljs-property">params</span> = options.<span class="hljs-property">params</span> || {};
options.<span class="hljs-property">params</span>[<span class="hljs-string">'callback'</span>] = callbackName;

<span class="hljs-keyword">const</span> paramsArr = <span class="hljs-title class_">Object</span>.<span class="hljs-title function_">keys</span>(options.<span class="hljs-property">params</span>).<span class="hljs-title function_">map</span>(<span class="hljs-function"><span class="hljs-params">key</span> =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">encodeURIComponent</span>(key)}</span>=<span class="hljs-subst">${<span class="hljs-built_in">encodeURIComponent</span>(options.params[key])}</span>`</span>;
});

script.<span class="hljs-property">src</span> = <span class="hljs-string">`<span class="hljs-subst">${url}</span>?<span class="hljs-subst">${paramsArr.join(<span class="hljs-string">'&amp;'</span>)}</span>`</span>;
script.<span class="hljs-property">onerror</span> = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-title function_">cleanup</span>();
  <span class="hljs-title function_">reject</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(<span class="hljs-string">'JSONP request error'</span>));
};

<span class="hljs-variable language_">document</span>.<span class="hljs-property">body</span>.<span class="hljs-title function_">appendChild</span>(script);

}); }</pre></div><p id="0b39"><b>Explanation</b>: The <code>jsonp</code> function dynamically creates a script element to handle JSONP requests, providing a Promise-based API for cross-origin requests.</p><p id="8802">These implementations cover a variety of advanced JavaScript concepts, ranging from object cloning and currying to asynchronous patterns like Promise.all and debounce. Understanding and practicing these concepts will enhance your proficiency in JavaScript development.</p><p id="1628">If you found this article helpful, please encourage me by giving it a clap. Follow me for more interesting articles on web development.</p><h1 id="cec4">Stackademic</h1><p id="f8ee">Thank you for reading until the end. Before you go:</p><ul><li>Please consider <b>clapping</b> and <b>following</b> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><b>X</b></a><b> | <a href="https://www.linkedin.com/company/stackademic">LinkedIn</a> | <a href="https://www.youtube.com/c/stackademic">YouTube</a> | <a href="https://discord.gg/in-plain-english-709094664682340443">Discord</a></b></li><li>Visit our other platforms: <a href="https://plainenglish.io"><b>In Plain English</b></a><b> | <a href="https://cofeed.app/">CoFeed</a> | <a href="https://venturemagazine.net/">Venture</a></b></li></ul></article></body>

Challenging JavaScript Interview Questions for Senior Developers for High Salaries — Part 2

Today, let’s continue with our advanced JavaScript interview questions series, and hope it can help you get the senior position that you desire.

8. JSONP Cross-Origin Request

Question: Implement a JSONP cross-origin request.

jsonp('/api/data', {
  params: {
    name: 'jsonp'
  }  
})

Answer:

function jsonp(url, options) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    const callbackName = `jsonpCallback_${Date.now()}_${Math.floor(Math.random() * 10000)}`;

    const timer = setTimeout(() => {
      cleanup();
      reject(new Error('JSONP request timeout'));
    }, options.timeout || 5000);

    function cleanup() {
      delete window[callbackName];
      clearTimeout(timer);
      script.remove();
    }

    window[callbackName] = function(data) {
      cleanup();
      resolve(data);
    };

    options.params = options.params || {};
    options.params['callback'] = callbackName;

    const paramsArr = Object.keys(options.params).map(key => {
      return `${encodeURIComponent(key)}=${encodeURIComponent(options.params[key])}`;
    });

    script.src = `${url}?${paramsArr.join('&')}`;
    script.onerror = () => {
      cleanup();
      reject(new Error('JSONP request error'));
    };

    document.body.appendChild(script);
  });
}

Explanation: The jsonp function creates a script element to handle JSONP requests, utilizing a dynamically generated callback function.

9. Deep Clone Implementation

Question: Implement a deepClone function for deep object cloning.

const obj = {
  a: 1,
  b: {
    c: 2
  }
}

const clone = deepClone(obj);

Answer:

function deepClone(source, clonedMap) {
  clonedMap = clonedMap || new Map();

  if (source === null || typeof source !== 'object') {
    return source;
  }

  if (clonedMap.has(source)) {
    return clonedMap.get(source);
  }

  var result;
  var type = getType(source);

  if (type === 'object' || type === 'array') {
    result = type === 'array' ? [] : {};

    clonedMap.set(source, result);

    for (var key in source) {
      if (source.hasOwnProperty(key)) {
        result[key] = deepClone(source[key], clonedMap);
      }
    }
  } else {
    result = source;
  }

  return result;
}

function getType(source) {
  return Object.prototype.toString
    .call(source)
    .replace(/^\[object (.+)\]$/, '$1')
    .toLowerCase();
}

Explanation: The deepClone function recursively clones objects and arrays, preventing circular references using a clonedMap.

10. Function Currying

Question: Implement an add function to achieve 1 + 2 + 3 as add(1)(2)(3).

var a = add(1)(2)(3)(4);   // 10
var b = add(1, 2, 3, 4);   // 10
var c = add(1, 2)(3, 4);   // 10
var d = add(1, 2, 3)(4);   // 10

console.log(a + 10); // 20

Answer:

function add() {
    var _args = [].slice.call(arguments);

    var _adder = function() {
        _args.push(...arguments);
        return _adder;
    };

    _adder.toString = function () {
        return _args.reduce(function (a, b) {
            return a + b;
        });
    }

    return _adder;
}

var a = add(1)(2)(3)(4);   // 10
var b = add(1, 2, 3, 4);   // 10
var c = add(1, 2)(3, 4);   // 10
var d = add(1, 2, 3)(4);   // 10

console.log(a + 10); // 20

Explanation: The add function uses currying to allow both (1)(2)(3) and (1, 2, 3) syntax, achieving a flexible and expressive API.

11. Promise.all Implementation

Question: Implement a myAll method similar to Promise.all.

myAll([
  myPromise1, 
  myPromise2
]).then(([res1, res2]) => {
  //...
})

Answer:

function myAll(promises) {
  return new Promise((resolve, reject) => {
    const result = new Array(promises.length);
    let count = 0;

    promises.forEach((p, index) => {
      p.then(res => {
        result[index] = res;
        count++;
        if (count === promises.length) {
          resolve(result);
        }
      })
      .catch(reject);
    });
  });
}

Explanation: The myAll function mimics the behavior of Promise.all, resolving an array of results when all promises are fulfilled.

12. Implementation of ‘instanceof’ Operator

Question: Implement an instanceof operator.

Answer:

function myInstanceof(left, right) {
  if (arguments.length !== 2) {
    throw new Error("myInstanceof requires exactly two arguments.");
  }

  if (left === null) {
    return false;
  }

  if (typeof left !== "object") {
    return false;
  }

  let proto = Object.getPrototypeOf(left);
  while (proto !== null) {
    if (right.prototype === proto) {
      return true;
    }
    proto = Object.getPrototypeOf(proto);
  }

  return false;
}

Explanation: The myInstanceof function checks if an object left is an instance of a constructor function right by traversing the object's prototype chain.

13. Debounce Function Implementation

Question: Implement a debounce function.

const debouncedFn = debounce(fn, 1000);
const cancel = debouncedFn();

Answer:

function debounce(fn, delay = 500) {
  let timer;

  return function(...args) {
    clearTimeout(timer);

    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);

    // Return a function to cancel the debounce
    return () => {
      clearTimeout(timer);
    }
  }
}

Explanation: The debounce function delays the invocation of fn until a specified time has passed without additional calls. It returns a function to cancel the debounce.

14. Implementation of ‘JSONP’ Function

Question: Implement a JSONP cross-origin request function.

jsonp('/api/data', {
  params: {
    name: 'jsonp'
  }  
})

Answer:

function jsonp(url, options) {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    const callbackName = `jsonpCallback_${Date.now()}_${Math.floor(Math.random() * 10000)}`;

    const timer = setTimeout(() => {
      cleanup();
      reject(new Error('JSONP request timeout'));
    }, options.timeout || 5000);

    function cleanup() {
      delete window[callbackName];
      clearTimeout(timer);
      script.remove();
    }

    window[callbackName] = function(data) {
      cleanup();
      resolve(data);
    };

    options.params = options.params || {};
    options.params['callback'] = callbackName;

    const paramsArr = Object.keys(options.params).map(key => {
      return `${encodeURIComponent(key)}=${encodeURIComponent(options.params[key])}`;
    });

    script.src = `${url}?${paramsArr.join('&')}`;
    script.onerror = () => {
      cleanup();
      reject(new Error('JSONP request error'));
    };

    document.body.appendChild(script);
  });
}

Explanation: The jsonp function dynamically creates a script element to handle JSONP requests, providing a Promise-based API for cross-origin requests.

These implementations cover a variety of advanced JavaScript concepts, ranging from object cloning and currying to asynchronous patterns like Promise.all and debounce. Understanding and practicing these concepts will enhance your proficiency in JavaScript development.

If you found this article helpful, please encourage me by giving it a clap. Follow me for more interesting articles on web development.

Stackademic

Thank you for reading until the end. Before you go:

JavaScript
Javascript Tips
Interview
Interview Questions
Front End Development
Recommended from ReadMedium