برچسب: Functions

  • 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

  • Trigonometric Functions – Sine – Useful code


    import numpy as np

    import matplotlib.pyplot as plt

    import matplotlib.animation as animation

     

    # Generate unit circle points

    theta = np.linspace(0, 2 * np.pi, 1000)

    x_circle = np.cos(theta)

    y_circle = np.sin(theta)

     

    # Initialize figure

    fig, ax = plt.subplots(figsize=(8, 8))

    ax.plot(x_circle, y_circle, ‘b-‘, label=“Unit Circle”)  # Unit circle

    ax.axhline(0, color=“gray”, linestyle=“dotted”)

    ax.axvline(0, color=“gray”, linestyle=“dotted”)

     

    # Add dynamic triangle components

    triangle_line, = ax.plot([], [], ‘r-‘, linewidth=2, label=“Triangle Sides”)

    point, = ax.plot([], [], ‘ro’)  # Moving point on the circle

     

    # Text for dynamic values

    dynamic_text = ax.text(0.03, 0.03, “”, fontsize=12, color=“black”, ha=“left”, transform=ax.transAxes)

     

    # Set up axis limits and labels

    ax.set_xlim(1.2, 1.2)

    ax.set_ylim(1.2, 1.2)

    ax.set_title(“Sine as a Triangle on the Unit Circle”, fontsize=14)

    ax.set_xlabel(“cos(θ)”, fontsize=12)

    ax.set_ylabel(“sin(θ)”, fontsize=12)

    ax.legend(loc=“upper left”)

     

    # Animation update function

    def update(frame):

        angle = theta[frame]

        x_point = np.cos(angle)

        y_point = np.sin(angle)

        degrees = np.degrees(angle) % 360  # Convert radians to degrees

        

        # Update triangle

        triangle_line.set_data([0, x_point, x_point, 0], [0, y_point, 0, 0])

        

        # Update point on the circle

        point.set_data([x_point], [y_point])  # Fixed this line to avoid the warning

        

        # Update text for angle, opposite side length, and sin(θ)

        dynamic_text.set_text(f“Angle: {degrees:.1f}°\nOpposite Side Length: {y_point:.2f}\nsin(θ): {y_point:.2f}”)

        return triangle_line, point, dynamic_text

     

    # Create animation

    ani = animation.FuncAnimation(fig, update, frames=len(theta), interval=20, blit=True)

    plt.show()



    Source link