Populating datasets with relative indexing

I am working on a code where I need to fill the datasets with the property isProjected set to 1. There are 3 datasets - lower estimate, projected, and upper estimate. The goal is to fill the Lower Estimate and Upper Estimate with a background color of rgba(252, 0, 47, 0.2) while leaving the Projected dataset unfilled (fill: false). However, the current code fills all 3 datasets. "Upper Estimate" should be filled with -1, "Lower Estimate" with +1, and "Projected" left unfilled.

View image description here

This is what I have attempted so far. Here is the buildChart config code:

buildChartConfig(data: DataConfig): ChartConfiguration {
    
    const newData: ChartData = { ... }
    ...
 

This is the dataset defaults code:

export const datasetDefaults = (value, index, colorType) => { 
    ...
 

And this is the code snippet that assigns the isProjected property a value of 1:

[...datasets, { ... }]

Answer №1

Here is the updated code snippet:

createChartConfig(data: DataConfiguration): ChartSetup {
  const newData: ChartData = {
    ...data,
    datasets: data.datasets.map((val, index, arr) => {
      const checkProjection = (dataset: DatasetConfiguration) => dataset.isProjected;

      const config = {
        ...defaultDataset(val, index, this.colorType),
        ...val,
        ...(checkProjection(val) && {
          fill: checkProjection(val) ? '0' : '-1', 
          backgroundColor: checkProjection(val)
            ? 'rgba(252, 0, 47, 0)'
            : 'rgba(252, 0, 47, 0.2)',
        }),
      };

      return config;
    }),
  } as ChartData;
}

Answer №2

composeChartConfig(details: DataConfig): ChartConfiguration {
console.log('Data Being Analyzed:', details);

const freshData: ChartData = {
  ...details,
  datasets: details.datasets.map((value, i, array) => {
    const flagProjected = (dataPoint: DatasetConfig) => dataPoint.isProjected;
    console.log('Is Projected:', flagProjected(value));
    console.log('Position in Array:', i);
    console.log('First Projected Index:', array.findIndex(flagProjected));

    const outcome: CustomChartDataset = {
      ...setDefaultsForDataset(value, i, this.colorType),
      ...value,
      ...(flagProjected(value) &&
        i === array.findIndex(flagProjected) && {
          fill: 'origin',
          backgroundColor: 'rgba(252, 0, 47, 0.25)',
          borderColor: 'rgba(252, 0, 47, 0.25)',
          isProjected: true,
        }),
      ...(flagProjected(value) &&
        i === array.slice().reverse().findIndex(flagProjected) && {
          fill: false,
          backgroundColor: '#FC002F',
          borderColor: '#FC002F',
          isProjected: true,
        }),
    };

    console.log('Final Result:', outcome);
    return outcome;
  }),
} as ChartData;

Answer №3

After implementing a new flag that calculates specific projections, the chart configuration now accurately displays the desired outcome.` buildChartConfig(data: DataConfiguration): ChartSetup { console.log('Current Data:', data);

const updatedData: ChartData = {
  ...data,
  datasets: data.datasets.map((dataset, index, array) => {
    const isProjectedFlag = (config: DatasetConfiguration) => config.isProjected;
   
    const isFirstFlagged = index === array.findIndex(isProjectedFlag);
    const isLastFlagged =
      index ===
      array.length - 1 - array.slice().reverse().findIndex(isProjectedFlag);

    const customDisplay: CustomChartDataset = {
      ...adjustDefaults(dataset, index, this.colorType), //modified
      ...dataset,
      ...(isProjectedFlag(dataset) &&
        (isFirstFlagged || isLastFlagged) && {
          fill: 'origin',
          backgroundColor: 'rgba(252, 0, 47, 0.25)',
          borderColor: 'rgba(252, 0, 47, 0.25)',
          isProjected: true,
        }),
      ...(isProjectedFlag(dataset) && //prediction
        !(isFirstFlagged || isLastFlagged) && {
          fill: false,
          backgroundColor: '#FC002F',
          borderColor: '#FC002F',
          isProjected: true,
        }),
    };
    console.log('Updated Result:', customDisplay);
    return customDisplay;
  }),
} as ChartData;`

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 is the most effective way to determine the data type of a value associated with a key in an interface?

In my TypeScript interface, I have defined the following structure: MyInterface { 'key1': number | string; 'key2': string; 'key3': SomeOtherInterface; } I am looking to create a new type that utilizes the properties of ...

Tips for troubleshooting TypeScript integration tests within Pycharm

Currently, I have been utilizing PyCharm to code in typescript. To run tests in the integration directory, I execute npm run test:integration. However, I am now looking to debug the tests. The directory structure looks like this: my_project /src /tests ...

ESLint and Prettier are butting heads when trying to run their commands consecutively

My package.json file includes two commands: "format": "prettier --write \"{src,{tests,mocks}}/**/*.{js,ts,vue}\"", "lint": "eslint . -c .eslintrc.js --rulesdir eslint-internal-rules/ --ext .ts,.js,.vue ...

Tips for eliminating white frames or borders on the Mapbox canvas map

In my current project using Angular 10, I have integrated Mapbox to display path routes. Following the standard Angular practice of splitting components, I separated the map rendering component and called it into the main map component. However, I encounte ...

Discovering the title of a page in layout using Nextjs 13

How do I extract the title stored in the metadata object within the layout.tsx file? page.tsx: import { Metadata } from 'next'; export const metadata: Metadata = { title: 'Next.js', }; export default function Page() { return &a ...

Set certain properties within the nested object to be optional

Within a TypeScript project, there exists a type definition that looks like this: type Bar = { x: string; y: string; data: { z: string; w: string; }; }; This type is imported and widely used throughout the project, making it impossible for ...

Divide a list Observable into two parts

In my code, I have an Observable called 'allItems$' which fetches an array of Items. The Items[] array looks something like this: [false, false, true, false] My goal is to split the 'allItems$' Observable into two separate Observables ...

Only pass props to `Image` if they have a defined value

As I construct a blog platform using MDX and NextJS, I am creating a custom image component that utilizes the Next <Image> component. However, I've encountered a minor issue for which I have been unable to find a solution. The main question is: ...

The system is unable to locate a compatible object with the identifier '[object Object]' of type 'object'. NgFor is limited to binding with iterables like Arrays, not JSON data

Working with JSON data data:[ { assets:[[tool_order_id: "38",order_status_id: "10"]], order_info:[id: "1", order_type: "6",check: "1", current_Stage_id: "29"] }, { assets:[tool_order_ ...

Encountering unspecified values when subscribing to a BehaviorSubject and receiving it as an Observable

My goal is to display the name of the currently logged-in user in the header of my application. However, I encountered an issue where upon refreshing the page, the value would be lost due to SPA behavior (even though the data is stored in local storage). T ...

Exploring Angular: How to Access HTTP Headers and Form Data from POST Request

I am currently working with an authentication system that operates as follows: Users are directed to a third-party login page Users input their credentials The website then redirects the user back to my site, including an auth token in a POST request. Is ...

Solving the error message "Cannot find module '@angular/router/src/utils/collection' or its corresponding type declaration"

How do I troubleshoot this Error: src/app/metronic/orderByLocation/locationsByOneOrder/locationsByOneOrder.component.ts:7:25 - error TS2307: Cannot find module '@angular/router/src/utils/collection' or its corresponding type declarations.m 7 imp ...

Creating a randomly generated array within a Reactjs application

Every time a user clicks a button in reactjs, I want to create a random array of a specific size. The code for generating the array looks like this: const generateArray = (arraySize: number): number[] => { return [...Array(arraySize)].map(() => ~~( ...

What is the best way to split a single object into two separate objects based on a specific value within the object using lodash?

Imagine a scenario with an object containing two channels in Dutch (NL) language and one channel in English (EN) language: [ { "name": "De Redactie", "channels": [ { "name": "headlines", "pub ...

Modify the height of React Cards without implementing collapse functionality

Currently, I am in the process of developing a web interface that displays various processes and services. The information is presented in React cards that support expand/collapse functionality. However, I am facing an issue where expanding one card affect ...

I am facing an issue with the Angular2 Modal Form where it only displays the data but does

Hey there, I recently started diving into Angular and I'm loving the learning process. Currently, I've managed to successfully load a form into my Modal when clicking on "viewDetails". However, as soon as I modify the Form from <form ngNoFo ...

What is the best way to inform TypeScript when my Type has been altered or narrowed down?

In my application, I have a class that contains the API code: export class Api { ... static requestData = async ( abortController: React.MutableRefObject<AbortController | null> ) => { // If previous request exists, cancel it if ...

Set up karma-firefox-launcher for Angular version 15

In Angular 15, the number of configuration files has been reduced compared to previous versions. For example, the karma.conf.js file has been eliminated. In Angular 14, I used to set up karma.conf.js to include the require('karma-firefox-launcher&apos ...

Issue: Module "mongodb" could not be found when using webpack and typescript

I am encountering an issue while trying to use mongoose with webpack. Even though I have installed it as a dependency, when attempting to utilize the mongoose object and execute commands, it gives me an error stating that it cannot find the "." Module. Thi ...

Module 'angular2/angular2' not found

Currently, I am working on a node application with angular2 and gulp. One of the components I have created is login.ts: import {Component, View} from 'angular2/angular2'; import {FormBuilder, formDirectives } from 'angular2/forms'; @C ...