How to get refund amount from a given array of objects ? (Kind of complicated..)

Let’s say you were given an array of object data from database and you want to get REFUND result.
So you can give the amount of money when a user requests refund. Before we dive into the problem

- 'DEPOSIT' is the money that user deposit 

- 'POINT' is like an additional extra money/deposit that the business provide when the amount of deposit is over $30($30 deposit => 3 POINT is given,  $50 deposit => 10 POINT is given )

- 'POINT' is not refundable. 

- 'DEDUCTION' is the amount of money that user spent.

- THE RULE IS YOU NEED TO SUBTRACT DEDUCTION FROM DEPOSIT FIRST. AND WHEN DEPOSIT BECOMES 0 or NEGATIVE, WE SUBTRACT DEDUCTION FROM POINT (if exists..)  - you can realize what it means in the example 2

Let’s say I got user 1’s deposit history data by typing query.

const queryResult = [
    {
        date: '2022-10-10',
        amount : 50,
        type: 'DEPOSIT',
    },
    {
        date: '2022-10-10',
        amount : 10,
        type: 'POINT',
    },
    {
        date: '2022-10-10',
        amount : -5,
        type: 'DEDUCTION',
    },
    {
        date: '2022-10-10',
        amount : -5,
        type: 'DEDUCTION',
    },
];

In this case, the result must become

const result = {
    remained_deposit: 40,
    remained_point: 10,
    balance: 50 (remained_deposit + remained_point),
    refundable: 40(remained_deposit)
}


** explain: we have 50 deposit and subtract two deduction from deposit. 
(50 -5 -5 = 40)

So, when the user requests refund, the user must get refund $40 (not $50..)

Let’s see another case.

const data2 = [
    {
        date: '2022-10-10 ',
        amount : 50,
        type: 'DEPOSIT',
    },
    {
        date: '2022-10-10',
        amount : 10,
        type: 'POINT',
    },
    {
        date: '2022-10-10',
        amount : -30,
        type: 'DEDUCTION',
    },
    {
        date: '2022-10-11',
        amount : -25,
        type: 'DEDUCTION',
    },
    {
        date: '2022-10-11',
        amount : 10,
        type: 'DEPOSIT',
    },

];

In this case, the result must become

const result2 = {
    remained_deposit: 10,
    remained_point: 5,
    balance: 15,
    refundable: 10
}

As we did above, we subtract deduction from deposit first.
50(deposit) - 30(deduction) = 20 (deposit)
20(deposit) - 25(deduction) = -5(deposit.. becomes negative)

In this case, we calculate with the POINT.
-5(deposit) + 10 (POINT) = 5(POINT)

if the user requests refund at this point, he/she can get nothing. 
Because remained balance which is POINT(5) is not refundable.

However since the user deposit 10 after the last deduction,
and if he/she requests refund at this point, remained_deposit 10 will be given to the user. 

Let’s see one more confusing-looking case

const data3 = [
    {
        date: '2022-10-10',
        amount : 50,
        type: 'DEPOSIT',
    },
    {
        date: '2022-10-10',
        amount : 10,
        type: 'POINT',
    },
    {
        date: '2022-10-10',
        amount : -40,
        type: 'DEDUCTION',
    },
    {
        date: '2022-10-11',
        amount : 30,
        type: 'DEPOSIT',
    },
    {
        date: '2022-10-11',
        amount : 3,
        type: 'POINT',
    },
    {
        date: '2022-10-11',
        amount : -25,
        type: 'DEDUCTION',
    },

];

In this case, the result must become

const result3 = {
    remained_deposit: 25,
    remained_point: 3,
    balance: 28,
    refundable: 25
}

**explanation

50(deposit) - 40(deduction) = 10(deposit)
10(deposit) - 25(deduction) = -15(deposit)

**even though deposit(30) comes first than deduction(-25), we subtract deduction from the very first deposit first. 

-15(deposit) + 10(point ) = -5(deposit)
-5(deposit) + 30(deposit) = 25(deposit)

What matters is that the first deposit needs to be whole subtracted first and then POINT is next.

When the user request refund in this case, he/she can get $25. 

