Best JavaScript code snippet using wpt
store.js
Source:store.js
1/*2 * @copyright Copyright (c) 2020 Florian Steffens3 *4 * @author Florian Steffens <flost-online@mailbox.org>5 * @author Marcus Nitzschke <mail@kendix.org>6 *7 * @license GNU AGPL version 3 or any later version8 *9 * This program is free software: you can redistribute it and/or modify10 * it under the terms of the GNU Affero General Public License as11 * published by the Free Software Foundation, either version 3 of the12 * License, or (at your option) any later version.13 *14 * This program is distributed in the hope that it will be useful,15 * but WITHOUT ANY WARRANTY; without even the implied warranty of16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the17 * GNU Affero General Public License for more details.18 *19 * You should have received a copy of the GNU Affero General Public License20 * along with this program. If not, see <http://www.gnu.org/licenses/>.21 *22 */23import Vue from 'vue'24import Vuex from 'vuex'25import { WeightApi } from './WeightApi'26import { PersonApi } from './PersonApi'27import { MeasurementApi } from './MeasurementApi'28import { FeelingApi } from './FeelingApi'29import { SleepApi } from './SleepApi'30import { SmokingApi } from './SmokingApi'31import { ActivitiesApi } from './ActivitiesApi'32import { MedicationApi } from './MedicationApi'33import { showSuccess } from '@nextcloud/dialogs'34Vue.use(Vuex)35const weightApiClient = new WeightApi()36const personApiClient = new PersonApi()37const measurementApiClient = new MeasurementApi()38const feelingApiClient = new FeelingApi()39const sleepApiClient = new SleepApi()40const smokingApiClient = new SmokingApi()41const activitiesApiClient = new ActivitiesApi()42const medicationApiClient = new MedicationApi()43// eslint-disable-next-line import/no-named-as-default-member44export default new Vuex.Store({45 state: {46 initialLoading: true,47 loading: false,48 app: 'health',49 activePersonId: null,50 activeModule: 'person', // person51 showSidebar: false,52 persons: null,53 rWeightDatasets: [],54 measurementDatasets: [],55 feelingDatasets: [],56 sleepDatasets: [],57 smokingDatasets: [],58 activitiesDatasets: [],59 medicationDatasets: [],60 medicationPlanDatasets: [],61 selectedMedicationPlan: null,62 sharees: [],63 },64 getters: {65 person: state => (state.persons && state.persons[state.activePersonId]) ? state.persons[state.activePersonId] : null,66 personsLength: state => state.persons ? state.persons.length : 0,67 canEdit: state => {68 return state.activePersonId !== null && state.persons[state.activePersonId] ? state.persons[state.activePersonId].permissions.PERMISSION_EDIT : false69 },70 canManage: state => {71 return state.activePersonId !== null && state.persons[state.activePersonId] ? state.persons[state.activePersonId].permissions.PERMISSION_MANAGE : false72 },73 },74 mutations: {75 persons(state, persons) {76 state.persons = persons.slice()77 },78 personsAdd(state, person) {79 state.persons.push(person)80 },81 personsDelete(state, person) {82 const existingIndex = state.persons.findIndex(set => set.id === person.id)83 if (existingIndex !== -1) {84 state.persons.splice(existingIndex, 1)85 }86 },87 personUpdate(state, data) {88 const p = state.persons89 const existingIndex = p.findIndex(set => set.id === data.id)90 if (existingIndex !== -1) {91 p.splice(existingIndex, 1)92 p.push(data)93 }94 state.persons = p95 },96 activePersonId(state, id) {97 state.activePersonId = id98 },99 activeModule(state, module) {100 state.activeModule = module101 },102 personData(state, data) {103 state.personData = data104 },105 // directly called (without actions)106 addAclToCurrentPerson(state, createdAcl) {107 state.persons[state.activePersonId].acl.push(createdAcl)108 },109 updateAclFromCurrentPerson(state, acl) {110 const currentPerson = this.state.persons[this.state.activePersonId]111 const aclIndex = currentPerson.acl.findIndex((entry) => acl.id === entry.id)112 Vue.set(this.state.persons[this.state.activePersonId].acl, aclIndex, acl)113 },114 deleteAclFromCurrentPerson(state, acl) {115 const currentPerson = this.state.persons[this.state.activePersonId]116 const removeIndex = currentPerson.acl.findIndex((entry) => acl.id === entry.id)117 if (removeIndex > -1) {118 Vue.delete(currentPerson.acl, removeIndex)119 }120 },121 showSidebar(state, bool) {122 state.showSidebar = bool123 },124 rWeightDatasets(state, data) {125 state.rWeightDatasets = data126 },127 rWeightDatasetsAppend(state, data) {128 state.rWeightDatasets.push(data)129 },130 rWeightDatasetsDelete(state, data) {131 const existingIndex = state.rWeightDatasets.findIndex(set => set.id === data.id)132 if (existingIndex !== -1) {133 state.rWeightDatasets.splice(existingIndex, 1)134 }135 },136 rWeightDatasetsUpdate(state, data) {137 const datasets = state.rWeightDatasets138 const existingIndex = datasets.findIndex(set => set.id === data.id)139 if (existingIndex !== -1) {140 datasets.splice(existingIndex, 1)141 datasets.push(data)142 }143 state.rWeightDatasets = datasets144 },145 loading(state, status) {146 state.loading = !!status147 },148 initialLoading(state, status) {149 state.initialLoading = !!status150 },151 // -------------152 measurementDatasets(state, data) {153 state.measurementDatasets = data154 },155 measurementDatasetsAppend(state, data) {156 state.measurementDatasets.push(data)157 },158 measurementDatasetsDelete(state, data) {159 const existingIndex = state.measurementDatasets.findIndex(set => set.id === data.id)160 if (existingIndex !== -1) {161 state.measurementDatasets.splice(existingIndex, 1)162 }163 },164 measurementDatasetsUpdate(state, data) {165 const datasets = state.measurementDatasets166 const existingIndex = datasets.findIndex(set => set.id === data.id)167 if (existingIndex !== -1) {168 datasets.splice(existingIndex, 1)169 datasets.push(data)170 }171 state.measurementDatasets = datasets172 },173 // -------------174 feelingDatasets(state, data) {175 state.feelingDatasets = data176 },177 feelingDatasetsAppend(state, data) {178 state.feelingDatasets.push(data)179 },180 feelingDatasetsDelete(state, data) {181 const existingIndex = state.feelingDatasets.findIndex(set => set.id === data.id)182 if (existingIndex !== -1) {183 state.feelingDatasets.splice(existingIndex, 1)184 }185 },186 feelingDatasetsUpdate(state, data) {187 const datasets = state.feelingDatasets188 const existingIndex = datasets.findIndex(set => set.id === data.id)189 if (existingIndex !== -1) {190 datasets.splice(existingIndex, 1)191 datasets.push(data)192 }193 state.feelingDatasets = datasets194 },195 // -------------196 sleepDatasets(state, data) {197 state.sleepDatasets = data198 },199 sleepDatasetsAppend(state, data) {200 state.sleepDatasets.push(data)201 },202 sleepDatasetsDelete(state, data) {203 const existingIndex = state.sleepDatasets.findIndex(set => set.id === data.id)204 if (existingIndex !== -1) {205 state.sleepDatasets.splice(existingIndex, 1)206 }207 },208 sleepDatasetsUpdate(state, data) {209 const datasets = state.sleepDatasets210 const existingIndex = datasets.findIndex(set => set.id === data.id)211 if (existingIndex !== -1) {212 datasets.splice(existingIndex, 1)213 datasets.push(data)214 }215 state.sleepDatasets = datasets216 },217 // -------------218 smokingDatasets(state, data) {219 state.smokingDatasets = data220 },221 smokingDatasetsAppend(state, data) {222 state.smokingDatasets.push(data)223 },224 smokingDatasetsDelete(state, data) {225 const existingIndex = state.smokingDatasets.findIndex(set => set.id === data.id)226 if (existingIndex !== -1) {227 state.smokingDatasets.splice(existingIndex, 1)228 }229 },230 smokingDatasetsUpdate(state, data) {231 const datasets = state.smokingDatasets232 const existingIndex = datasets.findIndex(set => set.id === data.id)233 if (existingIndex !== -1) {234 datasets.splice(existingIndex, 1)235 datasets.push(data)236 }237 state.smokingDatasets = datasets238 },239 // -------------240 activitiesDatasets(state, data) {241 state.activitiesDatasets = data242 },243 activitiesDatasetsAppend(state, data) {244 state.activitiesDatasets.push(data)245 },246 activitiesDatasetsDelete(state, data) {247 const existingIndex = state.activitiesDatasets.findIndex(set => set.id === data.id)248 if (existingIndex !== -1) {249 state.activitiesDatasets.splice(existingIndex, 1)250 }251 },252 activitiesDatasetsUpdate(state, data) {253 const datasets = state.activitiesDatasets254 const existingIndex = datasets.findIndex(set => set.id === data.id)255 if (existingIndex !== -1) {256 datasets.splice(existingIndex, 1)257 datasets.push(data)258 }259 state.activitiesDatasets = datasets260 },261 // -------------262 medicationDatasets(state, data) {263 state.medicationDatasets = data264 },265 medicationDatasetsAppend(state, data) {266 state.medicationDatasets.push(data)267 },268 medicationDatasetsDelete(state, data) {269 const existingIndex = state.medicationDatasets.findIndex(set => set.id === data.id)270 if (existingIndex !== -1) {271 state.medicationDatasets.splice(existingIndex, 1)272 }273 },274 medicationDatasetsUpdate(state, data) {275 const datasets = state.medicationDatasets276 const existingIndex = datasets.findIndex(set => set.id === data.id)277 if (existingIndex !== -1) {278 datasets.splice(existingIndex, 1)279 datasets.push(data)280 }281 state.medicationDatasets = datasets282 },283 // -------------284 medicationPlanDatasets(state, data) {285 state.medicationPlanDatasets = data286 },287 medicationPlanDatasetsAppend(state, data) {288 state.medicationPlanDatasets.push(data)289 state.selectedMedicationPlan = data.id290 },291 medicationPlanDatasetsDelete(state, data) {292 const existingIndex = state.medicationPlanDatasets.findIndex(set => set.id === data.id)293 if (existingIndex !== -1) {294 state.medicationPlanDatasets.splice(existingIndex, 1)295 }296 },297 medicationPlanDatasetsUpdate(state, data) {298 const datasets = state.medicationPlanDatasets299 const existingIndex = datasets.findIndex(set => set.id === data.id)300 if (existingIndex !== -1) {301 datasets.splice(existingIndex, 1)302 datasets.push(data)303 }304 state.medicationPlanDatasets = datasets305 },306 medicationPlanSelected(state, planId) {307 state.selectedMedicationPlan = planId308 },309 // ----------------310 setSharees(state, shareesUsersAndGroups) {311 Vue.set(state, 'sharees', shareesUsersAndGroups.exact.users)312 state.sharees.push(...shareesUsersAndGroups.exact.groups)313 state.sharees.push(...shareesUsersAndGroups.users)314 state.sharees.push(...shareesUsersAndGroups.groups)315 },316 },317 actions: {318 async loadPersons({ dispatch, state, commit }) {319 commit('initialLoading', true)320 const persons = await personApiClient.load()321 if (persons && persons.length > 0) {322 commit('persons', persons)323 if (state.activePersonId === null) {324 dispatch('setActivePerson', 0)325 }326 dispatch('loadModuleContentForPerson')327 }328 commit('initialLoading', false)329 },330 async loadSharees({ commit }, query) {331 const params = new URLSearchParams()332 if (typeof query === 'undefined') {333 return334 }335 params.append('search', query)336 params.append('format', 'json')337 params.append('perPage', 20)338 params.append('itemType', [0, 1])339 params.append('lookup', false)340 const response = await personApiClient.searchSharees(params)341 commit('setSharees', response.data.ocs.data)342 },343 async addAclToCurrentPerson({ dispatch, commit }, newAcl) {344 newAcl.personId = this.state.persons[this.state.activePersonId].id345 const result = await personApiClient.addAcl(newAcl)346 commit('addAclToCurrentPerson', result)347 },348 async updateAclFromCurrentPerson({ commit }, acl) {349 acl.personId = this.state.persons[this.state.activePersonId].id350 const result = await personApiClient.updateAcl(acl)351 commit('updateAclFromCurrentPerson', result)352 },353 async deleteAclFromCurrentPerson({ dispatch, commit }, acl) {354 acl.personId = this.state.persons[this.state.activePersonId].id355 const result = await personApiClient.deleteAcl(acl)356 commit('deleteAclFromCurrentPerson', result)357 },358 setActivePerson({ dispatch, commit }, id) {359 commit('activePersonId', id)360 // commit('setModuleSettings', {})361 dispatch('loadModuleContentForPerson')362 },363 setActiveModule({ dispatch, commit }, module) {364 commit('activeModule', module)365 dispatch('loadModuleContentForPerson')366 },367 async loadModuleContentForPerson({ getters, commit, dispatch, state }) {368 // this ist called if the active person or module changed369 // it should load all data, that is necessary for the active module370 commit('loading', true)371 // await dispatch('weightDatasetsLoadByPerson', [])372 // await dispatch('measurementDatasetsLoadByPerson', [])373 // await dispatch('feelingDatasetsLoadByPerson', [])374 commit('rWeightDatasets', [])375 commit('feelingDatasets', [])376 commit('sleepDatasets', [])377 commit('measurementDatasets', [])378 commit('smokingDatasets', [])379 commit('activitiesDatasets', [])380 commit('medicationDatasets', [])381 if (state.activeModule === 'weight') {382 await dispatch('weightDatasetsLoadByPerson', getters.person.id)383 } else if (state.activeModule === 'measurement') {384 await dispatch('measurementDatasetsLoadByPerson', getters.person.id)385 } else if (state.activeModule === 'feeling') {386 await dispatch('feelingDatasetsLoadByPerson', getters.person.id)387 } else if (state.activeModule === 'sleep') {388 await dispatch('sleepDatasetsLoadByPerson', getters.person.id)389 } else if (state.activeModule === 'smoking') {390 await dispatch('smokingDatasetsLoadByPerson', getters.person.id)391 } else if (state.activeModule === 'activities') {392 await dispatch('activitiesDatasetsLoadByPerson', getters.person.id)393 } else if (state.activeModule === 'medicine') {394 await dispatch('medicationPlanDatasetsLoadByPerson', getters.person.id)395 }396 commit('loading', false)397 },398 async setValue({ commit, state, getters }, data) {399 // console.debug('try to update person value', data)400 // data: {key, value, [id]}401 const id = 'id' in data ? data.id : getters.person.id402 const o = await personApiClient.updateValue(id, data.key, data.value)403 // console.debug('return from person api', o)404 commit('personUpdate', o)405 showSuccess(t('health', 'Value successfully saved', {}))406 },407 async addPerson({ state, dispatch, commit }, name) {408 const p = await personApiClient.addPerson(name)409 commit('personsAdd', p)410 },411 async deletePerson({ state, dispatch, commit }, person) {412 const existingIndex = state.persons.findIndex(set => set.id === person.id)413 await personApiClient.deletePerson(person.id)414 commit('personsDelete', person)415 if (existingIndex !== -1) {416 dispatch('setActivePerson', 0)417 }418 },419 // module weight420 async weightDatasetsLoadByPerson({ commit }, personId) {421 // console.debug('weightDatasetsLoadByPerson', personId)422 const datasets = await weightApiClient.findDatasetsByPerson(personId)423 // console.debug('found datasets', datasets)424 commit('rWeightDatasets', datasets)425 // console.debug('saved to store "rWeightDatasets"')426 },427 async rWeightDatasetsAppend({ commit, getters }, set) {428 // console.debug('add weight dataset', set)429 const o = await weightApiClient.addSet(getters.person.id, set)430 // console.debug('returned o', o)431 commit('rWeightDatasetsAppend', o)432 },433 async rWeightDatasetsUpdate({ commit, getters }, set) {434 console.debug('update weight dataset', set)435 const o = await weightApiClient.updateSet(set)436 console.debug('returned o', o)437 commit('rWeightDatasetsUpdate', o)438 },439 async rWeightDatasetsDelete({ commit, getters }, set) {440 // console.debug('remove weight dataset', set)441 const o = await weightApiClient.deleteSet(set)442 // console.debug('returned o', o)443 commit('rWeightDatasetsDelete', o)444 },445 // module measurement446 async measurementDatasetsLoadByPerson({ commit }, personId) {447 const datasets = await measurementApiClient.findDatasetsByPerson(personId)448 // console.debug('found datasets', datasets)449 commit('measurementDatasets', datasets)450 },451 async measurementDatasetsAppend({ commit, getters }, set) {452 const o = await measurementApiClient.addSet(getters.person.id, set)453 // console.debug('returned o', o)454 commit('measurementDatasetsAppend', o)455 },456 async measurementDatasetsUpdate({ commit, getters }, set) {457 const o = await measurementApiClient.updateSet(set)458 // console.debug('returned o', o)459 commit('measurementDatasetsUpdate', o)460 },461 async measurementDatasetsDelete({ commit, getters }, set) {462 const o = await measurementApiClient.deleteSet(set)463 // console.debug('returned o', o)464 commit('measurementDatasetsDelete', o)465 },466 // module feeling467 async feelingDatasetsLoadByPerson({ commit }, personId) {468 const datasets = await feelingApiClient.findDatasetsByPerson(personId)469 // console.debug('found datasets', datasets)470 commit('feelingDatasets', datasets)471 },472 async feelingDatasetsAppend({ commit, getters }, set) {473 const o = await feelingApiClient.addSet(getters.person.id, set)474 // console.debug('returned o', o)475 commit('feelingDatasetsAppend', o)476 },477 async feelingDatasetsUpdate({ commit, getters }, set) {478 const o = await feelingApiClient.updateSet(set)479 // console.debug('returned o', o)480 commit('feelingDatasetsUpdate', o)481 },482 async feelingDatasetsDelete({ commit, getters }, set) {483 const o = await feelingApiClient.deleteSet(set)484 // console.debug('returned o', o)485 commit('feelingDatasetsDelete', o)486 },487 // module sleep488 async sleepDatasetsLoadByPerson({ commit }, personId) {489 const datasets = await sleepApiClient.findDatasetsByPerson(personId)490 // console.debug('found datasets', datasets)491 commit('sleepDatasets', datasets)492 },493 async sleepDatasetsAppend({ commit, getters }, set) {494 const o = await sleepApiClient.addSet(getters.person.id, set)495 // console.debug('returned o', o)496 commit('sleepDatasetsAppend', o)497 },498 async sleepDatasetsUpdate({ commit, getters }, set) {499 const o = await sleepApiClient.updateSet(set)500 // console.debug('returned o', o)501 commit('sleepDatasetsUpdate', o)502 },503 async sleepDatasetsDelete({ commit, getters }, set) {504 const o = await sleepApiClient.deleteSet(set)505 // console.debug('returned o', o)506 commit('sleepDatasetsDelete', o)507 },508 // module smoking509 async smokingDatasetsLoadByPerson({ commit }, personId) {510 const datasets = await smokingApiClient.findDatasetsByPerson(personId)511 // console.debug('found datasets', datasets)512 commit('smokingDatasets', datasets)513 },514 async smokingDatasetsAppend({ commit, getters }, set) {515 const o = await smokingApiClient.addSet(getters.person.id, set)516 // console.debug('returned o', o)517 commit('smokingDatasetsAppend', o)518 },519 async smokingDatasetsUpdate({ commit, getters }, set) {520 const o = await smokingApiClient.updateSet(set)521 // console.debug('returned o', o)522 commit('smokingDatasetsUpdate', o)523 },524 async smokingDatasetsDelete({ commit, getters }, set) {525 const o = await smokingApiClient.deleteSet(set)526 // console.debug('returned o', o)527 commit('smokingDatasetsDelete', o)528 },529 // module activities530 async activitiesDatasetsLoadByPerson({ commit }, personId) {531 const datasets = await activitiesApiClient.findDatasetsByPerson(personId)532 // console.debug('found datasets', datasets)533 commit('activitiesDatasets', datasets)534 },535 async activitiesDatasetsAppend({ commit, getters }, set) {536 const o = await activitiesApiClient.addSet(getters.person.id, set)537 // console.debug('returned o', o)538 commit('activitiesDatasetsAppend', o)539 },540 async activitiesDatasetsUpdate({ commit, getters }, set) {541 const o = await activitiesApiClient.updateSet(set)542 // console.debug('returned o', o)543 commit('activitiesDatasetsUpdate', o)544 },545 async activitiesDatasetsDelete({ commit, getters }, set) {546 const o = await activitiesApiClient.deleteSet(set)547 // console.debug('returned o', o)548 commit('activitiesDatasetsDelete', o)549 },550 // module medication551 async medicationDatasetsAppend({ commit, state }, set) {552 console.debug(state)553 const o = await medicationApiClient.addMedication(state.selectedMedicationPlan, set)554 // console.debug('returned o', o)555 commit('medicationDatasetsAppend', o)556 },557 async medicationDatasetsUpdate({ commit }, set) {558 const o = await medicationApiClient.updateMedication(set)559 // console.debug('returned o', o)560 commit('medicationDatasetsUpdate', o)561 },562 async medicationDatasetsDelete({ commit }, set) {563 const o = await medicationApiClient.deleteMedication(set)564 // console.debug('returned o', o)565 commit('medicationDatasetsDelete', o)566 },567 // module medicationPlan568 async medicationPlanDatasetsLoadByPerson({ commit }, personId) {569 const datasets = await medicationApiClient.findMedicationPlansByPerson(personId)570 // console.debug('found datasets', datasets)571 commit('medicationPlanDatasets', datasets)572 },573 async medicationPlanDatasetsAppend({ commit, getters }, set) {574 const o = await medicationApiClient.addMedicationPlan(getters.person.id, set)575 // console.debug('returned o', o)576 commit('medicationPlanDatasetsAppend', o)577 },578 async medicationPlanDatasetsUpdate({ commit }, set) {579 const o = await medicationApiClient.updateMedicationPlan(set)580 // console.debug('returned o', o)581 commit('medicationPlanDatasetsUpdate', o)582 },583 async medicationPlanDatasetsDelete({ commit }, set) {584 const o = await medicationApiClient.deleteMedicationPlan(set)585 // console.debug('returned o', o)586 commit('medicationPlanDatasetsDelete', o)587 },588 async medicationPlanSelected({ commit }, plan) {589 commit('medicationPlanSelected', plan.id)590 const o = await medicationApiClient.findMedicationByPlan(plan.id)591 commit('medicationDatasets', o)592 },593 },...
cartContext.js
Source:cartContext.js
1import { createContext, useState} from "react"2export const CartContext = createContext()3export const CartProvider = ({children}) =>{4 const [cart, setCart] = useState([])5//Añadir al carrito6const addToCart = (id,price,imageId,stock,name, qty) => {7 console.log(name)8 const existingIndex = cart.findIndex((item) => item.id === id);9 10 11 if (existingIndex >= 0) {12 cart[existingIndex] = {13 ...cart[existingIndex],14 qty: cart[existingIndex].qty + qty,15 };16 } else {17 setCart([18 ...cart,19 20 {21 id:id,22 price:price,23 imageId:imageId,24 stock:stock,25 name:name,26 qty:qty,27 },28 ]);29 } 30 31}32//Cantidad de productos totales33const productsCount= () =>{34 let count = 035 cart.forEach((item)=>{36count+=item.qty37 })38return count39}40const totalPrice = () =>{41 let count= 042 cart.forEach((item) => {43count+=item.price * item.qty44 })45return count46}47//Remover del carrito48const removeFromCart = (itemInCart) => {49 const existingIndex = cart.findIndex((item) => item.id === itemInCart.id);50 const cartCopy = Array.from(cart);51console.log(existingIndex)52 if (existingIndex >= 0) {53 cartCopy.splice(existingIndex, 1);54 setCart(cartCopy);55 }56 };57 const sumar = (item) =>{58const existingIndex = cart.findIndex((product) => product.id === item.id);59console.log(cart)60if(cart[existingIndex].qty<cart[existingIndex].stock){61 const newCart = [...cart] 62 newCart[existingIndex] =63 { 64 ...cart[existingIndex],65 qty: cart[existingIndex].qty + 1,66 67}68console.log(newCart)69setCart(newCart)70}71} 72 const restar = (item) =>{73 74 const existingIndex = cart.findIndex((product) => product.id === item.id);75console.log(existingIndex)76 77 if(item.qty>1){78 79 const newCart = [...cart]80 newCart[existingIndex ]= {81 ...cart[existingIndex],82 qty: cart[existingIndex].qty - 1,83 84 }85setCart(newCart)86 } else {87 removeFromCart(item)88 }89 }90 return (91 <CartContext.Provider value={{ cart,setCart, addToCart, removeFromCart, productsCount , totalPrice, sumar, restar}}>92 {children} 93 </CartContext.Provider>94 )95}96//gtihub de un profe https://github.com/angelicamolero/OnlineShop97// video de firebase https://www.youtube.com/watch?v=itNsRn1kjLU...
cart-reducer.js
Source:cart-reducer.js
1import {2 ADD_TO_CART,3 REMOVE_FROM_CART,4 CLEAR_CART,5 CHANGE_FREQUENCY,6 TOGGLE_SUBSCRIPTION,7} from "../actions/action-types"8export default function cartReducer(state, action) {9 let newCart = [...state]10 let existingIndex11 if (action.payload) {12 existingIndex = state.findIndex(13 item => item.variant === action.payload.variant14 )15 }16 const saveData = cart => {17 localStorage.setItem("cart", JSON.stringify(cart))18 }19 switch (action.type) {20 case ADD_TO_CART:21 if (existingIndex !== -1) {22 let newQty = newCart[existingIndex].qty + action.payload.qty23 if (newQty > action.payload.stock) {24 newQty = action.payload.stock25 }26 newCart[existingIndex] = { ...newCart[existingIndex], qty: newQty }27 } else {28 newCart.push(action.payload)29 }30 saveData(newCart)31 return newCart32 case REMOVE_FROM_CART:33 const newQty = newCart[existingIndex].qty - action.payload.qty34 if (newQty <= 0) {35 newCart = newCart.filter(36 item => item.variant !== action.payload.variant37 )38 } else {39 newCart[existingIndex] = { ...newCart[existingIndex], qty: newQty }40 }41 saveData(newCart)42 return newCart43 case CHANGE_FREQUENCY:44 newCart[existingIndex].subscription = action.payload.frequency45 saveData(newCart)46 return newCart47 case TOGGLE_SUBSCRIPTION:48 const existingSubscription = !!newCart[existingIndex].subscription49 if (existingSubscription) {50 delete newCart[existingIndex].subscription51 } else {52 newCart[existingIndex].subscription = action.payload.frequency53 }54 saveData(newCart)55 return newCart56 case CLEAR_CART:57 localStorage.removeItem("cart")58 return []59 default:60 return state61 }...
Using AI Code Generation
1const wptools = require('wptools');2const fs = require('fs');3const path = require('path');4const async = require('async');5const request = require('request');6const csv = require('csv-parser');7const results = [];8const filePath = path.join(__dirname, 'data.csv');9const resultsPath = path.join(__dirname, 'results.csv');10const resultsFile = fs.createWriteStream(resultsPath, { flags: 'a' });11const csvStream = csv()12 .on('data', (data) => results.push(data))13 .on('end', () => {14 async.eachLimit(results, 10, (result, callback) => {15 const { title, pageid } = result;16 wptools.page(title).get((err, response) => {17 if (err) {18 console.log(err);19 return callback();20 }21 const { image } = response.data;22 if (image) {23 const { url } = image[0];24 const { descriptionurl } = image[0];25 const { title } = image[0];26 const { extmetadata } = image[0];27 const { DateTime } = extmetadata;28 const { Artist } = extmetadata;29 const { Credit } = extmetadata;30 const { LicenseShortName } = extmetadata;31 const { LicenseUrl } = extmetadata;32 const { UsageTerms } = extmetadata;33 const { Attribution } = extmetadata;34 const { Restriction } = extmetadata;35 const { ObjectName } = extmetadata;36 const { Commonscat } = extmetadata;37 const { Categories } = extmetadata;38 const { Description } = extmetadata;39 const { Depicts } = extmetadata;40 const { ImageDescription } = extmetadata;41 const { ImagePage } = extmetadata;42 const { ImageTitle } = extmetadata;43 const { ImageUrl } = extmetadata;44 const { License } = extmetadata;45 const { LicenseShort } = extmetadata;46 const { MetadataDate } = extmetadata;47 const { ObjectHistory } = extmetadata;48 const { ObjectNameHistory } = extmetadata;49 const { ObjectPage } = extmetadata;50 const { ObjectUrl } = extmetadata;51 const { OtherVersions } = extmetadata;52 const { Permission } = extmetadata;53 const {
Using AI Code Generation
1const wptools = require('wptools');2const fs = require('fs');3const data = JSON.parse(fs.readFileSync('./data.json', 'utf8'));4const wikipages = data.map((item) => {5 return item.wiki;6});7const pages = wptools.get(wikipages);8pages.then((res) => {9 console.log(res);10});11[MIT](LICENSE)
Using AI Code Generation
1const wpt = require('wpt-api').wpt;2const wptInstance = new wpt('API_KEY');3let arr = [1, 2, 3, 4, 5];4let index = wptInstance.existingIndex(arr, 3);5console.log(index);6## existingIndex(arr, value, [fromIndex])7wpt.existingIndex([1, 2, 1, 2], 2);8wpt.existingIndex([1, 2, 1, 2], 2, 2);9wpt.existingIndex([1, 2, 1, 2], 3);10## existingLastIndex(arr, value, [fromIndex])11wpt.existingLastIndex([1, 2, 1, 2], 2);12wpt.existingLastIndex([1, 2, 1, 2], 2, 2);13wpt.existingLastIndex([1, 2, 1, 2], 3);14## fill(arr, value, [start], [end])
Using AI Code Generation
1var wpt = require('webpagetest');2var options = {3};4var client = wpt(options);5client.getTestHistory(function(err, data) {6 if (err) return console.error(err);7 console.log(data);8});9### wpt(options)10#### client.runTest(url, options, callback)
Using AI Code Generation
1var wpt = require('wpt');2var wpt = new WebPageTest('www.webpagetest.org','A.8d1d0b0c7e0e1c6b0d8b3f3f3c3c3c3c');3wpt.getTesters(function(err, data) {4 if (err) return console.error(err);5 console.log(data);6});7var wpt = new WebPageTest('www.webpagetest.org','A.8d1d0b0c7e0e1c6b0d8b3f3f3c3c3c3c');8#### runTest(url, options, callback)9- `location` - The location to test from (default: `ec2-us-west-1:Chrome`)10- `firstViewOnly` - Only test the first view (default: `false`)11- `runs` - Number of test runs (default: `1`)12- `private` - Make the test private (default: `false`)13- `video` - Capture video of the test (default: `true`)14- `sensitive` - Don't send any JavaScript to the browser (default: `false`)15- `ignoreSSL` - Ignore SSL certificate errors (default: `false`)16- `connectivity` - The simulated connectivity profile (default: `Cable`)17- `bwDown` - The download bandwidth in Kbps (default: `2000`)18- `bwUp` - The upload bandwidth in Kbps (default: `1000`)19- `latency` - The latency in ms (default: `50`)20- `plr` - The packet loss rate (default: `0`)21- `mobile` - Run the test on a mobile device (default: `false`)22- `mobileDevice` - The mobile device to emulate (default: `Apple iPhone 4`)23- `mobileCarrier` - The mobile carrier to emulate (default: `Vodafone`)24- `timeline` - Capture a timeline of page load events (default: `false`)
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!