Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Solve three exercises - Carlos Maldonado #198

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 32 additions & 3 deletions 01-basic-cs/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,17 @@ const assert = require('assert')

const database = require('./database.json')

const total = 0 // TODO
const total = _.chain(database)
.map(userFromDB => userFromDB.hats) // Get only the hats
.omitBy(_.isEmpty) // Remove empty array of hats
.values() // Get only the array of hats of every user instead of keys
.flatten() // Get only one array with all hats
.countBy('id') // Count how many of every hat has been purchased
.toPairs() // Convert ever object {id: count} to array [id, count]
.sortBy(hat => hat[1]) // sort by count (second element of every [id, count] array)
.takeRight(3) // Select first three elements
.sumBy(hat => hat[1]) // Sum the top three elements
.value()

// Throws error on failure
assert.equal(total, 23, `Invalid result: ${total} != 23`)
Expand All @@ -14,6 +24,25 @@ console.log('Success!')

/**
* Time and space complexity in O() notation is:
* - time complexity: TODO
* - space complexity: TODO
* - time complexity:
* The methods 'map', 'omitBy', 'flatten', 'countBy' and 'toPairs' have a
* time complexity of O(n) since the have to access every element of the array
* to apply their functions.
*
* The method 'sortBy' has a time complexity of O(n Log n) since it uses a special
* sorting algorithm
*
* the methods 'takeRight' and 'sumBy' have a time complexity of O(k), where k
* is the number of elements to operate.
*
* In conclusion, the time complexity of this algorithm depends on the length of
* the array in the database and the qantity of elements to take into account
* in the final sum. In general the time complexity is O(n Log n) due to the method
* 'sortBy', wich has the higher time complexity.
*
* - space complexity:
* In this case, the space complexity is O(n), where n is the number of elements
* in the database. This is because every operation in the chain returns a new array,
* and, in general (taking worst case scenario), the space required to store these arrays
* is proportional to the size of array in the database.
*/
22 changes: 21 additions & 1 deletion 02-nodejs/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,30 @@
const express = require('express')

const User = require('./models/User')
const { Transform } = require('stream')

// Setup Express.js app
const app = express()

// TODO: everything else
app.get('/users', (req, res) => {
const filename = 'users-db.csv'
const users = User.find().batchSize(30).cursor()

res.setHeader('Content-Disposition', `attachment; filename="${filename}"`)
res.setHeader('Content-Type', 'text/csv')

res.write('id, email, name\n')

const streamCSV = new Transform({
objectMode: true,
transform (user, _, done) {
const row = `${user.id},${user.email},${user.name}\n`
done(null, row)
}
})

streamCSV.pipe(res)
users.pipe(streamCSV)
})

app.listen(3000)
34 changes: 28 additions & 6 deletions 03-react/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions 03-react/src/App.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import React from 'react'
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import Exercise from './components/pages/Exercise'

Expand Down
124 changes: 70 additions & 54 deletions 03-react/src/components/pages/Exercise/index.js
Original file line number Diff line number Diff line change
@@ -1,45 +1,9 @@
import './assets/styles.css'
import { useState } from 'react'
import { React, useState } from 'react'
import { movies } from '../../../core/data/movies'
import { discountRules } from '../../../core/data/discounts'

