How to use itemIndex method in Best

Best JavaScript code snippet using best

CustomTimePicker.js

Source:CustomTimePicker.js Github

copy

Full Screen

1import React, { useState, useRef } from 'react';2import PropTypes from 'prop-types';3import { FlatList, Text, StyleSheet, View } from 'react-native'4/**5 * @param {Object} props6 * @param {String} [props.initialSelectedTime]7 * @param {Function} props.onTimeChange8 * @param {Number} [props.width]9 * @param {Number} [props.height]10 */11const CustomTimePicker = ({ initialSelectedTime, onTimeChange, width, height }) => {12 // default width and height13 let itemHeight = 30;14 let listHeight = 100;15 if (height) {16 listHeight = height;17 itemHeight = listHeight / 3;18 }19 const [hourList] = useState([20 { 'label': '', 'itemIndex': 0, 'value': 0 },21 { 'label': '01', 'itemIndex': 1, 'value': 1 },22 { 'label': '02', 'itemIndex': 2, 'value': 2 },23 { 'label': '03', 'itemIndex': 3, 'value': 3 },24 { 'label': '04', 'itemIndex': 4, 'value': 4 },25 { 'label': '05', 'itemIndex': 5, 'value': 5 },26 { 'label': '06', 'itemIndex': 6, 'value': 6 },27 { 'label': '07', 'itemIndex': 7, 'value': 7 },28 { 'label': '08', 'itemIndex': 8, 'value': 8 },29 { 'label': '09', 'itemIndex': 9, 'value': 9 },30 { 'label': '10', 'itemIndex': 10, 'value': 10 },31 { 'label': '11', 'itemIndex': 11, 'value': 11 },32 { 'label': '12', 'itemIndex': 12, 'value': 12 },33 { 'label': '', 'itemIndex': 13, 'value': 13 },34 ])35 const [minuteList] = useState([36 { 'label': '', 'itemIndex': 0, 'value': 0 },37 { 'label': '00', 'itemIndex': 1, 'value': 0 },38 { 'label': '31', 'itemIndex': 2, 'value': 30 },39 { 'label': '02', 'itemIndex': 3, 'value': 2 },40 { 'label': '03', 'itemIndex': 4, 'value': 3 },41 { 'label': '04', 'itemIndex': 5, 'value': 4 },42 { 'label': '05', 'itemIndex': 6, 'value': 5 },43 { 'label': '06', 'itemIndex': 7, 'value': 6 },44 { 'label': '07', 'itemIndex': 8, 'value': 7 },45 { 'label': '08', 'itemIndex': 9, 'value': 8 },46 { 'label': '09', 'itemIndex': 10, 'value': 9 },47 { 'label': '10', 'itemIndex': 11, 'value': 10 },48 { 'label': '11', 'itemIndex': 12, 'value': 11 },49 { 'label': '12', 'itemIndex': 13, 'value': 12 },50 { 'label': '13', 'itemIndex': 14, 'value': 13 },51 { 'label': '14', 'itemIndex': 15, 'value': 14 },52 { 'label': '15', 'itemIndex': 16, 'value': 15 },53 { 'label': '16', 'itemIndex': 17, 'value': 16 },54 { 'label': '17', 'itemIndex': 18, 'value': 17 },55 { 'label': '18', 'itemIndex': 19, 'value': 18 },56 { 'label': '19', 'itemIndex': 20, 'value': 19 },57 { 'label': '20', 'itemIndex': 21, 'value': 20 },58 { 'label': '21', 'itemIndex': 22, 'value': 21 },59 { 'label': '22', 'itemIndex': 23, 'value': 22 },60 { 'label': '23', 'itemIndex': 24, 'value': 23 },61 { 'label': '24', 'itemIndex': 25, 'value': 24 },62 { 'label': '25', 'itemIndex': 26, 'value': 25 },63 { 'label': '26', 'itemIndex': 27, 'value': 26 },64 { 'label': '27', 'itemIndex': 28, 'value': 27 },65 { 'label': '28', 'itemIndex': 29, 'value': 28 },66 { 'label': '29', 'itemIndex': 30, 'value': 29 },67 { 'label': '30', 'itemIndex': 31, 'value': 30 },68 { 'label': '31', 'itemIndex': 32, 'value': 31 },69 { 'label': '32', 'itemIndex': 33, 'value': 32 },70 { 'label': '33', 'itemIndex': 34, 'value': 33 },71 { 'label': '34', 'itemIndex': 35, 'value': 34 },72 { 'label': '35', 'itemIndex': 36, 'value': 35 },73 { 'label': '36', 'itemIndex': 37, 'value': 36 },74 { 'label': '37', 'itemIndex': 38, 'value': 37 },75 { 'label': '38', 'itemIndex': 39, 'value': 38 },76 { 'label': '39', 'itemIndex': 40, 'value': 39 },77 { 'label': '40', 'itemIndex': 41, 'value': 40 },78 { 'label': '41', 'itemIndex': 42, 'value': 41 },79 { 'label': '42', 'itemIndex': 43, 'value': 42 },80 { 'label': '43', 'itemIndex': 44, 'value': 43 },81 { 'label': '44', 'itemIndex': 45, 'value': 44 },82 { 'label': '45', 'itemIndex': 46, 'value': 45 },83 { 'label': '46', 'itemIndex': 47, 'value': 46 },84 { 'label': '47', 'itemIndex': 48, 'value': 47 },85 { 'label': '48', 'itemIndex': 49, 'value': 48 },86 { 'label': '49', 'itemIndex': 50, 'value': 49 },87 { 'label': '50', 'itemIndex': 51, 'value': 50 },88 { 'label': '51', 'itemIndex': 52, 'value': 51 },89 { 'label': '52', 'itemIndex': 53, 'value': 52 },90 { 'label': '53', 'itemIndex': 54, 'value': 53 },91 { 'label': '54', 'itemIndex': 55, 'value': 54 },92 { 'label': '55', 'itemIndex': 56, 'value': 55 },93 { 'label': '56', 'itemIndex': 57, 'value': 56 },94 { 'label': '57', 'itemIndex': 58, 'value': 57 },95 { 'label': '58', 'itemIndex': 59, 'value': 58 },96 { 'label': '59', 'itemIndex': 60, 'value': 59 },97 { 'label': '', 'itemIndex': 61, 'value': 60 },98 ])99 const [ampmList] = useState([100 { 'label': '', 'itemIndex': 0, 'value': 'AM' },101 { 'label': 'AM', 'itemIndex': 1, 'value': 'AM' },102 { 'label': 'PM', 'itemIndex': 2, 'value': 'PM' },103 { 'label': '', 'itemIndex': 3, 'value': 'AM' },104 ])105 106 // Initial index107 const [currentHourIndex, setCurrentHourIndex] = useState(getHourIndex(initialSelectedTime))108 const [currentMinuteIndex, setCurrentMinuteIndex] = useState(getMinuteIndex(initialSelectedTime))109 const [currentAMPMIndex, setCurrentAMPMIndex] = useState(getAMPMIndex(initialSelectedTime))110 const SelectedListItem = React.memo(({ name, style }) => (111 <View style={style}>112 <Text style={{ alignItems: 'flex-end', justifyContent: 'flex-end', fontSize: 24, color: '#808080', fontFamily: 'SFPro', backgroundColor: 'transparent' }}>{name}</Text>113 </View>114 ));115 const DeselectedListItem = React.memo(({ name, style }) => (116 <View style={style}>117 <Text style={{ justifyContent: 'flex-end', fontSize: 20, color: '#CCCCCC', fontFamily: 'SFPro', backgroundColor: 'transparent' }}>{name}</Text>118 </View>119 ));120 const styles = StyleSheet.create({121 list: {122 height: listHeight,123 width: '100%',124 backgroundColor: 'transparent',125 flexDirection: "row",126 justifyContent: "space-between"127 },128 listStyle: {129 width: '33%',130 backgroundColor: 'transparent'131 },132 listItemHour: {133 height: itemHeight,134 alignItems: 'flex-end',135 justifyContent: 'center',136 backgroundColor: 'transparent'137 },138 listItemMinute: {139 height: itemHeight,140 alignItems: 'center',141 justifyContent: 'center',142 backgroundColor: 'transparent'143 },144 listItemAMPM: {145 height: itemHeight,146 alignItems: 'flex-start',147 justifyContent: 'center',148 backgroundColor: 'transparent'149 },150 });151 const flatList = useRef(null);152 function getHourIndex(initialTime) {153 console.log("initialTime= ", initialTime)154 const initialTimeSeparated = initialTime.split(':')155 for (var i = 0; i < hourList.length; i++) {156 if (initialTimeSeparated[0] == hourList[i].label){157 return i158 break159 }160 }161}162 function getMinuteIndex(initialTime) {163 console.log("initial time=",initialTime)164 const initialTimeSeparated = initialTime.split(':')165 const initialTimeSeparated1 = initialTimeSeparated[1].split(' ')166 for (var i = 0; i < minuteList.length; i++) {167 if (initialTimeSeparated1[0] == minuteList[i].label){168 return i169 break170 }171 }172 }173 function getAMPMIndex(initialTime) {174 const initialTimeSeparated = initialTime.split(' ')175 for (var i = 0; i < ampmList.length; i++) {176 if (initialTimeSeparated[1] == ampmList[i].label){177 return i178 break179 }180 }181 }182 const processTime = (type, index) => {183 var finalHour = ""184 var finalMinute = ""185 var finalAMPM = ""186 var finalTime = ""187 if (type == "Hour") {188 finalHour = hourList[index].label189 finalMinute = minuteList[currentMinuteIndex].label190 finalAMPM = ampmList[currentAMPMIndex].label191 } else if (type == "Minute") {192 finalHour = hourList[currentHourIndex].label193 finalMinute = minuteList[index].label194 finalAMPM = ampmList[currentAMPMIndex].label195 } else if (type == "AMPM") {196 finalHour = hourList[currentHourIndex].label197 finalMinute = minuteList[currentMinuteIndex].label198 finalAMPM = ampmList[index].label199 console.log("finalAMPM=" , finalAMPM)200 }201 finalTime = finalHour + ":" + finalMinute + " " + finalAMPM202 console.log(finalTime)203 onTimeChange({ item: finalTime })204 }205 return (206 <View style={styles.list}>207 <FlatList208 showsHorizontalScrollIndicator={false}209 showsVerticalScrollIndicator={false}210 style={styles.listStyle}211 nestedScrollEnabled={true}212 onMomentumScrollEnd={(event) => {213 let index = Math.round(event.nativeEvent.contentOffset.y / itemHeight);214 console.log(index)215 setCurrentHourIndex(index + 1)216 processTime("Hour", index + 1)217 }}218 onScrollEndDrag={(event) => {219 let index = Math.round(event.nativeEvent.contentOffset.y / itemHeight);220 console.log(index)221 setCurrentHourIndex(index + 1)222 // processTime("Hour", index + 1)223 }}224 initialScrollIndex={currentHourIndex - 1}225 ref={flatList}226 data={hourList}227 renderItem={(item) => {228 return (item.item.itemIndex == currentHourIndex) ?229 <SelectedListItem230 name={item.item.label}231 style={styles.listItemHour} />232 : <DeselectedListItem233 name={item.item.label}234 style={styles.listItemHour} />235 }}236 getItemLayout={(_, index) => ({ length: itemHeight, offset: index * itemHeight, index })}237 snapToOffsets={hourList.map((x, i) => (i * itemHeight))}238 bounces={false}239 pagingEnabled={true}240 ListEmptyComponent={() => <Text>No Items</Text>}241 />242 <FlatList243 showsHorizontalScrollIndicator={false}244 showsVerticalScrollIndicator={false}245 style={styles.listStyle}246 nestedScrollEnabled={true}247 onMomentumScrollEnd={(event) => {248 let index = Math.round(event.nativeEvent.contentOffset.y / itemHeight);249 // console.log(event.nativeEvent.contentOffset.y / itemHeight)250 // console.log(index)251 setCurrentMinuteIndex(index + 1)252 processTime("Minute", index + 1)253 }}254 onScroll={(event) => {255 let index = Math.round(event.nativeEvent.contentOffset.y / itemHeight);256 console.log(index)257 setCurrentMinuteIndex(index + 1)258 // processTime("Minute", index + 1)259 }}260 initialScrollIndex={currentMinuteIndex - 1}261 ref={flatList}262 data={minuteList}263 renderItem={(item) => {264 return (item.item.itemIndex == currentMinuteIndex) ?265 <SelectedListItem266 name={item.item.label}267 style={styles.listItemMinute} />268 : <DeselectedListItem269 name={item.item.label}270 style={styles.listItemMinute} />271 }}272 getItemLayout={(_, index) => ({ length: itemHeight, offset: index * itemHeight, index })}273 snapToOffsets={minuteList.map((x, i) => (i * itemHeight))}274 bounces={false}275 pagingEnabled={true}276 ListEmptyComponent={() => <Text>No Items</Text>}277 />278 <FlatList279 showsHorizontalScrollIndicator={false}280 showsVerticalScrollIndicator={false}281 style={styles.listStyle}282 nestedScrollEnabled={true}283 onMomentumScrollEnd={(event) => {284 let index = Math.round(event.nativeEvent.contentOffset.y / itemHeight);285 setCurrentAMPMIndex(index + 1)286 processTime("AMPM", index + 1)287 }}288 onScrollEndDrag={(event) => {289 let index = Math.round(event.nativeEvent.contentOffset.y / itemHeight);290 console.log(index)291 setCurrentAMPMIndex(index + 1)292 // processTime("AMPM", index + 1)293 }}294 initialScrollIndex={currentAMPMIndex - 1}295 ref={flatList}296 data={ampmList}297 renderItem={(item) => {298 return (item.item.itemIndex == currentAMPMIndex) ?299 <SelectedListItem300 name={item.item.label}301 style={styles.listItemAMPM} />302 : <DeselectedListItem303 name={item.item.label}304 style={styles.listItemAMPM} />305 }}306 getItemLayout={(_, index) => ({ length: itemHeight, offset: index * itemHeight, index })}307 snapToOffsets={ampmList.map((x, i) => (i * itemHeight))}308 bounces={false}309 pagingEnabled={true}310 ListEmptyComponent={() => <Text>No Items</Text>}311 />312 </View>313 )314}315CustomTimePicker.propTypes = {316 initialSelectedTime: PropTypes.string,317 onTimeChange: PropTypes.func,318 height: PropTypes.number,319 width: PropTypes.number320}...

Full Screen

Full Screen

Item.spec.ts

Source:Item.spec.ts Github

copy

Full Screen

1import { expect } from 'chai';2import { shallowMount, mount, createLocalVue } from '@vue/test-utils';3import sinon from 'sinon';4import Item from '@/components/widgets/timeline/Item.vue';5import moment from 'moment';6// describe('widgets/timeline/Item.vue', () => {7// const title = 'title';8// const date = moment();9// const description = 'description';10// const fadeInLeft = true;11// const imageUrl = 'imageUrl';12// const editMode = false;13// const itemIndex = 0;14// describe('Props', () => {15// it('should populate the props correctly', () => {16// const wrapper = shallowMount(Item, {17// propsData: {18// title: title,19// date: date,20// description: description,21// fadeInLeft: fadeInLeft,22// imageUrl: imageUrl,23// editMode: editMode,24// itemIndex: itemIndex,25// },26// });27// expect(wrapper.props().title).to.equal(title);28// expect(wrapper.props().date).to.deep.equal(date);29// expect(wrapper.props().description).to.equal(description);30// expect(wrapper.props().fadeInLeft).to.equal(fadeInLeft);31// expect(wrapper.props().imageUrl).to.equal(imageUrl);32// expect(wrapper.props().editMode).to.equal(editMode);33// expect(wrapper.props().itemIndex).to.equal(itemIndex);34// });35// });36// describe('Data', () => {37// it('should populate the data correctly', () => {38// const wrapper = shallowMount(Item, {39// propsData: {40// title: title,41// date: date,42// description: description,43// fadeInLeft: fadeInLeft,44// imageUrl: imageUrl,45// editMode: editMode,46// itemIndex: itemIndex,47// },48// });49// expect(wrapper.vm.containsImage).to.be.true;50// expect(wrapper.vm.updatedTitle).to.equal(title);51// expect(wrapper.vm.updatedDescription).to.equal(description);52// expect(wrapper.vm.updatedDate).to.deep.equal(date.toDate());53// expect(wrapper.vm.updatedImageUrl).to.equal(imageUrl);54// });55// });56// describe('getter classObject', () => {57// it('should return the correct value', () => {58// const wrapper = shallowMount(Item, {59// propsData: {60// title: title,61// date: date,62// description: description,63// fadeInLeft: fadeInLeft,64// imageUrl: imageUrl,65// editMode: editMode,66// itemIndex: itemIndex,67// },68// });69// expect(wrapper.vm.classObject).to.deep.equal({70// 'timeline-content': true,71// 'js--fadeInLeft': fadeInLeft,72// 'js--fadeInRight': !fadeInLeft,73// 'timeline-card': wrapper.vm.containsImage,74// });75// });76// });77// describe('getter headerImageUrl', () => {78// it('should return the correct value when not in edit mode', () => {79// const wrapper = shallowMount(Item, {80// propsData: {81// title: title,82// date: date,83// description: description,84// fadeInLeft: fadeInLeft,85// imageUrl: imageUrl,86// editMode: false,87// itemIndex: itemIndex,88// },89// });90// expect(wrapper.vm.headerImageUrl).to.equal(imageUrl);91// wrapper.setData({ updatedImageUrl: 'updatedImageUrl' });92// });93// it('should return the correct value when in edit mode', () => {94// const wrapper = shallowMount(Item, {95// propsData: {96// title: title,97// date: date,98// description: description,99// fadeInLeft: fadeInLeft,100// imageUrl: imageUrl,101// editMode: true,102// itemIndex: itemIndex,103// },104// });105// wrapper.setData({ updatedImageUrl: 'updatedImageUrl' });106// expect(wrapper.vm.headerImageUrl).to.equal(wrapper.vm.updatedImageUrl);107// });108// });109// describe('getter formattedDate', () => {110// it('should return the correct value when in edit mode', () => {111// const wrapper = shallowMount(Item, {112// propsData: {113// title: title,114// date: date,115// description: description,116// fadeInLeft: fadeInLeft,117// imageUrl: imageUrl,118// editMode: editMode,119// itemIndex: itemIndex,120// },121// });122// expect(wrapper.vm.formattedDate).to.equal(date.format('DD MMMM YYYY'));123// });124// });125// describe('#emitUpdatedItem', () => {126// it('should call the correct method', () => {127// const updatedItem = sinon.spy();128// const wrapper = shallowMount(Item, {129// propsData: {130// title: title,131// date: date,132// description: description,133// fadeInLeft: fadeInLeft,134// imageUrl: imageUrl,135// editMode: editMode,136// itemIndex: itemIndex,137// },138// methods: {139// updatedItem,140// },141// });142// wrapper.setData({143// updatedTitle: 'updated title',144// updatedDescription: 'updated description',145// updatedDate: new Date(),146// updatedImageUrl: 'updatedImageUrl',147// });148// wrapper.vm.emitUpdatedItem();149// expect(150// updatedItem.calledOnceWith({151// title: wrapper.vm.updatedTitle,152// description: wrapper.vm.updatedDescription,153// date: moment(wrapper.vm.updatedDate),154// imageUrl: wrapper.vm.updatedImageUrl,155// }),156// ).to.be.true;157// });158// });159// describe('#openImgUrlPicker', () => {160// it('should set the correct value on component data', () => {161// const wrapper = shallowMount(Item, {162// propsData: {163// title: title,164// date: date,165// description: description,166// fadeInLeft: fadeInLeft,167// imageUrl: imageUrl,168// editMode: editMode,169// itemIndex: itemIndex,170// },171// });172// expect(wrapper.vm.showImgUrlPicker).to.be.false;173// wrapper.vm.openImgUrlPicker();174// expect(wrapper.vm.showImgUrlPicker).to.be.true;175// });176// });177// describe('#deleteItem', () => {178// it('should call the correct method', () => {179// const deletedItem = sinon.spy();180// const wrapper = shallowMount(Item, {181// propsData: {182// title: title,183// date: date,184// description: description,185// fadeInLeft: fadeInLeft,186// imageUrl: imageUrl,187// editMode: editMode,188// itemIndex: itemIndex,189// },190// methods: {191// deletedItem,192// },193// });194// wrapper.vm.deleteItem();195// expect(deletedItem.calledOnceWith(itemIndex)).to.be.true;196// });197// });198// describe('events', () => {199// describe('#updatedItem', () => {200// it('should emit the correct event', () => {201// const wrapper = shallowMount(Item, {202// propsData: {203// title: title,204// date: date,205// description: description,206// fadeInLeft: fadeInLeft,207// imageUrl: imageUrl,208// editMode: editMode,209// itemIndex: itemIndex,210// },211// });212// const now = moment();213// const item = {214// internalId: '1',215// title: 'title',216// description: 'description',217// date: now,218// imageUrl: 'imageUrl',219// };220// wrapper.vm.updatedItem(item);221// expect(wrapper.emitted('updated-item')).to.have.lengthOf(1);222// expect(wrapper.emitted('updated-item')[0]).to.deep.equal([item]);223// });224// });225// describe('#deletedItem', () => {226// it('should emit the correct event', () => {227// const wrapper = shallowMount(Item, {228// propsData: {229// title: title,230// date: date,231// description: description,232// fadeInLeft: fadeInLeft,233// imageUrl: imageUrl,234// editMode: editMode,235// itemIndex: itemIndex,236// },237// });238// const index = 0;239// wrapper.vm.deletedItem(index);240// expect(wrapper.emitted('deleted-item')).to.have.lengthOf(1);241// expect(wrapper.emitted('deleted-item')[0]).to.deep.equal([index]);242// });243// });244// });...

Full Screen

Full Screen

Knapsack.js

Source:Knapsack.js Github

copy

Full Screen

1import MergeSort from '../../sorting/merge-sort/MergeSort';2export default class Knapsack {3 /**4 * @param {KnapsackItem[]} possibleItems5 * @param {number} weightLimit6 */7 constructor(possibleItems, weightLimit) {8 this.selectedItems = [];9 this.weightLimit = weightLimit;10 this.possibleItems = possibleItems;11 }12 sortPossibleItemsByWeight() {13 this.possibleItems = new MergeSort({14 /**15 * @var KnapsackItem itemA16 * @var KnapsackItem itemB17 */18 compareCallback: (itemA, itemB) => {19 if (itemA.weight === itemB.weight) {20 return 0;21 }22 return itemA.weight < itemB.weight ? -1 : 1;23 },24 }).sort(this.possibleItems);25 }26 sortPossibleItemsByValue() {27 this.possibleItems = new MergeSort({28 /**29 * @var KnapsackItem itemA30 * @var KnapsackItem itemB31 */32 compareCallback: (itemA, itemB) => {33 if (itemA.value === itemB.value) {34 return 0;35 }36 return itemA.value > itemB.value ? -1 : 1;37 },38 }).sort(this.possibleItems);39 }40 sortPossibleItemsByValuePerWeightRatio() {41 this.possibleItems = new MergeSort({42 /**43 * @var KnapsackItem itemA44 * @var KnapsackItem itemB45 */46 compareCallback: (itemA, itemB) => {47 if (itemA.valuePerWeightRatio === itemB.valuePerWeightRatio) {48 return 0;49 }50 return itemA.valuePerWeightRatio > itemB.valuePerWeightRatio ? -1 : 1;51 },52 }).sort(this.possibleItems);53 }54 // Solve 0/1 knapsack problem55 // Dynamic Programming approach.56 solveZeroOneKnapsackProblem() {57 // We do two sorts because in case of equal weights but different values58 // we need to take the most valuable items first.59 this.sortPossibleItemsByValue();60 this.sortPossibleItemsByWeight();61 this.selectedItems = [];62 // Create knapsack values matrix.63 const numberOfRows = this.possibleItems.length;64 const numberOfColumns = this.weightLimit;65 const knapsackMatrix = Array(numberOfRows).fill(null).map(() => {66 return Array(numberOfColumns + 1).fill(null);67 });68 // Fill the first column with zeros since it would mean that there is69 // no items we can add to knapsack in case if weight limitation is zero.70 for (let itemIndex = 0; itemIndex < this.possibleItems.length; itemIndex += 1) {71 knapsackMatrix[itemIndex][0] = 0;72 }73 // Fill the first row with max possible values we would get by just adding74 // or not adding the first item to the knapsack.75 for (let weightIndex = 1; weightIndex <= this.weightLimit; weightIndex += 1) {76 const itemIndex = 0;77 const itemWeight = this.possibleItems[itemIndex].weight;78 const itemValue = this.possibleItems[itemIndex].value;79 knapsackMatrix[itemIndex][weightIndex] = itemWeight <= weightIndex ? itemValue : 0;80 }81 // Go through combinations of how we may add items to knapsack and82 // define what weight/value we would receive using Dynamic Programming83 // approach.84 for (let itemIndex = 1; itemIndex < this.possibleItems.length; itemIndex += 1) {85 for (let weightIndex = 1; weightIndex <= this.weightLimit; weightIndex += 1) {86 const currentItemWeight = this.possibleItems[itemIndex].weight;87 const currentItemValue = this.possibleItems[itemIndex].value;88 if (currentItemWeight > weightIndex) {89 // In case if item's weight is bigger then currently allowed weight90 // then we can't add it to knapsack and the max possible value we can91 // gain at the moment is the max value we got for previous item.92 knapsackMatrix[itemIndex][weightIndex] = knapsackMatrix[itemIndex - 1][weightIndex];93 } else {94 // Else we need to consider the max value we can gain at this point by adding95 // current value or just by keeping the previous item for current weight.96 knapsackMatrix[itemIndex][weightIndex] = Math.max(97 currentItemValue + knapsackMatrix[itemIndex - 1][weightIndex - currentItemWeight],98 knapsackMatrix[itemIndex - 1][weightIndex],99 );100 }101 }102 }103 // Now let's trace back the knapsack matrix to see what items we're going to add104 // to the knapsack.105 let itemIndex = this.possibleItems.length - 1;106 let weightIndex = this.weightLimit;107 while (itemIndex > 0) {108 const currentItem = this.possibleItems[itemIndex];109 const prevItem = this.possibleItems[itemIndex - 1];110 // Check if matrix value came from top (from previous item).111 // In this case this would mean that we need to include previous item112 // to the list of selected items.113 if (114 knapsackMatrix[itemIndex][weightIndex]115 && knapsackMatrix[itemIndex][weightIndex] === knapsackMatrix[itemIndex - 1][weightIndex]116 ) {117 // Check if there are several items with the same weight but with the different values.118 // We need to add highest item in the matrix that is possible to get the highest value.119 const prevSumValue = knapsackMatrix[itemIndex - 1][weightIndex];120 const prevPrevSumValue = knapsackMatrix[itemIndex - 2][weightIndex];121 if (122 !prevSumValue123 || (prevSumValue && prevPrevSumValue !== prevSumValue)124 ) {125 this.selectedItems.push(prevItem);126 }127 } else if (knapsackMatrix[itemIndex - 1][weightIndex - currentItem.weight]) {128 this.selectedItems.push(prevItem);129 weightIndex -= currentItem.weight;130 }131 itemIndex -= 1;132 }133 }134 // Solve unbounded knapsack problem.135 // Greedy approach.136 solveUnboundedKnapsackProblem() {137 this.sortPossibleItemsByValue();138 this.sortPossibleItemsByValuePerWeightRatio();139 for (let itemIndex = 0; itemIndex < this.possibleItems.length; itemIndex += 1) {140 if (this.totalWeight < this.weightLimit) {141 const currentItem = this.possibleItems[itemIndex];142 // Detect how much of current items we can push to knapsack.143 const availableWeight = this.weightLimit - this.totalWeight;144 const maxPossibleItemsCount = Math.floor(availableWeight / currentItem.weight);145 if (maxPossibleItemsCount > currentItem.itemsInStock) {146 // If we have more items in stock then it is allowed to add147 // let's add the maximum allowed number of them.148 currentItem.quantity = currentItem.itemsInStock;149 } else if (maxPossibleItemsCount) {150 // In case if we don't have specified number of items in stock151 // let's add only items we have in stock.152 currentItem.quantity = maxPossibleItemsCount;153 }154 this.selectedItems.push(currentItem);155 }156 }157 }158 get totalValue() {159 /** @var {KnapsackItem} item */160 return this.selectedItems.reduce((accumulator, item) => {161 return accumulator + item.totalValue;162 }, 0);163 }164 get totalWeight() {165 /** @var {KnapsackItem} item */166 return this.selectedItems.reduce((accumulator, item) => {167 return accumulator + item.totalWeight;168 }, 0);169 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var BestBefore = require('./BestBefore.js');2var bb = new BestBefore("2017-11-20");3console.log(bb.itemIndex("2017-11-20"));4console.log(bb.itemIndex("2017-11-21"));5console.log(bb.itemIndex("2017-11-19"));6console.log(bb.itemIndex("2017-11-22"));7console.log(bb.itemIndex("2017-11-18"));8console.log(bb.itemIndex("2017-11-23"));9console.log(bb.itemIndex("2017-11-17"));10console.log(bb.itemIndex("2017-11-24"));11console.log(bb.itemIndex("2017-11-16"));12console.log(bb.itemIndex("2017-11-25"));13console.log(bb.itemIndex("2017-11-15"));14console.log(bb.itemIndex("2017-11-26"));15console.log(bb.itemIndex("2017-11-14"));16console.log(bb.itemIndex("2017-11-27"));17console.log(bb.itemIndex("2017-11-13"));18console.log(bb.itemIndex("2017-11-28"));19console.log(bb.itemIndex("2017-11-12"));20console.log(bb.itemIndex("2017-11-29"));21console.log(bb.itemIndex("2017-11-11"));22console.log(bb.itemIndex("2017-11-30"));23console.log(bb.itemIndex("2017-11-10"));24console.log(bb.itemIndex("2017-12-01"));25console.log(bb.itemIndex("2017-11-09"));26console.log(bb.itemIndex("2017-12-02"));27console.log(bb.itemIndex("2017-11-08"));28console.log(bb.itemIndex("2017-12-03"));29console.log(bb.itemIndex("2017-11-07"));30console.log(bb.itemIndex("2017-12-04"));31console.log(bb.itemIndex("2017-11-06"));32console.log(bb.itemIndex("2017-12-05"));33console.log(bb.itemIndex("2017-11-05"));34console.log(bb.itemIndex("2017-12-06"));35console.log(bb.itemIndex("2017-11-04"));36console.log(bb.itemIndex("2017-12-07"));37console.log(bb.itemIndex("2017-11-03"));38console.log(bb.itemIndex("2017-12-08"));39console.log(bb.item

Full Screen

Using AI Code Generation

copy

Full Screen

1const BestBuy = require('./bestbuy.js');2const bestBuy = new BestBuy();3bestBuy.itemIndex('samsung', 'tv')4 .then((data) => {5 console.log(data);6 })7 .catch((error) => {8 console.log(error);9 });

Full Screen

Using AI Code Generation

copy

Full Screen

1var BestBuy = require('bestbuy')('your-api-key');2BestBuy.products('(search=ipod)', {show: 'sku,name,salePrice', page: 2, pageSize: 3, sort: 'sku.asc'})3 .then(function(data){4 console.log(data);5 })6 .catch(function(error){7 console.log(error);8 });

Full Screen

Using AI Code Generation

copy

Full Screen

1var BestBuy = require('bestbuy')('your-api-key');2BestBuy.products('(search=ipod)', {show: 'sku,name,salePrice', page: 2, pageSize: 3, sort: 'sku.asc'})3 .then(function(data){4 console.log(data);5 })6 .catch(function(error){7 console.log(error);8 });

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Best automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful