برچسب: Array

  • Access items from the end of the array using the ^ operator | Code4IT

    Access items from the end of the array using the ^ operator | Code4IT


    Just a second! 🫷
    If you are here, it means that you are a software developer.
    So, you know that storage, networking, and domain management have a cost .

    If you want to support this blog, please ensure that you have disabled the adblocker for this site.
    I configured Google AdSense to show as few ADS as possible – I don’t want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.

    Thank you for your understanding.
    Davide

    Say that you have an array of N items and you need to access an element counting from the end of the collection.

    Usually, we tend to use the Length property of the array, and then subtract the number corresponding to the position we want to reach:

    string[] values = {
        "alfa",
        "bravo",
        "charlie",
        "delta",
        "echo",
        "foxtrot",
        "golf"
    };
    
    var echo = values[values.Length - 3];
    

    As you can see, we are accessing the same variable twice in a row: values[values.Length - 3].

    We can simplify that specific line of code by using the ^ operator:

    string[] values = {
        "alfa",
        "bravo",
        "charlie",
        "delta",
        "echo",
        "foxtrot",
        "golf"
    };
    
    var echo = values[^3];
    

    Yes, that’s just syntactic sugar, but it can help make your code more readable. In fact, if you have a look at the IL code generated by both examples, they are perfectly identical. IL is quite difficult to read and understand, but you can acknowledge that both syntaxes are equivalent by looking at the decompiled C# code:

    C# decompiled code

    Performance is not affected by this operator, so it’s just a matter of readability.

    Clearly, you still have to take care of array bounds – if you access values[^55] you’ll get an IndexOutOfRangeException.

    Pay attention that the position is 1-based!

    string[] values = {
        "alfa",
        "bravo",
        "charlie",
        "delta",
        "echo",
        "foxtrot",
        "golf"
    };
    
    Console.WriteLine(values[^1]); //golf
    Console.WriteLine(values[^0]); //IndexOutOfRangeException
    

    Further readings

    Using ^ is a nice trick that many C# developers don’t know. There are some special characters that can help us but are often not used. Like the @ operator!

    🔗 C# Tip: use the @ prefix when a name is reserved

    This article first appeared on Code4IT 🐧

    Wrapping up

    In this article, we’ve learned that just using the right syntax can make our code much more readable.

    But we also learned that not every new addition in the language brings performance improvements to the table.

    I hope you enjoyed this article! Let’s keep in touch on Twitter or on LinkedIn, if you want! 🤜🤛

    Happy coding!

    🐧





    Source link

  • Top 10 JavaScript Array Functions.

    Top 10 JavaScript Array Functions.


    Unlocking the Power of JavaScript: The Top 10 Array Functions You Need to Know.

    JavaScript, the language that breathes life into web pages, has a powerful array of functions that can transform your code into elegant, efficient, and concise masterpieces. Whether you’re a seasoned developer or just starting, mastering these functions will elevate your coding skills and streamline your workflow.

    In this blog post, we dive into the top 10 JavaScript array functions every developer should have in their toolkit. From transforming data with map() and filter() to perform complex operations reduce(), we’ll explore each function with examples and best practices. Join us on this journey as we unlock the potential of JavaScript arrays and take your coding abilities to the next level.

    Here are the top 10 JavaScript array functions that are widely used due to their efficiency and versatility:

    1. map():

    • Purpose: Creates a new array by applying a callback function to each element of the original array.
    • Example:
    const numbers = [2, 3, 4, 5];
    const squared = numbers.map(x => x * x);
    console.log(squared);
    

    2. filter():

    • Purpose: Creates a new array with all elements that pass the test implemented by the provided callback function.
    • Example:
    const numbers = [2, 3, 4, 5]; 
    const evens = numbers.filter(x => x % 2 === 0);
    console.log(squared);
    

    3.reduce():

    • Purpose: Executes a reducer function on each element of the array, resulting in a single output value.It integrate a whole array into a single value using a callback function.
    • Example:
    const numbers = [2, 3, 4, 5]; 
    const sum = numbers.reduce((total, num) => total + num, 0); 
    console.log(sum); 
    

    4.forEach():

    • Purpose: Executes a provided function once for each array element.
    • Example:
    const numbers = [2, 3, 4, 5]; 
    numbers.forEach(x => console.log(x));
    

    5.find():

    • Purpose: Returns the value of the first element in the array that satisfies the provided testing function.
    • Example:
    const numbers = [2, 3, 4, 5]; 
    const firstEven = numbers.find(x => x % 2 === 0);
    console.log(firstEven);
    output: 2

    6.some():

    • Purpose: Tests whether at least one element in the array passes the test implemented by the provided callback function. 
    • Example:
    const numbers = [2, 3, 4, 5];
    const hasEven = numbers.some(x => x % 2 === 0);
    console.log(hasEven); output: true

    7.every():

    • Purpose: Tests whether all elements in the array pass the test implemented by the provided function.
    • Example:
    const numbers = [2, 3, 4, 5]; 
    const allEven = numbers.every(x => x % 2 === 0);
    console.log(allEven); output: false

    8.includes():

    • Purpose: Determines whether an array includes a certain value among its entries, returning true or false as appropriate.
    • Example:
    const numbers = [2, 3, 4, 5]; 
    const hasNumber = numbers.includes(5);
    console.log(hasNumber); output: false

    9.push():

    • Purpose: Adds one or more elements to the end of an array and returns the new length of the array.
    • Example:
    const numbers = [2, 3, 4, 5]; 
    numbers.push(6);
    console.log(hasNumber); output: [2, 3, 4, 5,6];

    10.slice():

    • Purpose: Returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included).
    • Example:
    const numbers = [2, 3, 4, 5]; 
    const subArray = numbers.slice(1, 3); 

    These functions are fundamental tools in JavaScript programming, enabling you to manipulate and traverse arrays effectively.

    JavaScript Program To Check Whether a String is Palindrome or Not.      Binary Gap In Javascript.



    Source link