Method chaning in javascript

How do I create method chaining functionality similar to jQuery in JavaScript. For eg. I have a main function where I can add different methods to it like add, subtract, multiply, divide, while main function taking one param.

Main(5).add(3).subtract(2).multiply(4).divide(6)

or

Main(10).subtract(5).add(5).divide(6)

It can be anything.

I was trying to put methods in an object in the return statement of the parent function, but it didn’t work.

function main(a) {
    return {
        sum: function (b) {
            return a + b;
        },
        substract: function (c) {
            return a - c;
        },
    };
}

Please help

How to display a placeholder while scrolling in react native’s sectionlist?

I have a sectionList in a React Native app. It works at full speed on IOS devices, but it’s much slower on Android devices. I’ve made all possible optimizations. The biggest issue is that when scrolling very fast, the list renders a black screen, while all my rows are grey. So it looks weird and buggy.

Is it possible to display a placeholder while the list is scrolling (an empty grey row with a bottom border)? Or at least a grey background on my list?

The code is:

 <SafeAreaView style={styles.container}>
      <SectionList
        removeClippedSubviews={true}
        maxToRenderPerBatch={8}
        initialNumToRender={8}
        viewabilityConfig={{
          minimumViewTime: 300,
          viewAreaCoveragePercentThreshold: 100,
          waitForInteraction: true,
        }}
        sections={data}
        keyExtractor={(item) => item.name}
        renderItem={({ item }) => <ProfileCard profile={item} />}
        renderSectionHeader={({ section: { title } }) => (
          <Text style={styles.header}>{title}</Text>
        )}
      />
</SafeAreaView>

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Color.black,
    width: "100%",
    paddingHorizontal: 12,
    paddingTop: StatusBar.currentHeight, //12
  },
  header: {
    fontSize: 16,
    padding: 12,
    color: Color.white,
    fontWeight: "700",
    backgroundColor: Color.black_medium,
  }
});

Is there a better way to organize this dynamic class naming?

so I have this variable extend that is either an empty string or active
which is a CSS class.

once the top div is clicked, all subsequent elements updates with “active”

 <div
      className={`container ${extend ? "active" : ""}`}
      onClick={() => setExtend(!extend)}
    >
      <p className={`card ${extend ? "active" : ""}`}>Visa Card</p>
      <h1 className={`balance ${extend ? "active" : ""}`}>$55,343.15</h1>

then my CSS looks like this

.container {
&.active
}

.card {
&.active
}

.balance {
&.active
}


I feel like there is a lot of repetition in both CSS and JS and I am wondering if there is a more elegant way to do this

How to convert this Ajax ActionLink to Url Action or Something Similar?

I have the following Ajax ActionLink code:

render: function (data, type, row) {
    return '@Ajax.ActionLink("Confirm", "Edit", "ResidencyConfirmation",
        new { Id = data, ApplicationId = row.Id },
        new AjaxOptions { UpdateTargetId = "SubItemContainer",
            OnSuccess = "onShowSubItemSuccess",
            InsertionMode = InsertionMode.Replace },
        new { @class = "btn btn-primary" })';
}

This code is supposed to render buttons called “Confirm” in a jQuery datatable column. When one of the “Confirm” buttons is clicked, it is supposed to pass two Id parameters and then display a modal dialog. This functionality works if I hardcode the Ids, such as Id = new Guid("guid-value-here"), row.Id = new Guid("guid-value-here")

The challenge is that I am unable to pass the data and row.Id values as parameters.

I have been successful at passing data and row.x parameters using Url Actions, such as the following example:

render: function (row) {
    var applicationDetails = '@Url.Action("Details", "Application")/' + row.Id;
    return '<a href="' + applicationDetails + '" class="btn btn-info fa fa-folder-open"></a>';

How can I convert my Ajax ActionLink to a Url Action or something similar to perform the same functionality?

Can anyone please help me to find out what’s the problem in my code?

I am trying to display the current date and time of the system in my basic HTML page. I have used setInterval = (date, 1000); along with the date() function to achieve my goal.

I want to clear (i.e. don’t want to display any time) time on the screen after certain time(I have used `counter` variable to set a condition). For this I am using `clearInterval(ID)`.

However, when my counter becomes 5, my code is supposed to execute the `clearInterval` function and clear the screen. But, that does not happen and time(on the screen) keeps on displaying and the value of `counter` keeps on increasing.][1]

want the app to save the passing screen after a user has passed the test even when the app exits in react native

I am trying to build a learning app where the user will learn a skill and then give a certain test about it. The problem I am having is that once the user has passed the test, I want the app to always show the passing screen. Meaning, i don’t want the app to show the test screen all over everytime the user open the app rather once a test has been passed, the app should permanently store the passing state there. I have no idea how to do it! It would be great if someone helps!

Here’s code snippets:

export default test =({navigation}) => { 


  const [index, setind] = useState(0);
  const [idis, setidis] = useState(false);
  const [count, setcount] = useState(0);
  const [error, setError] = useState('');
  const [results, setResults] = useState('');
  const [disb, setdis] = useState(true);
  const [ndisb, setndis] = useState(true);

 useEffect(() => {
   //Setting callbacks for the process status
   Voice.onSpeechStart = onSpeechStart;
   Voice.onSpeechEnd = onSpeechEnd;
   Voice.onSpeechResults = onSpeechResults;
   Voice.onSpeechError = onSpeechError;

   return () => {
    //destroy the process after switching the screen
    Voice.destroy().then(Voice.removeAllListeners);
   
    
  };
}, []);

check function for test

function Check() {
  if (results.includes(words[index])){
   // console.log(index);
    Alert.alert('Correct!','You are learning so well!');
    
     if(index==7) {
      if(count<5)
      {
            //  Alert.alert('pass','pass');
            // showing passing screen in the form of a modal
            setshowpass(true);
      }
      else{
        Alert.alert('fail','fail');
      }
    }
    if (index==7){
      setndis(true);
      setdis(true);
      setidis(true);
    }
    else{
   setndis(false);
   setdis(true);
   setidis(true);
    }
   
  }
  else{
    Alert.alert('Ops!','Looks like you went wrong somewhere. Try again!');
    setcount(count+1);
    console.log('uc',count);
    setdis(true);
    setndis(true);
   
    if(count==5){
      Alert.alert('Restest', 'Looks like you had way too many mistakes!')
      setind(0);
      setcount(0);
      setdis(true);
    }
  }
}




     const words=['word1', 'wor2', 'word3', 'word4', 'wrd5', 'word6', 'wor7', 'w8'];
      
      
        const [showpass, setshowpass]=useState(false);

return (
    <View style={styles.body}
    >

        <Modal
          transparent={false}
          visible={showpass}
         animationType='slide'
          hardwareAccelerated 
          >
            <View style={styles.body}>
              <Text style={styles.toptext}>Congratulations!</Text>
              <Text style={styles.toptext}>Worked great in Turkishya!</Text>
              <Text style={styles.topptext}>
                And mastered the skill 'Alphabets'
              </Text>
            </View>
            </Modal>
<View>
);
}

How to give a toast message, when user add an item?

import React from 'react';

import { useForm } from “react-hook-form”;
import { toast } from ‘react-toastify’;

const AddStorage = () => {
const { register, handleSubmit } = useForm();

const onSubmit = data => {
    console.log(data);
    const url = `https://desolate-springs-82685.herokuapp.com/storage`;
    fetch(url, {
        method: 'POST',
        headers: {
            'content-type': 'application/json'
        },
        body: JSON.stringify(data)
    })
        .then(res => res.json())
        .then(result => {
            console.log(result);
             toast('Congrats! You added an order');
        })
};

return (
    <div className='w-50 mx-auto mb-5 mt-5 pb-5 pt-5'>
        <h2 className='text-center mb-4' >Please add a Storage</h2>
        <form className='d-flex flex-column' onSubmit={handleSubmit(onSubmit)}>
            <input className='mb-2' placeholder='Photo URL' type="text" {...register("img")} />
            <input className='mb-2' placeholder='Name' {...register("name", { required: true, maxLength: 20 })} />
            <input className='mb-2' placeholder='Capacity' type="number and text" {...register("capacity")} />
            <textarea className='mb-3' placeholder='Description' {...register("description")} />
            <input className='btn-success mb-4' type="submit" value="Add Storage" />
        </form>
    </div>
);

};

export default AddStorage;

React Google Maps Api doesn’t render children elements at first render

I’m trying to use Google Maps Api in my app, everything is fine until I want to display a Marker at the first render of the map. The Marker is not showing up, but if I add one more Marker after the render is done, the Marker will appear.

So the problem is that I want to render the map with a Marker already there, I don’t want to wait for some location to be selected.

I want to receive lat and lng from props, but for now I’ve made an hard coded const (center).

import React, { useMemo } from "react";
import { useJsApiLoader, GoogleMap, Marker } from "@react-google-maps/api";

export default function GoogleMaps({ lat, lng }) {
  const { isLoaded } = useJsApiLoader({
    googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY,
  });

  const center = useMemo(() => ({ lat: 42.4332, lng: 20.4343 }), []);

  if (!isLoaded) {
    return <h2>Calculating Locations..</h2>;
  }

  return (
    isLoaded && (
      <GoogleMap
        center={center}
        zoom={17}
        mapContainerStyle={{ width: "450px", height: "400px" }}
        options={{ disableDefaultUI: true, mapId: "deleted for this snippet" }}
      >
        <Marker position={center} />
      </GoogleMap>
    )
  );
}

Dynamic Input fields

I want to make input fields dynamic.
According to the user-selected option in one dropdown, I have to change to another select option, and also user can add more input fields and delete them.
I’m able to change according to users selection but now how I add more fields and delete it dynamically.
— script —-

<script>
    $(document).ready(function() {
      $("#standardone").change(function() {
        $(this).find("option:selected").each(function() {
          var optionValue = $(this).attr("value");
          if (optionValue == "ss") {
            $("#select1").show();
            $("#select2").hide();
            $("#select3").hide();
            $("#select4").hide();
            $("#select5").hide();
            $("#medium1").show();
            $("#board1").show();
          }
          if (optionValue == "C_1-4" || optionValue == "C_5-8" || optionValue == "C_9" || optionValue == "C_10" || optionValue == "C_9-10" || optionValue == "11-12_C") {
            $("#select1").show();
            $("#select2").hide();
            $("#select3").hide();
            $("#select4").hide();
            $("#select5").hide();
            $("#medium1").show();
            $("#board1").show();
          }
          if (optionValue == "11-12_S") {
            $("#select1").hide();
            $("#select2").hide();
            $("#select3").hide();
            $("#select4").show();
            $("#select5").hide();
            $("#medium1").show();
            $("#board1").show();
          }
          if (optionValue == "IIT-JEE") {
            $("#select1").hide();
            $("#select2").show();
            $("#select3").hide();
            $("#select4").hide();
            $("#select5").hide();
            $("#medium1").show();
            $("#board1").show();
          }
          if (optionValue == "NEET") {
            $("#select1").hide();
            $("#select2").hide();
            $("#select3").show();
            $("#select4").hide();
            $("#select5").hide();
            $("#medium1").show();
            $("#board1").show();
          }
          if (optionValue == "For_lang") {
            $("#select1").hide();
            $("#select2").hide();
            $("#select3").hide();
            $("#select4").hide();
            $("#medium1").hide();
            $("#board1").hide();
            $("#select5").show();
          }
        });
      }).change();    
    });
 </script>

—- body —-

<div class="col-sm-6 mb-3 ">
                  <div class="form-group">
                    <label for="name_of_business" class="font-weight-bold coac fw-bold">Standard</label>
                    <br>

                    <select name="std1" class="font-weight-bold" id="standardone">
                      <option value="ss">Select Standard</option>
                      <option value="C_1-4">Class 1-4</option>
                      <option value="C_5-8">Class 5-8</option>
                      <option value="C_9">Class 9</option>
                      <option value="C_10">Class 10</option>
                      <option value="11-12_C">11th-12th Commerce</option>
                      <option value="11-12_S">11th-12th Science</option>
                      <option value="IIT-JEE">IIT-JEE</option>
                      <option value="NEET">NEET</option>
                      <option value="For_lang">Foreign Langauges</option>
                    </select>
                  </div>
                </div>

                <div class="col-sm-6 mb-3">
                  <div class="form-group">
                    <label class="font-weight-bold fw-bold">Subjects</label>
                    <br>
                    <select name="sub11" class="font-weight-bold" id="select1">
                      <option value="ss">Select Subject</option>
                      <option value="all_sub">All Subjects</option>
                    </select>
                    <select name="sub12" class="font-weight-bold" id="select2">
                      <option value="ss">Select Subject</option>
                      <option value="all_sub">All Subjects</option>
                      <option value="Physics">Physics</option>
                      <option value="Chemistry">Chemistry</option>
                      <option value="Maths">Maths</option>
                    </select>
                    <select name="sub13" class="font-weight-bold" id="select3">
                      <option value="ss">Select Subject</option>
                      <option value="all_sub">All Subjects</option>
                      <option value="Physics">Physics</option>
                      <option value="Chemistry">Chemistry</option>
                      <option value="Biology">Biology</option>
                    </select>
                    <select name="sub14" class="font-weight-bold" id="select4">
                      <option value="ss">Select Subject</option>
                      <option value="all_sub">All Subjects</option>
                      <option value="Physics">Physics</option>
                      <option value="Chemistry">Chemistry</option>
                      <option value="Maths">Maths</option>
                      <option value="Biology">Biology</option>
                    </select>
                    <select name="sub15" class="font-weight-bold" id="select5">
                      <option value="ss">Select Languge</option>
                      <option value="Spoken_English">Spoken English</option>
                      <option value="German">German</option>
                      <option value="French">French</option>
                      <option value="Spanish">Spanish</option>
                    </select>
                  </div>
                </div>

facing this Error while running test case : InvalidArgumentError: missing field `handle` at line 1 column 2

Test Scenario :

  1. Open a web page (Candymapper.com)
  2. Close the Popup window

Code:

const {Builder, By, Key, util} = require("selenium-WebDriver");
const { Driver } = require("selenium-webdriver/edge");
async function example(){
    try{
    let driver = await new Builder().forBrowser("firefox").build();
    await driver.get("https://candymapper.com/");
    let handle = driver.getWindowHandle();
    await driver.switchTo().window()
    await driver.close();
    
   
}catch(error){
        console.log(error);
    }
}
example();

May be there are lots of mistakes I am new in automation please helpd

Creating a dynamic search bar using redux toolkit

This is a reducer that should change the state of the array

searchByName: (state) => {
      state.items.filter(name => name.toLowerCase().includes(state.users.toLowerCase()));
    }

This is a simple input bar in one of the components <input onChange={changeSearchTerm} type="text" value={searchTerm}></input>

The value is managed by useState() hook in the component.

What I’m trying to do is dispatches the value from the search bar

const changeSearchTerm = (e) => {
    setSearchTerm(e.target.value)
    dispatch(userActions(searchByName(searchTerm)));
  }

And then updates the state of the array, but I can’t seem to figure out how to properly send the value that’s been typed to the reducer so that it adjusts the array.