I hope the examples gave you some clues how you guys must calculate to get the refund.
If you are still confused, please let me know.
And if you guys can understand the problem, I would appreciate if you guys can advise me or give me a better clues, algorithms or solutions.

Thank you.

My JS Code Solution

let totalBalance = 0;
let totalRefund = 0;

// Get total balance 

for(let result of results){
    totalBalance += result.amount
}

console.log(totalBalance);



// Get total refund --it gets correct answer when it's case4(below), but it's wrong in case5

for(let result of results){
    totalRefund += result.amount
    // console.log(totalRefund);

    if(result.type === 'POINT'){
        totalRefund -= result.amount
    }

    if(totalRefund < 0){
            totalRefund = 0;
    }
}

// in case 5, the totalRefund supposed to be 15. But its result is 10...


case4

const results = [
    {
        date: '2022-10-10',
        amount : 50,
        type: 'DEPOSIT',
    },
    {
        date: '2022-10-10',
        amount : 10,
        type: 'POINT',
    },
    {
        date: '2022-10-10',
        amount : -45,
        type: 'DEDUCTION',
    },
    {
        date: '2022-10-10',
        amount : -10,
        type: 'DEDUCTION',
    },
    {
        date: '2022-10-11',
        amount : 30,
        type: 'DEPOSIT',
    },
    {
        date: '2022-10-10',
        amount : 3,
        type: 'POINT',
    },
]


// totalRefund = 30 (correct)

50(deposit) - 45(deduction) = 5(deposit)
5(deposit) - 10(deduction) = -5(deposit)
-5(deposit) + 10(point) = 5(point)

the remain_deposit is 30 and remained point is = 8(5+3)


case5

const results = [
    {
        date: '2022-10-10',
        amount : 50,
        type: 'DEPOSIT',
    },
    {
        date: '2022-10-10',
        amount : 10,
        type: 'POINT',
    },
    {
        date: '2022-10-10',
        amount : -45,
        type: 'DEDUCTION',
    },
    {
        date: '2022-10-10',
        amount : -10,
        type: 'DEDUCTION',
    },
    {
        date: '2022-10-11',
        amount : 30,
        type: 'DEPOSIT',
    },
    {
        date: '2022-10-10',
        amount : 3,
        type: 'POINT',
    },
    {
        date: '2022-10-10',
        amount : -10,
        type: 'DEDUCTION',
    },
    {
        date: '2022-10-10',
        amount : -10,
        type: 'DEDUCTION',
    },
]




// totalRefund = 10 (wrong)

50(deposit) - 45(deduction) = 5(deposit)
5(deposit) - 10(deduction) = -5(deposit)
-5(deposit) + 10(point) = 5(point)
5(point) - 10(deduction) = -5(deduction)
-5(deduction) + 30(deposit) = 25(deposit)
25(deposit) - 10(deduction) = **15(remained_deposit == refund)**


Googling and code by myself. But still get unwanted/unexpected result.
Some case, the code can get the refund correctly, but in some cases it doesn’t.

flow input type – why we need to type double array like type[][]?

I’m using functional programming library and there is pipe-like function called flow. It’s usage looks like this

flow(
  map(item => item.toString())
)([1, 2, 3])

