Calculator using JQuery

I am trying to create calculator using JQuery, HTML and CSS.
Numbers should be displayed on screen when I click on number button.
When I click on ‘C’ – I need to clear screen to default value.
When I select one operator, then another, the second one should replace first one on the screen.
When I click on ‘=’ – I need to display result on screen.

This is my code, but it doesn’t work properly.
js:

$(function () {
var functionButtons = "*/-+";
$(".calc-btn").each(function () {
    var $t = $(this);
    $(this).click(function () {
    if (functionButtons.indexOf($(".result").val().slice(-1)) > 0) {
        $(".result").val(
        $(".result")
            .val()
            .slice(0, $(".result").val().length - 1) + $(this).html()
        );
    }
    if ($(".result").val() != "NaN" && $(".result").val() != "Infinity") {
        if (+$t.val() >= 0 && +$t.val() <= 9) {
        $(".result").val($(".result").val() + $(this).html());
        }
    }
    });
});
$(".equal").on("click", function () {
    exp = $(".result").val();
    $(".result").val(eval(exp));
});
$(".clear").on("click", function () {
    $(".result").val("");
});
});

Vue Testing Library: How to mock Vue component

We usualy have components that use other components. So when testing our component say ComponentA it may use ComponentB and ComponentC. While there are some components that we want to be rendered (ComponentA and ComponentB) and want to test how they interact with our component, there are also others (ComponentC), which we may not want to test here, because they have their own tests. I.e. we want to “shallow-render” ComponentC when testing ComponentA.

Using react testing library we can do this:

import * as mockedComponentCModule from '....ComponentC';

jest.spyOn(mockedComponentCModule, 'ComponentC').mockImplementation(() => (
    <div data-testid="mocked-component-c" />
));

So in react when we do render(<ComponentA />) the ComponentC will render as a simple div instead of the actual component.

My question is – how can I do this with Vue Testing Library?

Is there a faster way to do ZigZag encoding in JavaScript that works with large numbers?

I am attempting to perform ZigZag encoding for numbers in JavaScript that are within the safe bounds of JavaScript integers

These functions seem to work up to 2^30 - 1 only because JavaScript bit-wise operators only work with 32 bit numbers:

function encodeZigzag(value) {
  return ((value << 1) ^ (value >> 31));
}

function decodeZigzag(encoded) {
  return (encoded >> 1) ^ -((encoded & 1));
}

console.log(decodeZigzag(encodeZigzag(0)));
console.log(decodeZigzag(encodeZigzag(-1))); 
console.log(decodeZigzag(encodeZigzag(2))); 
console.log(decodeZigzag(encodeZigzag(-2))); 
console.log(decodeZigzag(encodeZigzag(1073741823))); 
console.log(decodeZigzag(encodeZigzag(1073741824))); // breaks

Anyways, I was looking for a pair of alternate functions that worked up to a larger upper-bound (2^53 or so). I came up with these, which seem to work, but I was wondering if there was a more elegant / performant way:

function bigEncodeZigzag(v) {
  const shift = v * 2;

  return v >= 0 ? shift : -shift - 1;
}

function bigDecodeZigzag(v) {
  const shift = Math.floor(v / 2);

  return v % 2 === 0 ? shift : -shift - 1;
}

console.log(bigDecodeZigzag(bigEncodeZigzag(0)));
console.log(bigDecodeZigzag(bigEncodeZigzag(-1))); 
console.log(bigDecodeZigzag(bigEncodeZigzag(2))); 
console.log(bigDecodeZigzag(bigEncodeZigzag(-2))); 
console.log(bigDecodeZigzag(bigEncodeZigzag(1073741823))); 
console.log(bigDecodeZigzag(bigEncodeZigzag(1073741824))); // works

tts Code doesnt work anymore after page reload?

i am trying to add a text to speech button to my website and another button that stops it again. It worked perfectly before until i reloaded the page, then it didnt do anything anymore.

