Is there a more efficient alternative to `[].push.apply(this, arr)` for combining elements in an array instance within a constructor?

It only takes 0.15ms for this line in my constructor function to execute.

[].push.apply(this, selector);

I'm not satisfied with the 0.15ms execution time. I believe there must be a quicker alternative available.

This particular line seems to be converting NodeList/HTMLCollection to an array. But do I really need it to be in array format? Perhaps there is another solution that can be used instead. Any ideas?

(function () {
    'use strict';
    
    function Query(selector) {
        if (selector.indexOf('.') !== -1) {
            selector = document.querySelectorAll(selector);
        }
        else {
            selector = document.getElementsByTagName(selector);
        }
        
        [].push.apply(this, selector);
    }
    
    function $(selector) {
        return new Query(selector);
    }
    
    
    Query.prototype = new Array;
    Query.prototype.hide = function () {
        for (var i=0,len=this.length;  i<len;  i++) {
            this[i].style.display = 'none';
        }
        return this;
    };
    
    
    window.$= $;
}());

Answer №1

Upon receiving insightful recommendations from @SebastianSimon this[0] = selector[0]; and @PeterSeliger this.push(...selector); in the comments, I entertained the idea of a for-loop.

Through thorough testing, it became apparent that this approach was quicker than using "[].push.apply(this, selector);".

I am open to further guidance from seasoned developers on this matter.

(function () {
    'use strict';
    
    function Query(selector) {
        if (selector.indexOf('.') !== -1) {
            selector = document.querySelectorAll(selector);
        }
        else {
            selector = document.getElementsByTagName(selector);
        }
        
        //[].push.apply(this, selector);
        var i=0,  len=selector.length;
        for (;  i<len;  ) {
            this[i] = selector[i++];
        }
        this.length = len;
    }
    
    function $(selector) {
        return new Query(selector);
    }
    
    
    Query.prototype = new Array;
    Query.prototype.hide = function () {
        for (var i=0,len=this.length;  i<len;  i++) {
            this[i].style.display = 'none';
        }
        return this;
    };
    
    
    window.$= $;
}());

Answer №2

(function () {

  'use strict';

  class Query extends Array {

    constructor(selector) {
      super();

      this.push(...document.querySelectorAll(selector));
    }
    hide() {
      for (var idx = 0, len = this.length;  idx < len; idx++) {
        this[idx].style.display = 'none';
      }
      return this;
    }
    show() {
      for (var idx = 0, len = this.length;  idx < len; idx++) {
        this[idx].style.display = '';
      }
      return this;
    }
  }

  function $(selector) {
    return new Query(selector);
  }
  window.$ = $;

}());

const query = $('span');

setTimeout(() => query.hide(), 1000);
setTimeout(() => $('.quick-fox > span').show(), 2000);

setTimeout(() => console.log({ query }), 3000);
setTimeout(() => console.log('query.push(...$("p")) ...', query.push(...$("p"))), 4000);
setTimeout(() => console.log({ query }), 5000);
<p class="foo-bar">
  <span>foo</span>
  <span>bar</span>
  <span>baz</span>
</p>

<p class="quick-fox">
  <span>The</span>
  <span>quick</span>
  <span>brown</span>
  <span>fox</span>
</p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leverage the power of Reactjs to add hover effects to a mapped

I am facing a challenge in styling the ListItem on hover. The issue arises when the list is dynamically generated, causing all list items to change style simultaneously when hovered over. How can I target only one element for styling? Below is the code sni ...

What is the best way to turn each function within the module pattern into a promise?