Flow is generic so it takes in this case 2 type arguments. The first one is for input ([1, 2, 3]) and the second one is for what the entire flow returns (in this case it is [‘1’, ‘2’, ‘3’]. Knowing that I’m typing the flow

flow<number[], string[]>...

but then I get error which disappears only when I type it like

flow<number[][], string[]>...

The type definition for flow looks like this

export declare function flow<A extends ReadonlyArray<unknown>, B>(ab: (...a: A) => B): (...a: A) => B

Tell me please why I need to do double array in this case please.

How to pass data from axios response from parent to child in Vue

I’m doing axios call on my view level (parent) and based on the data returned, I do assign it to ref() variable. Then I want to pass this variable as props to my child component.

parent

<template>
    <User_List :users="uniqueNames"/>
</template>


<script setup lang="ts">
import User_List from "@/components/User/User_list.vue"
import { useRoute } from 'vue-router'
import { ref, onMounted } from 'vue'
import { api } from "@/api"
import { UserNameSurname } from "@/interfaces/user"
import { useNotification } from "@kyvg/vue3-notification";
import router from '@/router';

const { notify }  = useNotification()
const route = useRoute()
const uniqueNames = ref<UserNameSurname>([])

const get_unique_users = async (phrase: string) =>{
    await api
    .post("users/find_unique_users", {phrase: phrase})
    .then(response => {
        uniqueNames.value = response.data
    })
    .catch(error => {
        notify({
            title: "Błąd",
            text: error.response.data.detail,
            type: "warn",
            duration: 3000
        });
        router.push("/")
    })
}

onMounted(() => {
    const phrase = route.params.phrase
    get_unique_users(phrase)
})
</script>

child:

<template>
    <div>this is user list {{props.users}}</div>
</template>


<script setup lang="ts">
import { UserNameSurname } from '@/interfaces/user';
const props = defineProps<{users: UserNameSurname}>()
</script>

The problem is that my child component sees it as undefined. It looks like the component mounts before the actual call is made. How can i overcome it?

Bundle simple JS for node with Vite

I’m trying to bundle a simple JS file with Vite for node.

Here’s my vite.config.js:

import { resolve } from 'path'
import { defineConfig } from 'vite'

export default defineConfig({
    build: {
        target: 'node18',
        lib: {
            entry: resolve(__dirname, 'index.js'),
            fileName: 'index',
            formats: ['cjs'],
        },
    },
})

And my index.js:

import axios from 'axios';

async function main() {
    const { status } = await axios.get('https://google.com')
    console.log(status)
}

main()

Then, when I run node dist/index.js after building it with Vite (npx vite build) I get the following exception:

ReferenceError: window is not defined

It seems the target: 'node18' has no effect in the vite.config.js.

I was able to run the same script with webpack, but I’d love to use Vite instead.

Any idea?

Thanks!

remove and add items in shopping cart

when I click the cross icon in shopping cart for first time it works well , but problem occurs when you want to add new items into shopping cart it is the time the cross icon doesn’t work. as far as I know cross icon works exactly before you want to add new items
the html of cart:

shopping cart html part:

 <div class="cart-container col-md-4 col-lg-3">
          <div class="content-container">
                <div class="img-container">
                    <div class="img-box"><img src="images/cart-item-1.png" class="cart-img"  alt=""></div>
                    <div class="price-box">
                        <h3>cart item 01</h3>
                        <p>$15.99/-</p>
                    </div>
                </div>
                <div class="xmark"><i class="fa-solid fa-xmark"></i></div>
            </div>
        </div>

(add to cart button) html part:

  <div class="box">
                    <img src="images/menu-1.png" class="buy-coffee" alt="cappuccino">
                    <h3>tasty and healty</h3>
                    <div class="price">
                        $15.99
                        <span>$20.99</span>
                    </div>
                    <button type="button">add to cart</button>
                </div>

function which remove item from shopping cart:

const crossIcons = document.querySelectorAll('.fa-xmark');
     for(let crossIcon of crossIcons){
            crossIcon.addEventListener("click",function(event){
                this.closest('div.content-container').remove();
            })

function for adding new items to shopping cart:

let addTocarts = document.querySelectorAll('.box button');
 for (let addToCart of addTocarts) {
            addToCart.addEventListener("click", myfunc);
            function myfunc(event) {
                event.preventDefault()
                let boxImg
                let boxSelect = addToCart.closest('div.box');
                boxImg = boxSelect.children[0].getAttribute('src');
                let el = ` <div class="content-container">
                <div class="img-container">
                    <div class="img-box"><img src="${boxImg}" class="cart-img" alt=""></div>
                    <div class="price-box">
                        <h3>cart item 01</h3>
                        <p>$15.99/-</p>
                    </div>
                </div>
                <div class="xmark"><i class="fa-solid fa-xmark" ></i></div>
            </div>`;


                document.querySelector('.cart-container').innerHTML += el;
            }
        }


I just want to add and remove items for cart shop

Fullcalendar nowIndicator

i have a problem when setting up nowIndicator in Fullcalendar.
When i specify: slotDuration: “01:00:00” hte timeline is only updated every hour. But if I define it with slotDuration: “00:30:00” everthing is working, and now line is displaying the actual time. Any ideas how to fix this?

document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');

var calendar = new FullCalendar.Calendar(calendarEl, {
initialView: 'resourceTimeline',
nowIndicator: true,
slotDuration: "01:00:00",
slotLabelInterval: "01:00:00",
snapDuration: "00:01:00",
weekends: false,
duration: { days: 14 }
});

calendar.render();
});