So I tried adding window.onload= function but then it just starts reading as soon as i reload the page. but i want it to only read if you click the button and stop when the stop button is pressed. I dont understand what i am doing wrong especially because it used to work sometimes and then it didnt again even when i didnt really change the code

  window.speechSynthesis.cancel();
  function textToSpeech()
{
   const speech = new SpeechSynthesisUtterance();
    let voices = speechSynthesis.getVoices();
    let convert = document.getElementById("text").innerHTML;
    speech.text = convert;
    speech.volume = 2;
    speech.rate = 1;
    speech.pitch = 1;
    speech.voice = voices[1];
    speechSynthesis.speak(speech);
}
function stop()
{
    window.speechSynthesis.cancel();
}
 speakBtn.addEventListener('click', textToSpeech);
cancelBtn.addEventListener('click', stop);
 </script>
 <input type="button" id="1200196725" value="Speak" style="float: left; 
background-color:#00a2ab;
display:inline-block;
padding:0.3em 1.2em;
margin:0 0.3em 0.3em 0;
border-radius:2em;
box-sizing: border-box;
text-decoration:none;
font-family:'Roboto',sans-serif;
font-weight:300;
color:#FFFFFF;">
 <input type="button" id="1731941681" value="Stop" style="float: left;background-color:#d4004b;
display:inline-block;
padding:0.3em 1.2em;
margin:0 0.3em 0.3em 0;
border-radius:2em;
box-sizing: border-box;
text-decoration:none;
font-family:'Roboto',sans-serif;
font-weight:300;
color:#FFFFFF;">
 <p id="1112939208" style="display:none">
  my text here
 </p>

have multiple like buttons while having local storage still working

I have this like buttons that can be toggled from like or dislike and it saves its position with local storage so if you refresh the position it will stay the same. The only thing is that I do not know how to have multiple of these that work and save in local storage.

in snippet the code won-t work because of local storage but in vs code or in replit it should work.

const btn1 = document.querySelector('#green');
const btn2 = document.querySelector('#red');

const likeStatus = localStorage.getItem('like-status');
if (likeStatus) {
  if (likeStatus === 'liked') {
    btn1.classList.add('green');
  }
  if (likeStatus === 'disliked') {
    btn2.classList.add('red');
  }
}

btn1.addEventListener('click', () => {
  setButtonColorAndAddToLocalStorage(btn1, 'green', btn2, 'red', 'liked');
});

btn2.addEventListener('click', () => {
  setButtonColorAndAddToLocalStorage(btn2, 'red', btn1, 'green', 'disliked');
});

setButtonColorAndAddToLocalStorage = (elm, elmClass, altElm, altElmClass, status) => {
  const elmStatusSet = elm.classList.contains(elmClass);
  elm.classList.toggle(elmClass);
  altElm.classList.remove(altElmClass);
  localStorage.setItem('like-status', elmStatusSet ? '' : status);
};
  
body{
  margin: 40px;
}

button{
  cursor: pointer;
  outline: 0;
  color: #AAA;

}

.btn:focus {
  outline: none;
}

.green{
  color: green;
}

.red{
  color: red;
}
<script src="https://use.fontawesome.com/fe459689b4.js"></script>

  <button class="btn" id="green"><i class="fa fa-thumbs-up fa-lg" aria-hidden="true"></i></button>
  <button class="btn" id="red"><i class="fa fa-thumbs-down fa-lg" aria-hidden="true"></i></button>

how professional developers learn other developer’s code? [closed]

I have a question for anyone especially professional developers who are working as a dev for more than 5 years now.

how do you learn other peoples’ code fast? like, for example, you take someone’s source code from GitHub and you make it run on your machine and while running the code you encounter an error, as a professional dev what are your practices to resolve that in the fastest and most effective way? I want to learn from you I want to be more competitive in this field.

GULP.js: three single tasks works fine in stand alone but leads to unexpected results in gulp.series()

