Selecting the appropriate color code based on a specified value

If the value of zoneTempDiff1 falls below 1.5, consider using temp: 1 color. If it exceeds 1.5, opt for temp: 2 color. The same logic applies to all different values such as -1, -2, 0, 1, 2, 3, 4, or 5, each corresponding to a specific color code. In cases where the value is greater than +6 or less than -6, use the respective colors for temp:+6 or temp:-6.


floor.entities.forEach(elementId => {
  let objTemp: any = {};
  objTemp.currentTemp = 68;
  objTemp.desiredTempHeating = 70.5;

  let zoneTempDiff1 = objTemp.currentTemp - objTemp.desiredTempHeating;
  let tempColor1 = this.temperatureColors.filter(color => zoneTempDiff1 < (color.temp + 1) && zoneTempDiff1 > (color.temp - 1));
  objTemp.tempColorToInsert = tempColor1.color;

  floor.droppeditem.push(objTemp);
});

temperatureColors: any = [
   { color: '#50B3D3', temp: -6 },
   { color: '#25CBE4', temp: -4 },
   { color: '#25CBE4', temp: -3 },
   { color: '#7EE2DD', temp: -2 },
   { color: '#7EE2DD', temp: -1 },
   { color: '#89DE6F', temp: 0 },
   { color: '#89DE6F', temp: 1 },
   { color: '#D2E143', temp: 2 },
   { color: '#D2E143', temp: 3 },
   { color: '#FDCB31', temp: 4 },
   { color: '#FDCB31', temp: 5 },
   { color: '#F59A4A', temp: 6 }
];

Answer №1

Could you clarify your question?

The function is invoked like this:

getColor(68, 78, colors);

We provide the current temperature, desired temperature, and an array of color objects as arguments.

const getColor = (current, desired, colors) => {

We calculate the temperature difference and round it to the nearest whole number.

const diff = Math.round(current - desired);

We determine the index of the last element in the colors array.

const last = colors.length - 1;

Next, we check if the difference is less than or equal to the temp property specified in the first color object of our array. If so, we return that color and finish.

if (diff <= colors[0].temp) return colors[0].color;

A similar comparison here but now we are looking for if the difference is greater than or equal to the temp in the last color object in the array.

if (diff >= colors[last].temp) return colors[last].color;

If neither condition is met, we iterate through the array and use find to locate the object with a temp value that matches the diff.

return colors.find(color => diff === color.temp).color;

Is this clear enough?

// Code snippet ***

Let's introduce a new function.

This time around, we directly compute the difference and utilize Array.reduce to pinpoint the color object from the array. While it's concise (almost like a one-liner), it may require more effort to understand. However, it offers greater flexibility since every temperature variation doesn't need to be included in the input array.

 // Another code snippet ***

Understanding Reduce

The reduce method operates on an array by applying a callback function to each element and eventually producing a single value.

For instance, given an array [1, 2, 3], we can reduce it to the sum of all elements. The magic happens within the reduce callback function.

The callback receives four parameters: accumulator, current element, current element index, and the array itself.

...

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

What sets apart the $ and $() functions in jQuery?

After reviewing the jQuery API, I noticed that $() represents a collection of matched elements. However, I am curious about the significance of $. An example from the imagesLoaded library is provided below. if ( $ ) { $.fn.imagesLoaded = function( opt ...

Set the initial index position to 0 for the property type

Looking to define a type for the following scenario: categories.categories[0].category.map((c: CategoryObject) => ({ category: c.name[0]._text[0], Can we specify index 0 in the type declaration? For example: type CategoryObject = { name[0]: { _te ...

Exploring CSS animations by utilizing the transform and color properties

I am currently working on a project that involves animating text (specifically "happy birthday to you") and a heart. The idea is for the heart to drop and hit each word one by one, turning them yellow upon impact. Once the last word is hit, the text shou ...

What is the method for dynamically assigning a name to ngModel?

I have the following code snippet: vmarray[]={'Code','Name','Place','City'} export class VMDetail { lstrData1:string; lstrData2:string; lstrData3:string; lstrData4:string; lstrData5:string; ...

Multiple instances of jQuery file being loaded repeatedly

Having an issue with the jQuery file (jquery-1.11.3.min.js) loading multiple times. It seems that other jQuery files in the index.html page might be causing this. Any advice on how to resolve this would be greatly appreciated. <script type="text/javasc ...

Is there a way to navigate to the next or previous image in a lightbox by using ev.target.nextElementSibling or ev.target.prevElementSibling?

I am new to the world of web development Currently, I'm facing an issue with my lightbox feature. I want to navigate between images by using ev.target.nextElementSibling and ev.target.prevElementSibling when clicking on the next/previous arrow.png ic ...

"MongoDB's .find function functions properly in the shell environment, but encounters issues when

As a newcomer to Node Express Mongo, I decided to venture into creating my own website after following tutorials. The page I'm working on is a login page. While other people's code has worked for me, my attempt didn't go as planned. Even con ...

Confirming the information in two sections of a form

Could someone assist me with validating my form? Specifically, I need help ensuring that the house number field only accepts two numbers and the postcode field only allows 5 characters. I have implemented a pattern attribute for validation and I am curiou ...

Record the variable as star symbols in the VSTS Extension

I am working on a VSTS extension using Typescript and utilizing the vsts-task-lib Currently, I am encountering an issue with the execSync function, which displays the command being executed. However, I need to hide a token obtained from a service by displ ...

You are unable to apply 'use client' on a layout element in Next.js

While attempting to retrieve the current page from the layout.txt file, I encountered errors after adding 'use client' at the top of the page: Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data parseMod ...

Problem Alert: Click Event Not Functioning on Generated Links

Take a look at these two code snippets. Despite other jQuery functions in the same JS file working fine on the UL element, nothing seems to be happening with these. Is there something obvious that I am missing? <ul id="activityPaganation" class="paga ...

Create a list that starts with a header determined by an object's attribute within an array

Currently in Vue, I am attempting to create a list based on a specific property within an object. The array being retrieved from the vuex store is structured as follows: const array = [ { name: "British title string" nationality: "British" }, { ...

Issue with TableHead not functioning properly when sorting is requested

I'm currently facing an issue with my table that has clickable row headers for sorting functionality using the onRequestSort function. Unfortunately, it seems like this feature is not working as expected. I have implemented the sorting logic using rea ...

Experiencing difficulties with certain npm CLI modules when using it as a task runner and build tool

After coming across an article about using npm as a build tool, I decided to give it a try for my tasks. However, I am facing an issue that has me stuck. Whenever I run a global command-line tool like JSLINT, JSHINT, or ESLINT using npm, the console always ...

Adjust the dimensions of the canvas without disrupting the existing artwork

I am currently working on a pixel art application where I am facing an issue with saving images from the canvas. The saved image appears small and pixelated when I try to resize it. I would like to resize the image to larger dimensions, but I am unsure of ...

"Spin an image using Javascript when it is shown on the

I've got a script that shows an image when we are attacked by a monster. The image is initially set to display="none", but switches to display="" when a monster appears. What I'm looking to do is make the image rotate 360° when it changes from ...

Apigee Usergrid: Absence of bulk delete feature

Currently, I am utilizing usergrid for storage in a customer project. The data is divided into two collections: carShowrooms and cars. Thus far, everything has been running smoothly. However, there arises a situation where I need to refresh the masterdata ...

What is the significance of the "component" prop within MUI components?

I am a beginner in React and HTML. Currently, I am using MUI and React to create my own website. I am currently attempting to add an "Upload button" that will allow me to select an image file when clicked. Below is the official implementation: <Button ...

If I exclusively utilize TypeScript with Node, is it possible to transpile it to ES6?

I am developing a new Node-based App where browser-compatibility is not a concern as it will only run on a Node-server. The code-base I am working with is in TypeScript. Within my tsconfig.json, I have set the following options for the compiler: { "inc ...

Discovering the wonders of Angular: fetching and utilizing data

Recently delved into the world of Angular and I've hit a roadblock. I'm struggling to grasp how Angular accesses data in the DOM. In all the examples I've come across, data is initialized within a controller: phonecatApp.controller(' ...