export default function Exercise01 () {
const movies = [
{
id: 1,
name: 'Star Wars',
price: 20
},
{
id: 2,
name: 'Minions',
price: 25
},
{
id: 3,
name: 'Fast and Furious',
price: 10
},
{
id: 4,
name: 'The Lord of the Rings',
price: 5
}
]

const discountRules = [
{
m: [3, 2],
discount: 0.25
},
{
m: [2, 4, 1],
discount: 0.5
},
{
m: [4, 2],
discount: 0.1
}
]

const [cart, setCart] = useState([
{
id: 1,
Expand All @@ -48,27 +12,79 @@ export default function Exercise01 () {
quantity: 2
}
])
const ACTIONS = {
INCREMENT: 'INCREMENT',
DECREMENT: 'DECREMENT'
}

const getTotal = () => {
const moviesInCartIds = cart.map(movie => movie.id)
const discountRule = discountRules.find(rule => {
return rule.movieIds.length === moviesInCartIds.length && rule.movieIds.every(id => moviesInCartIds.includes(id))
})

const totalWithoutDiscount = cart.reduce((acc, movie) => acc + movie.price * movie.quantity, 0)
const total = discountRule ? totalWithoutDiscount * (1 - discountRule.discountPercentage) : totalWithoutDiscount

return total
}

const getMovieIndexFromCart = (id) => {
return cart.findIndex(movieInCart => movieInCart.id === id)
}

const getTotal = () => 0 // TODO: Implement this
const addMovieToCart = (movie) => {
const cartToSet = [...cart]
const existingMovieIndex = getMovieIndexFromCart(movie.id)

if (existingMovieIndex >= 0) {
cartToSet[existingMovieIndex].quantity++
} else {
cartToSet.push({
...movie,
quantity: 1
})
}
setCart(cartToSet)
}

const updateQuantity = (movieId, action) => {
const cartToUpdate = [...cart]
const movieIndexToUpdate = getMovieIndexFromCart(movieId)

switch (action) {
case ACTIONS.INCREMENT:
cartToUpdate[movieIndexToUpdate].quantity++
break
case ACTIONS.DECREMENT:
cartToUpdate[movieIndexToUpdate].quantity > 1
? cartToUpdate[movieIndexToUpdate].quantity--
: cartToUpdate.splice(movieIndexToUpdate, 1)
break
default:
break
}
setCart(cartToUpdate)
}

return (
<section className="exercise01">
<div className="movies__list">
<ul>
{movies.map(o => (
<li className="movies__list-card">
{movies.map(movie => (
<li className="movies__list-card" key={movie.id}>
<ul>
<li>
ID: {o.id}
ID: {movie.id}
</li>
<li>
Name: {o.name}
Name: {movie.name}
</li>
<li>
Price: ${o.price}
Price: ${movie.price}
</li>
</ul>
<button onClick={() => console.log('Add to cart', o)}>
<button onClick={() => addMovieToCart(movie)}>
Add to cart
</button>
</li>
Expand All @@ -77,27 +93,27 @@ export default function Exercise01 () {
</div>
<div className="movies__cart">
<ul>
{cart.map(x => (
<li className="movies__cart-card">
{cart.map(cartMovie => (
<li className="movies__cart-card" key={cartMovie.id}>
<ul>
<li>
ID: {x.id}
ID: {cartMovie.id}
</li>
<li>
Name: {x.name}
Name: {cartMovie.name}
</li>
<li>
Price: ${x.price}
Price: ${cartMovie.price}
</li>
</ul>
<div className="movies__cart-card-quantity">
<button onClick={() => console.log('Decrement quantity', x)}>
<button onClick={() => updateQuantity(cartMovie.id, ACTIONS.DECREMENT)}>
-
</button>
<span>
{x.quantity}
{cartMovie.quantity}
</span>
<button onClick={() => console.log('Increment quantity', x)}>
<button onClick={() => updateQuantity(cartMovie.id, ACTIONS.INCREMENT)}>
+
</button>
</div>
Expand Down
14 changes: 14 additions & 0 deletions 03-react/src/core/data/discounts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export const discountRules = [
{
movieIds: [3, 2],
discountPercentage: 0.25
},
{
movieIds: [2, 4, 1],
discountPercentage: 0.5
},
{
movieIds: [4, 2],
discountPercentage: 0.1
}
]
22 changes: 22 additions & 0 deletions 03-react/src/core/data/movies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export const movies = [
{
id: 1,
name: 'Star Wars',
price: 20
},
{
id: 2,
name: 'Minions',
price: 25
},
{
id: 3,
name: 'Fast and Furious',
price: 10
},
{
id: 4,
name: 'The Lord of the Rings',
price: 5
}
]
Loading