I would like to implement a build and watch job with automated testing via gulp.js.
New for me is the integration of a typescript compiler and the testing of frontend javascript in node.js.
For this I have coded three tasks:

  1. compiling the typescript files into frontend javascript files
  2. compiling the backend javascript test files using jsdom and amd-loader
  3. running the unit tests

If I execute the tasks one by one, everything works as intended.
But if I run all three in gulp.series() after a code change, the next task does not grap the result of the previous task but to the state before the gulp.series call.
A TS change overwrites JS version 1 with JS version 2 in the build task.
The following buildUnitTests task, however, still uses JS version 1.

This is not the case with the watcher, where all changes are recognised by all tasks. But here I have the problem that every change triggers the execution of the unitTestings task and with the termination of the task the Watcher is also terminated:

[hh:mm:ss] The following tasks did not complete: watch, watch
[hh:mm:ss] Did you forget to signal async completion?

Well, the unit tests in the watcher are also a drag on performance and probably belong more in the release task – only there it doesn’t work as desired yet.
What to do so that the tasks are processed one after the other, but the view to the changed files is updated between the tasks?

This is the file structure:

dev
|_ js
|_|_ customElements
|_|_|_ callbackBrookerExtesion.js
|_|
|_|_ looselyConnected
|_|_|_ stringifiedReferenceHandler
|_|_|_|_ require.js
|_|_|_|_ set.js
|_|_|
|_|_|_ callbackBrooker.js
|_|_|_ fileManager.js
|_|_|_ stringifiedReferenceHandler.js

gulp
|_ tasks
|_|_ script.js
|
|_ config.js
|_ index.js

test
|_ config
|_|_ unitTests.json
|
|_ templates
|_|_ exports.js
|_|_ looselyConnected.js
|_|_ prepare.js
|
|_ unittests
|_|_ spec
|_|_|_ looselyConnected
|_|_|_|_ callbackBrooker
|_|_|_|_|_ pull.spec.js
|_|_|_|_|_ push.spec.js
|_|
|_|_ src
|_|_|_ // the unit tests for custom elements are in progress 
|_|_|_ looselyConnected.js

TS
|_ client
|_|_ customElements
|_|_|_ callbackBrookerExtesion.ts
|_|_|_ tsCallbackBrookerExtesionConfig.json
|_|
|_|_ looselyConnected
|_|_|_ stringifiedReferenceHandler
|_|_|_|_ require.ts
|_|_|_|_ set.jts
|_|_|
|_|_|_ callbackBrooker.ts
|_|_|_ fileManager.ts
|_|_|_ looselyConnected.d.ts
|_|_|_ stringifiedReferenceHandler.ts
|_|
|_|_ tsBaseConfig.json
|
|_ tsconfig
|_|_ customElements.json
|_|_ looselyConnected.json

gulpfile.js

gulp/index.js:

const gulp = require("gulp");
const scripts = require("./tasks/scripts");

gulp.task("default",
    gulp.series(
        scripts.build,
        scripts.buildUnitTests,
        scripts.unitTesting
    )
);

gulp.task("build",
    gulp.series(
        scripts.build
    )
);

gulp.task("buildUnitTests",
    gulp.series(
        scripts.buildUnitTests
    )
);

gulp.task("unitTesting",
    gulp.series(
        scripts.unitTesting
    )
);

gulp.task("watch",
    gulp.series(
        scripts.watch
    )
);

gulp/config.js