Example of the problem

BR
Leo

I tried to change slotDuraion as described.

ReactJS my Search function not searching on every pages of pagination.What should I do?

My Search function only searching for products on 1 page of pagination.

    // Pagination source code ==============================================================
    const [currentPage, setCurrentPage] = useState(1)
    const [postsPerPage] = useState(6)

    const indexOfLastPost = currentPage * postsPerPage;
    const indexOfFirstPost = indexOfLastPost - postsPerPage;
    const currentPosts = moviedata.slice(indexOfFirstPost, indexOfLastPost)
    const howManyPages = Math.ceil(moviedata.length/postsPerPage)

<div className='movieslist'>
     <div className='list'>
                                    {currentPosts.filter(u=>u.title.toLocaleLowerCase().includes(query)).map((fd, i) => {
    return <Card  img={fd.img} title={fd.title} quality={fd.quality} rating={fd.rating} price={fd.price} duration={fd.duration} year={fd.year} id={fd.id} allproduct={fd} allwishlist={fd} key={i} />
})}

    </div>

    <Pagination pages = {howManyPages} setCurrentPage={setCurrentPage}/>

</div>


I wanted to search the items of all pages, not just one page****but it only searches the items on one page

Display images Horizontally or vertically in a Carousel

What I’m trying to do is to flip the images depending if their Heigh is higher than they Width, or them Width is bigger than their Height.

If The Hight is Higher: Display the image Vertically
If the Width is Higher: Display the image Horizontally.

Here I can show yo how the images are displaying now..

This image has to be Horizontal

enter image description here

This image is Vertically (Ok)

enter image description here

This was what I was trying but with not luck. I know I have to change modal-dialog, but I’m unable to do it.

window.addEventListener('DOMContentLoaded', (event) => {
    let modalImg = document.getElementById('modal-dialog');

    for (var i = 0; i < modalImg.lenght; i++) {
        if (modalImg[i].naturalWidth > modalImg[i].naturalHeight) {
            modalImg[i].style.maxWidth = '50vw';
        } else {
            modalImg[i].style.maxWidth = '30vw';
            modalImg[i].style.maxHeight = '80vh';
        }
    }
});

The gallery is loaded dinamically, all images are brought from the BD.

  <div id="myModal" class="modal" aria-labelledby="exampleModalLabel" aria-hidden="true">
                <div class="modal-dialog" id="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="btn-close" data-bs-dismiss="modal" onclick="CloseModal()" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <div id="[email protected]()" class="carousel carousel-dark slide" data-bs-ride="carousel" data-bs-touch="false" data-bs-interval="false">
                                <div id="Entrega_numeroEntrega" class="carousel-inner" name="carousel-inner">
                                    <!-- IMAGENES -->
                                    @foreach (var pd in Model)
                                    {
                                        if (numeroEntrega != item.getNumeroEntrega())
                                        {
                                            string[] imgUrlSplit = pd.getImagenes().Split("/");
                                            
                                            if (img2 != pd.getImagenes().ToString())
                                            {
                                                <div class="carousel-item" id="carousel-item_@cont2" name="carousel-item">
                                                    <form action="~/Home/DescargarImagenIndividual" class="mb-3 position-relative">
                                                        <button type="submit" id="btnDescargarImagen" class="btn btn-primary" value="@pd.getImagenes()" name="imagenSelec">
                                                            <i class="fa fa-download mx-2"></i>Descargar Imágen
                                                        </button>
                                                    </form>
                                                    <img class="img-responsive imagenModal" id="img01_@cont2" src="@pd.getImagenes()" data-img-mostrar="@cont2" />
                                                </div>
                                            }
                                            cont2++;
                                            img2 = pd.getImagenes();
                                        }
                                    }
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

This is my css:

.modal {
        text-align: center;
        padding-top: 0 !important;
        overflow-y: hidden;
        display: none;
        position: fixed;
        z-index: 1;
        padding-top: 2%;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: hidden;
        background-color: rgba(0,0,0,0.9);
        text-align: center;

        .modal-dialog {
            .modal-content {
                margin: auto;
                display: block;
                width: 100%;
                object-fit: cover;


                .modal-body .carousel .carousel-inner .carousel-item .img-responsive {
                    height: 70vh;
                    width: 100%;
                }
            }

            .carusel {
                .carousel-control-prev {
                    margin-left: 15%;

                    #SpanArrowLeft {
                        font-size: 50px;
                    }
                }

                .carousel-control-next {
                    margin-right: 15%;

                    #SpanArrowRight {
                        font-size: 50px;
                    }
                }
            }
        }

Vue 3 test for text input format not working

I have the following that does not work. No matter what entry I put into the fieldName input valid is always true. I am aiming for only alphanumeric plus _ or – to be allowed:

valid = true;
const pattern = /^([a-zA-Z0-9 _-]+)$/;
if (pattern.test(this.fieldName)) {
  valid = false;
  this.message = "Invalid format";
}

Why is this not working?

Why is the keyword ‘default’ necessary when exporting a component withStyles

When I implement a simple React component with Mui’s withStyles HOC, I have to use the keyword “default” when exporting the component. Why can’t I use the HOC in the return statement within the functional component?

Is there something about Js or ReactJs that I’m missing?

Since I am forced to export this component as default, I lose the possibility to use the named import functionality, without using another import/export layer in between.

Below is the current working code:

// Card.js
import React from "react";
import {
  Card,
  withStyles
} from "@material-ui/core";

const styles = theme => ({
  card: {
    margin: theme.spacing(2)
  }
});

function CustomCard(props) {
  const {classes} = props;
  return (
    <Card className={classes.card}>
      Export me without being the default component.
    </Card>
  );
}

export default withStyles(styles)(MediaCard);

// Elsewhere.js
import CustomCard from "Card";
...

But i’d rather write something like this:

// Cards.js
import React from "react";
import {
  Card,
  withStyles
} from "@material-ui/core";

const styles = theme => ({
  card: {
    margin: theme.spacing(2)
  },
  anotherCard: {
    margin: theme.spacing(4)
  }
});

export function CustomCard(props) {
  const {classes} = props;
  return withStyles(styles)(
    <Card className={classes.card}>
      Jeah. I'm not the default component.
    </Card>
  );
}

export function AnotherCard(props) {
  const {classes} = props;
  return withStyles(styles)(
    <Card className={classes.anotherCard}>
      Jeah. I'm not the default component either.
    </Card>
  );
}

// Elsewhere.js
import { CustomCard, AnotherCard } from "Cards";
...

Javascript: How to conditionally added the value of a variable ( conditional) in a string interpolation? [duplicate]

I have a variable which exist conditionally. I want to use its value depending on the value if it exists or not. How to add in text conditionally

 // someStatus = 'SUCCEEDED' or can be failed too 
let x = 'unknown state'
let y = 'unknown stage'

if (someStatus === 'SUCCEEDED') {
    x = 'Succeeded'
} else {
    x = 'Failed'
    y = data.additionalAttributes.failedStage
}

const msgFormat = {
    "channel": "xyzzy",
    "text": `${name} ${x} ${y} ${account} ${link}`. // if y does not exist it is assigned undefined
}

Store data from javascript array as csv on local computer [duplicate]

I am new to js and I am stuck with a problem. I have been searching a lot but couldn’t find a good answer for my problem.

I need a csv file downloaded to my local computer. I just code in a js file in VS code and then run node to execute. So, in my js file I have an array with two arrays inside, so:

let arrayOne = ["tim", "tom", "paul"];
let arrayTwo = ["blue", "green", "yellow"];
let finalArray = [arrayOne, arrayTwo];

Now, I want to store finalArray in a csv file that would look like

tim    blue
tom    green
paul   yellow

I found some suggestions which involve html etc but I really just want to have it in my download or documents folder on my computer. Thanks for any help!!