Utilizing Angular 1.5, I have developed a factory function that returns a literal object structured as follows: return { item: null, get: function() { return item; }, create: function() { if (this.get()){ this.remove(); ...

Issues with loading content in jQuery's ajax() function

Having an issue with the ajax() function in jQuery. It seems like a simple problem, but I'm struggling to figure it out. My goal is to load content from another HTML file using ajax and here's the code I have so far: $(function(){ $('.submi ...

The absence of 'www' in the ajax path is causing an error

Apologies for my poor English as I am currently a student. My issue is related to the use of ajax without "www" in the URL. Let me demonstrate. var path = "www.sinemayolu.com"; //Real-time Ajax Search $('.searchtext').keyup(function ...

How can you extract elements from a JSON array into separate variables based on a specific property value within each element?

In the following JSON array, each item has a category property that determines its grouping. I need to split this array into separate JSON arrays based on the category property of each item. The goal is to extract all items with the category set to person ...

The Discord.js guildMemberUpdate event: Everything you need to know

I am currently working on creating a welcome message bot using Discord.js. The goal is to have the bot send a welcome message through a webhook in a specific channel when a member gains access to it. Here's what I have so far: client.on("guildMe ...

How can contextual binding be implemented in TypeScript?

In Laravel, you have the option to specify which class should be imported if a particular class is accessed. For example, if someone tries to use the Filesystem contract, it will return the Storage Facade (Laravel Contextual Binding). Similarly, if someo ...

Using PHP, show a specific table row when clicked by matching the ID

I am currently developing an application for a school project that manages tests. This app allows employees to log in, select a client, register clients, and conduct tests with them, all while storing the data in a database. I have successfully implemente ...

Multiple occurrences of trigger events were detected when loading ajax content

In a div I have embedded a paragraph and a button as shown below: <div id="my_div"> <p>This is a paragraph</p> <button class="my_btn">Click here!</a> </div> The content within the div is dynamically loaded via ...

Resizing an image based on the coordinates of a click position by utilizing jQuery

I'm new to experimenting with code, and I've been playing around with trying to shrink an image to nothing at a central point. I've found some success using a mix of the code snippet below and relative positioning in my CSS. $(function() ...

Having trouble extracting the date modified from a JSON file

I am able to retrieve section name, URL, web title, and headline from parsing JSON data with this code snippet. However, I seem to be encountering an issue where I cannot extract the last modified date. Here is the JSON structure: { "response":{ ...

Building a conditional statement in React based on the URL path: A beginner's guide

I want to incorporate a transparent menu specifically on the homepage. How should I go about this? I've established a constant named isHomePage and now I need to set a URL (the index.tsx) to define this constant. function MyApp({ Component, pageProps ...

Extracting text from an HTML file and passing it to an Express.js server: A beginner

Currently, I'm attempting to retrieve the values from an HTML text field and store them in variables. I require HTML to capture these values and return the response within the .html file. HTML: <body> <form> ...

Breaking down objects and setting default values

In need of assistance with resolving an issue related to default parameters and object destructuring. The 'product' object that I am working with has the following structure: { name: "Slip Dress", priceInCents: 8800, availableSizes ...

Make the jQuery toggle() function work like a regular radio button when selecting multiple options at a time

I have recently created two radio buttons using <i> font icons. Previously, I had successfully used the same code to create a checkbox, so I applied it to the radio buttons as well. After fixing the positioning, everything seemed fine when interactin ...

DANGEROUS EVALUATION: Tips for Safe Replacement

Looking for a safer alternative to the code below which utilizes eval. The script creates pop-up windows based on different classes. /* exported popup_default , popup_help , popup_sitemap , popup_footerlinks */ var matchClass = ['popup_default' ...

Identify the difference between a regular function and a constructor in JavaScript

How can we determine whether a function in javascript is a simple, plain (anonymous) function, or a constructor (a function with a prototype)? I have developed the following function for this purpose: function checkFunctionType(value) { var ownPropert ...

Preserve the chosen option in a dropdown menu even after a postback using JavaScript

Seeking Help in Retaining Dropdownlist Selected Value After Postback In my efforts to retain a dropdownlist selected value after postback, I have been exploring various methods. I extract the selected values from the dropdownlist and store them in local ...

Is it possible to implement pagination using 'useSWR' in combination with the contentful-client?

I am currently working on implementing pagination in a Next.js project using the useSWR hook. My approach seems to be functioning correctly, but I have a concern about caching due to the key parameter not being a unique string as recommended in the documen ...

Executing function inside an Angular factory

I am currently working with an Angular factory that contains various functions. My goal is to use myService to retrieve data, and upon successful retrieval, call another function within the factory: myApp.factory('myFactory', function($http) { ...