exports.unitTests = {
    looselyConnected: {
        files: [
            "./test/templates/prepare.js",
            "./test/templates/looselyConnected.js",
            "./dev/js/looselyConnected/callbackBroker.js",
            "./dev/js/looselyConnected/stringifiedReferenceHandler.js",
            "./dev/js/looselyConnected/fileManager.js",
            "./dev/js/looselyConnected/stringifiedReferenceHandler/require.js",
            "./dev/js/looselyConnected/stringifiedReferenceHandler/set.js",
            "./test/templates/exports.js"
        ],
        name: 'looselyConnected.js',
        dest: './test/unittests/src',
        watch: [
            "./TS/client/looselyConnected/**/*",
            "./TS/client/looselyConnected/looselyConnected.d.ts",
            "./TS/client/customElements/**/*"
        ],
        specs: [
            "test/unittests/src/looselyConnected.js",
            "test/unittests/spec/looselyConnected/callbackBroker/push.spec.js",
            "test/unittests/spec/looselyConnected/callbackBroker/pull.spec.js"
        ]
    }
}

gulp/tasks/script.js

const gulp = require("gulp");
const ts = require("gulp-typescript");
const concat = require('gulp-concat');
const Jasmine = require('jasmine');
const jasmine = new Jasmine();
const reporters = require('jasmine-reporters');
const config = require('../config');

const buildScript = cb => {
    let tsProject = ts.createProject("tsconfig/looselyConnected.json");
    tsProject.src().pipe(tsProject()).js.pipe(gulp.dest("./dev/js/looselyConnected"));
    tsProject = ts.createProject("tsconfig/customElements.json");
    tsProject.src().pipe(tsProject()).js.pipe(gulp.dest("./dev/js/customElements"));
    return cb();
};

const unitTesting = cb => {
    jasmine.loadConfigFile('./test/config/unitTests.json');
    jasmine.addReporter(new reporters.JUnitXmlReporter());
    jasmine.execute(config.unitTests.looselyConnected.specs);
    return cb();
}

const buildUnitTests = cb => {
    let tests = config.unitTests;
    for (i in tests) {
        let test = tests[i];
        gulp.src(test.files)
            .pipe(concat(test.name))
            .pipe(gulp.dest(test.dest));
    }
    return cb();
}

const watch = () => {
    let confLC = config.unitTests.looselyConnected;
    gulp.watch(confLC.watch, buildScript);
    gulp.watch(confLC.files, buildUnitTests);
    //gulp.watch(confLC.specs, unitTesting); -> this will quit the watcher after every change
}

module.exports = {
    build: buildScript,
    buildUnitTests: buildUnitTests,
    unitTesting: unitTesting,
    watch: watch,
};

How does a Date object in the front end become a string in the backend?

I am using Datepicker in React with Next.js

        <DatePicker
              selected={ formData.startDate }
              onChange={(date) => handleOnDateChange(date, "startDate") }
              name="startDate"
              showTimeSelect
              timeFormat="HH:mm"
              timeIntervals={15}
              timeCaption="time"
              dateFormat="MMMM d, yyyy h:mm aa"
              autoComplete='off'
              required
              onKeyDown={(e) => {
                e.preventDefault();
             }}
        />

This is my onChange function and my formData hook:

const handleOnDateChange = (date, name) => {
      setFormData({
        ...formData,
        [name]: date
      });
      console.log(date);
      console.log(typeof date)
    }


const [formData, setFormData] = useState({
      "name":"",
      "startDate": "",
      "deadline":""
    });

The console.log in handleOnDateChange method print the date in a string format and “object” respectively. So clearly, the dates in my formData state are clearly Date objects not strings.

However, once I pass this data to the backend through API and print the type of the dates, they becomes string.

I did:

const { startDate, deadline } = req.body;
console.log(typeof startDate);
console.log(typeof deadline);

They both print out “String”
Why does Next.js or Node.js turn the Date object to String?

LocalStorage Clearing when trying to remove a single item

I’m having an issue with localStorage. Whenever the X (fa-square-xmark) icon is clicked to remove one single item from localStorage, all of localStorage is cleared. What’s going on? Any suggestions will be appreciated.

Javascript File

const todoInput = document.querySelector('#todo-item')
const todoList = document.querySelector('.todo-list')
const form = document.querySelector('form')
const todos = []
const savedTodos = JSON.parse(localStorage.getItem('todos')) || []

for (let i = 0; i < savedTodos.length; i++) {
  let newTodo = document.createElement('LI')
  newTodo.innerText = savedTodos[i]
  newTodo.classList.add('todo-item')
  const deleteBtn = document.createElement('I')
  deleteBtn.classList.add('fa-sharp', 'fa-solid', 'fa-square-xmark')
  newTodo.append(deleteBtn)
  todoList.appendChild(newTodo)
}

form.addEventListener('submit', function (e) {
  // e.preventDefault()
  const newTodo = document.createElement('li')
  newTodo.innerText = todoInput.value
  newTodo.classList.add('todo-item')
  const deleteBtn = document.createElement('i')
  deleteBtn.classList.add('fa-sharp', 'fa-solid', 'fa-square-xmark')
  newTodo.append(deleteBtn)
  todoList.appendChild(newTodo)

  todoInput.value = ''

  todos.push(newTodo.innerText)
  console.log(newTodo.innerText)

  localStorage.setItem('todos', JSON.stringify(todos))
})

function removeFromStorage(itemToRemove) {
  for (let i = 0; i < todos.length; i++) {
    if (todos[i] === itemToRemove) {
      todos.splice(i, 1)
    }
  }
  localStorage.setItem('todos', JSON.stringify(todos))
}

todoList.addEventListener('click', function (e) {
  if (e.target.tagName === 'I') {
    e.target.parentElement.remove()
    removeFromStorage(e.target.parentElement.innerText)
  } else if (e.target.tagName === 'LI') {
    e.target.classList.toggle('todo-complete')
  }
  console.log(e.target.innerText)
})

Module not found: Error: Can’t resolve ‘fs’ . Read the details first

I’ve been building a basic weather api with React and TypeScript. I have utilized “npx create-react-app . typescript” for the setup. After building out my application I started it up. Initially I had success contacting the api however as I tried to save the api calls using fs.writeFile in addition to fs.readFile to collect the data I ran into the error that said it cannot resolve ‘fs’.

current ts.config

{
  "compilerOptions": {
    "paths": {
      "crypto": [
        "./node_modules/crypto-browserify"
      ],
    },
    "target": "ES2016",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext",
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "noResolve" : false,
    "types": ["node"],
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "downlevelIteration": true,
  },
  "include": [
    "src"
  ],
  "exclude":["node_modules"]
}

Tried to reset using npm install –save fs.

Deleted node_modules, package.lock.json, removed “fs”: “0.0.1-security”, and reinstalled. This actually seemed to work but then fs wouldn’t be recognized and I reinstalled then got a new error which is progress lol.

Error with getWeather, TypeError: fs__WEBPACK_IMPORTED_MODULE_1___default(…).readFile is not a function
at postWeather (App.tsx:51:1)
at App.tsx:25:1

I have checked stack overflow for existing material such as Module not found: Error: Can’t resolve ‘fs’ in.

The methods there haven’t been successful and I am still searching for alternative ways but if anyone could give some advise I would appreciate it.

Why this bg image is not showing up unless there’s a width, height or padding set?

I end up doing this but it’s a horrendous way to handle responsiveness

<section class="hero">
  <div class="hero__img"></div>
</section>

.hero {
  position: relative;
  background: var(--text-color);
  overflow: hidden;  
}

.hero__img {
background-color: var(--secondary-color);
background-image: url('./public/hero.jpg');
background-size: cover;
background-position: center ;
padding: 10em;
}


@media screen and (min-width: 700px) { 
.hero__img {
  background-color: var(--secondary-color);
  background-image: url('./public/hero.jpg');
  background-size: cover;
  background-position: center ;
  padding: 20em !important;
  }
}



but I can’t see the image unless I set some fixed width, height or padding. => thing that I don’t want bacause responsiveness would be lose.

What am I missing here?

codeSandbox link: https://codesandbox.io/s/cranky-hypatia-ui9m6i?file=/index.html&resolutionWidth=320&resolutionHeight=675

Thanks in advance!

How to disable certain time-slots/dates on datetime-local if those slots are booked on database

The datetime-local element accetps “min” and “max” attributes in order to allow the user to pick from an interval of dates. Is there a way to disable certain time slots or even certain dates which lie between the min and max? Some of the slots are booked on the database, and some dates are holidays.

I tried the “pattern” attribute, setting a regex dynamically for the accepted dates/times, it completely disregards it.

Random API Error in JavaScript after using import and not request

Im ne to JS and im having a fiew problems with an api.
Im trying to make a Website using the Open Ai Api. I importet their nmp pagage with request. That worked fine when executing the file in node but in the browser it did not work. then i read that packages dont work in the browser and i should use import to import it. But now im getting this error:
“GET http://127.0.0.1:5500/openai net::ERR_ABORTED 404 (Not Found)”
Why?

I have tried to Google it but if i would have found something i would not be here

Javascript: Passing arguments to function expressions with embedded function

I’m trying to understand the argument passing mechanism for function expressions that have functions within them, requiring argument passing. I think I know what is happening, but not sure.
I have the following code fragment:

makePassword(password) {
   return function guess(passwordGuess) {
      return (passwordGuess === password);
   }
}

var tryGuess = makePassword("secret");
console.log("Guessing 'nope': " + tryGuess("nope"));
console.log("Guessing 'secret': " + tryGuess("secret"));

tryGuess gets the function reference of makePassword("secret"). I understand that. I’m trying to wrap my head around why tryGuess("nope") passes nope to the inner function guess and not to makePassword? I’m think that, in this example, password is set before the function reference is passed to tryGuess?

If that is so, how would I pass the parameters to password and passwordGuess in tryGuess if I had assigned tryGuess like this:

var tryGuess = makePassword();

There is an assumption about nested functions and parameter passing that I must be missing. So, any help is greatly appreciated!

Thanks,

Russ

Javascript hide search results when searchbar is empty

I created a search function for a shop website. Currently when I run the html, the search results are shown from the begining. The mechanism of wrtiting letters and the results are only those that fit, works perfectly. I am just wondering how I can hide the search results from the begining and only show them when i click into the search box or when i write my first letter into it.

<body style="background-color: #F3F3F3;">
    
<div class="input-wrapper">
            <div class="fa fa-search"></div>
            <input class="suche" type="search" placeholder="Search.." id="search-item" onkeyup="search()" >
    </div>   

    <div class="ProdukteListe" id="ProdukteListe">

        <div class="ProduktName">
            <img src="hoodiefrontlogo.png" alt="">
            <div class= "ProduktDetails">
                <h2>ProduktName</h2>
                <h3>Preis</h3>
            </div>  
        </div>

        <div class="ProduktName">
            <img src="hoodieback.png" alt="">
            <div class=" ProduktDetails ">
                <h2>ProduktName</h2>
                <h3>Preis</h3>
            </div>
        </div>

        <div class="ProduktName">
            <img src="" alt="">
            <div class=" ProduktDetails ">
                <h2>ProduktName2</h2>
                <h3>Preis</h3>
            </div>
        </div>

    </div>

const search = () =>{ const searchbox = document.getElementById("search-item").value.toUpperCase(); 
const storeitems = document.getElementById("ProdukteListe") 
const product = document.querySelectorAll(".ProduktName") 
const pname = storeitems.getElementsByTagName("h2")

for(var i=0; i < pname.length; i++){

    let match = product[i].getElementsByTagName('h2')[0];

    
    if(match){
        let textvalue = match.textContent || match.innerHTML

        if(textvalue.toUpperCase().indexOf(searchbox) > - 1){
            product[i].style.display = "";

        }else{
            product[i].style.display = "none";
        }
    }
}

I tried to write a if into the script but it cant work because the script only executes when the first letter is typed. But the hiding i want has to be the default before that.