Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- JAVASCRIPT
- function applyBlackFriday(products, discount){
- return new Promise( (resolve, reject) => {
- if (isNaN(discount)) {
- reject(new Error('Invalid discount'));
- } else if (discount <= 0 || discount > 10) {
- reject(new Error('Discount not applicable'));
- }
- products.forEach(product => {
- if (product.name && typeof product.name === 'string' && product.price && typeof product.price === 'number') {
- product.price = (1 - discount/100) * product.price;
- } else {
- reject(new Error('Invalid array format'));
- }
- })
- resolve(products);
- })
- }
- function addTokens(input, tokens) {
- if (typeof input !== 'string') {
- throw new Error('Invalid input');
- }
- if (input.length < 6) {
- throw new Error(`Input should have at least 6 characters`);
- }
- tokens.forEach(tokenName => {
- if (typeof(tokenName) === 'string') {
- if (input.includes('...')) {
- input = input.replace('...', `${tokenName}`);
- }
- }
- else {
- throw new Error('Invalid array format');
- }
- });
- return input;
- }
- function applyDiscount(vehicles, discount) {
- return new Promise((resolve, reject) => {
- if (typeof discount !== 'number') {
- reject(new Error('Invalid discount'));
- }
- let lowestPrice = vehicles[0].price;
- for (let i = 0; i < vehicles.length; i++) {
- if (vehicles[i].price < lowestPrice) {
- lowestPrice = vehicles[i].price;
- }
- }
- lowestPrice = lowestPrice * (50 / 100);
- if (discount > lowestPrice) {
- reject('Discount too big');
- }
- vehicles.forEach(veh => {
- // if (veh && veh.name && typeof veh.name === 'string' && veh.price && typeof veh.price === 'number') {
- // veh.price = (1 - discount / 100) * veh.price;
- // }
- let obj = {
- name: ' ',
- price: 1
- }
- if (veh.isPrototypeOf(obj)) {
- veh.price = (1 - discount / 100) * veh.price;
- }
- else {
- reject(new Error('Invalid array format'));
- }
- })
- resolve(vehicles);
- });
- }
- //textprocessor
- alt model din seminar
- String.prototype.format = function(specs){
- let str = this.toString()
- if (specs){
- for (let prop in specs){
- str = str.replace('{' + prop + '}', specs[prop])
- }
- }
- return str
- }
- console.warn('i am a string with {a} and {b} params'.format({a : 'first', b : 'second'}))
- function translate(text, dictionary){
- if (typeof text !== 'string'){
- throw new Error('TypeError')
- }
- if (typeof dictionary !== 'object' || !dictionary){
- throw new Error('TypeError')
- }
- for (let prop in dictionary){
- if (typeof dictionary[prop] !== 'string'){
- throw new Error('TypeError')
- }
- }
- let result = text.split(' ')
- for (let prop in dictionary){
- let position = result.indexOf(prop)
- if (position !== -1){
- result[position] = dictionary[prop]
- }
- }
- return result.join(' ')
- }
- function capitalize(text, dictionary){
- if (typeof text !== 'string'){
- throw new Error('TypeError')
- }
- if (!Array.isArray(dictionary)){
- throw new Error('TypeError')
- }
- if (dictionary.filter((e) => typeof e !== 'string').length){
- throw new Error('TypeError')
- }
- let result = text
- let items = result.split(' ')
- for (let i = 0; i < items.length; i++){
- if (dictionary.indexOf(items[i]) !== -1){
- items[i] = items[i][0].toUpperCase() + items[i].slice(1, items[i].length)
- }
- }
- return items.join(' ')
- }
- /*
- Exista un tip obiectual definit (Bird)
- Să se definească tipul Penguin.
- Un pinguin este un tip copil pentru Bird și are în plus metoda swim(distance)
- Un pinguin nu poate fi creat fără un nume de tip string
- Un pinguin nu poate să zboare și va spune asta dacă i se cere
- Dacă se apelează makeNest, un pinguin va apela metoda părintelui său
- Vedeți testele pentru formatul exact al mesajelors
- */
- class Bird {
- constructor(name){
- this.name = name
- }
- fly(distance){
- return `${this.name} flies ${this.distance}`
- }
- makeNest(){
- return `${this.name} makes a nest`
- }
- }
- class Penguin extends Bird {
- constructor(name){
- if (!name || typeof name !== 'string'){
- throw new Error('CreationError')
- }
- super(name)
- }
- fly(distance){
- return `${this.name} is a penguin and cannot fly`
- }
- swim(distance){
- return `${this.name} swims ${distance}`
- }
- }
- /*
- Exista un tip obiectual definit (Widget)
- Funcția decorate adaugă la Widget o metodă numită enhance, care crește mărimea unui widget cu "n"
- Dacă parametrul trimis nu este un număr, se aruncă o excepție ("InvalidType")
- Metoda funcționează și asupra Widget-urilor deja declarate
- */
- class Widget {
- constructor(name, size){
- this.name = name
- this.size = size
- }
- getDescription(){
- return `a ${this.name} of size ${this.size}`
- }
- }
- function decorate(){
- Widget.prototype.enhance = function (n){
- if (typeof n !== 'number'){
- throw new Error("InvalidType")
- }
- this.size += n
- }
- }
- /*
- - funcția distance primește ca parametrii două array-uri
- - fiecare element poate apărea cel mult o dată într-un array
- - distanța dintre cele 2 array-uri este numărul de elemente diferite dintre ele
- - dacă parametrii nu sunt array-uri se va arunca o excepție ("InvalidType")
- */
- function distance(first, second){
- if (!Array.isArray(first) || !Array.isArray(second)){
- throw new Error('InvalidType')
- }
- let me = [...new Set(first)]
- let other = [...new Set(second)]
- let diffCount = 0
- for (let item of me){
- if (other.indexOf(item) === -1){
- diffCount++
- }
- else{
- other.splice(other.indexOf(item), 1)
- }
- }
- diffCount += other.length
- return diffCount
- }
- {
- "invoiceNumber": 1,
- "invoiceSeries": "ABCD",
- "invoiceItems": [{
- "productName": "Product 1",
- "quantity": 10,
- "productPrice": 10.00
- }, {
- "productName": "Product 2",
- "quantity": 10,
- "productPrice": 100.00
- }]
- }
- {
- "title": "Some article title",
- "abstract": "Some abstract here",
- "keywords": ["keyword1", "keyword2", "keyword3"],
- "authors": [{
- "fullName": "Author 1",
- "institution": "ASE",
- "email": "author1@example.com"
- }, {
- "fullName": "Author 2",
- "institution": "ASE",
- "email": "author2@example.com"
- }]
- }
- //SCHEMA
- let schema = {
- title: 'Article schema',
- type: 'object',
- required: ['title', 'abstract', 'keywords', 'authors'],
- properties: {
- title: {
- type: 'string'
- },
- abstract: {
- type: 'string'
- },
- keywords: {
- type: 'array',
- minItems: 3,
- items: {
- type: 'string'
- }
- },
- authors: {
- type: 'array',
- minItems: 2,
- items: {
- type: 'object',
- required: ['fullName', 'institution', 'email']
- }
- }
- }
- }
- describe("JSON", () => {
- describe("GET /article.json", () => {
- it('should return a valid json', (done) => {
- chai.request(app)
- .get('/article.json')
- .end((err, res) => {
- res.should.have.status(200);
- res.body.should.be.a('object');
- chai.assert.jsonSchema(res.body, schema)
- done();
- });
- })
- })
- });
- //
- {
- "name": "Some name title",
- "description": "Some description here",
- "sizes": [10, 12, 14],
- "price": 200,
- "inventory": [{
- "supplierName": "Some name",
- "quantity": 10,
- "aquisitionPrice": 100
- }, {
- "supplierName": "Some name",
- "quantity": 10,
- "aquisitionPrice": 100
- }]
- }
- {
- "accountHolder": "Some Name",
- "currentBalance": 100,
- "iban": "AABBSS",
- "currency": "RON",
- "transactions": [
- {
- "amount": 50,
- "transactionType": "IN",
- "beneficiaryName": "Some Name",
- "approved": false
- },
- {
- "amount": 50,
- "transactionType": "IN",
- "beneficiaryName": "Some Name",
- "approved": true
- }
- ]
- }
- {
- "name": "Some Name",
- "year": 3,
- "credits": 100,
- "superpowers": ["a", "b", "c"],
- "grades": [{
- "class": "Some class",
- "homeworkSubmitted": true,
- "examGrade": 5
- },{
- "class": "Some class",
- "homeworkSubmitted": false,
- "examGrade": 5
- }]
- }
- index html
- <!DOCTYPE html>
- <html>
- <head>
- <script>
- document.addEventListener('DOMContentLoaded', () => {
- fetch("path")
- .then( res => {
- return res.json();
- })
- .then(data => {
- let item = document.getElementById('myDiv');
- item.innerHTML = JSON.parse(data);
- })
- .catch(err => {
- console.warn(err);
- })
- });
- </script>
- </head>
- <body>
- <div id="myDiv"></div>
- </body>
- </html>
- SEQUELIZE
- var-0
- const express = require('express')
- const bodyParser = require('body-parser')
- const Sequelize = require('sequelize')
- const mysql = require('mysql2/promise')
- const DB_USERNAME = 'root'
- const DB_PASSWORD = 'welcome12#'
- mysql.createConnection({
- user : DB_USERNAME,
- password : DB_PASSWORD
- })
- .then(async (connection) => {
- await connection.query('DROP DATABASE IF EXISTS tw_exam')
- await connection.query('CREATE DATABASE IF NOT EXISTS tw_exam')
- })
- .catch((err) => {
- console.warn(err.stack)
- })
- const sequelize = new Sequelize('tw_exam', DB_USERNAME, DB_PASSWORD,{
- dialect : 'mysql',
- logging: false
- })
- // let Author = sequelize.define('author', {
- // name : Sequelize.STRING,
- // email : Sequelize.STRING,
- // address : Sequelize.STRING,
- // age : Sequelize.INTEGER
- // })
- const app = express()
- app.use(bodyParser.json())
- app.get('/create', async (req, res) => {
- try{
- await sequelize.sync({force : true})
- for (let i = 0; i < 10; i++){
- let author = new Author({
- name : 'name ' + i,
- email : 'name' + i + '@nowhere.com',
- address : 'some address on ' + i + 'th street'
- })
- await author.save()
- }
- res.status(201).json({message : 'created'})
- }
- catch(err){
- console.warn(err.stack)
- res.status(500).json({message : 'server error'})
- }
- })
- app.get('/authors', async (req, res) => {
- // should get all authors
- try{
- let authors = await Author.findAll()
- res.status(200).json(authors)
- }
- catch(err){
- // console.warn(err.stack)
- res.status(500).json({message : 'server error'})
- }
- })
- app.post('/authors', async (req, res) => {
- // should add an author
- // author names and emails cannot be empty
- // author addresses can be empty
- // author emails have to be valid
- try{
- let author = new Author(req.body)
- await author.save()
- res.status(201).json({message : 'created'})
- }
- catch(err){
- // console.warn(err.stack)
- res.status(500).json({message : 'server error'})
- }
- })
- app.listen(8080)
- module.exports = app
- ___________
- var-1
- const express = require('express')
- const bodyParser = require('body-parser')
- const Sequelize = require('sequelize')
- const mysql = require('mysql2/promise')
- const DB_USERNAME = 'root'
- const DB_PASSWORD = 'welcome12#'
- mysql.createConnection({
- user : DB_USERNAME,
- password : DB_PASSWORD
- })
- .then(async (connection) => {
- await connection.query('DROP DATABASE IF EXISTS tw_exam')
- await connection.query('CREATE DATABASE IF NOT EXISTS tw_exam')
- })
- .catch((err) => {
- console.warn(err.stack)
- })
- const sequelize = new Sequelize('tw_exam', DB_USERNAME, DB_PASSWORD,{
- dialect : 'mysql',
- logging: false
- })
- let Author = sequelize.define('author', {
- name : Sequelize.STRING,
- email : Sequelize.STRING,
- address : Sequelize.STRING,
- age : Sequelize.INTEGER
- },{
- timestamps : false
- })
- const app = express()
- app.use(bodyParser.json())
- app.get('/create', async (req, res) => {
- try{
- await sequelize.sync({force : true})
- for (let i = 0; i < 10; i++){
- let author = new Author({
- name : 'name ' + i,
- email : 'name' + i + '@nowhere.com',
- address : 'some address on ' + i + 'th street',
- age : 30 + i
- })
- await author.save()
- }
- console.warn('CREATED')
- res.status(201).json({message : 'created'})
- }
- catch(err){
- console.warn(err.stack)
- res.status(500).json({message : 'server error'})
- }
- })
- app.get('/authors', async (req, res) => {
- try{
- let authors = await Author.findAll()
- res.status(200).json(authors)
- }
- catch(err){
- // console.warn(err.stack)
- res.status(500).json({message : 'server error'})
- }
- })
- app.post('/authors', async (req, res) => {
- try{
- let author = new Author(req.body)
- await author.save()
- res.status(201).json({message : 'created'})
- }
- catch(err){
- // console.warn(err.stack)
- res.status(500).json({message : 'server error'})
- }
- })
- app.put('/authors/:id', async (req, res) => {
- // TODO: implementați funcția
- // adăugați o metoda pentru modificarea autorului
- // un autor inexistent nu poate fi modificat
- // numai câmpurile care sunt definite in request trebuie actualizate
- // add the method to modify an author
- // a non existant author cannot be updated
- // only defined fields should be updated
- try{
- let author = await Author.findById(req.params.id)
- if (!author){
- res.status(404).json({message : 'not found'})
- }
- else{
- author.name = req.body.name ? req.body.name : author.name
- author.email = req.body.email ? req.body.email : author.email
- author.address = req.body.address ? req.body.address : author.address
- author.age = req.body.age ? req.body.age : author.age
- await author.save()
- res.status(202).json({message : 'accepted'})
- }
- }
- catch(err){
- // console.warn(err.stack)
- res.status(500).json({message : 'server error'})
- }
- })
- app.delete('/authors/:id', async (req, res) => {
- // add the method to delete an author
- // a non existant author cannot be deleted
- try{
- let author = await Author.findById(req.params.id)
- if (!author){
- res.status(404).json({message : 'not found'})
- }
- else{
- await author.destroy()
- res.status(202).json({message : 'accepted'})
- }
- }
- catch(err){
- // console.warn(err.stack)
- res.status(500).json({message : 'server error'})
- }
- })
- app.listen(8080)
- module.exports = app
- __________________
- var-2
- const express = require('express')
- const bodyParser = require('body-parser')
- const Sequelize = require('sequelize')
- const mysql = require('mysql2/promise')
- const DB_USERNAME = 'root'
- const DB_PASSWORD = 'welcome12#'
- mysql.createConnection({
- user : DB_USERNAME,
- password : DB_PASSWORD
- })
- .then(async (connection) => {
- await connection.query('DROP DATABASE IF EXISTS tw_exam')
- await connection.query('CREATE DATABASE IF NOT EXISTS tw_exam')
- })
- .catch((err) => {
- console.warn(err.stack)
- })
- const sequelize = new Sequelize('tw_exam', DB_USERNAME, DB_PASSWORD,{
- dialect : 'mysql',
- logging: false
- })
- let Author = sequelize.define('author', {
- name : Sequelize.STRING,
- email : Sequelize.STRING,
- address : Sequelize.STRING,
- age : Sequelize.INTEGER
- })
- const app = express()
- app.use(bodyParser.json())
- app.get('/create', async (req, res) => {
- try{
- await sequelize.sync({force : true})
- for (let i = 0; i < 10; i++){
- let author = new Author({
- name : 'name ' + i,
- email : 'name' + i + '@nowhere.com',
- address : 'some address on ' + i + 'th street'
- })
- await author.save()
- }
- res.status(201).json({message : 'created'})
- }
- catch(err){
- console.warn(err.stack)
- res.status(500).json({message : 'server error'})
- }
- })
- app.get('/authors', async (req, res) => {
- // TODO: adăugați funcția pentru cererea listei autorilor
- // ar trebui să trimită clientului lista autorilor
- // ar trebui să permită paginare cu un număr de pagina pageNo și o mărime de pagină pageSize trimiși prin query
- // TODO: add the function to get all authors
- // should get all authors
- // should allow for pagination with a pageNo and a pageSize possibly sent as query parameters
- try{
- let pageSize = parseInt(req.query.pageSize)
- pageSize = pageSize ? parseInt(req.query.pageSize) : 5
- let authors
- let pageNo = parseInt(req.query.pageNo)
- if (pageNo){
- authors = await Author.findAll({
- offset : pageNo * pageSize,
- limit : pageSize
- })
- }
- else{
- authors = await Author.findAll()
- }
- res.status(200).json(authors)
- }
- catch(err){
- console.warn(err.stack)
- res.status(500).json({message : 'server error'})
- }
- })
- app.post('/authors', async (req, res) => {
- try{
- let author = new Author(req.body)
- await author.save()
- res.status(201).json({message : 'created'})
- }
- catch(err){
- // console.warn(err.stack)
- res.status(500).json({message : 'server error'})
- }
- })
- app.listen(8080)
- module.exports = app
- ________
- var-3
- const express = require('express')
- const bodyParser = require('body-parser')
- const Sequelize = require('sequelize')
- const Op = Sequelize.Op
- const mysql = require('mysql2/promise')
- const DB_USERNAME = 'root'
- const DB_PASSWORD = 'welcome12#'
- mysql.createConnection({
- user : DB_USERNAME,
- password : DB_PASSWORD
- })
- .then(async (connection) => {
- await connection.query('DROP DATABASE IF EXISTS tw_exam')
- await connection.query('CREATE DATABASE IF NOT EXISTS tw_exam')
- })
- .catch((err) => {
- console.warn(err.stack)
- })
- const sequelize = new Sequelize('tw_exam', DB_USERNAME, DB_PASSWORD,{
- dialect : 'mysql',
- logging: false
- })
- let Author = sequelize.define('author', {
- name : Sequelize.STRING,
- email : Sequelize.STRING,
- address : Sequelize.STRING,
- age : Sequelize.INTEGER
- })
- const app = express()
- app.use(bodyParser.json())
- app.get('/create', async (req, res) => {
- try{
- await sequelize.sync({force : true})
- for (let i = 0; i < 10; i++){
- let author = new Author({
- name : 'name ' + i,
- email : 'name' + i + '@nowhere.com',
- address : 'some address on ' + i + 'th street'
- })
- await author.save()
- }
- res.status(201).json({message : 'created'})
- }
- catch(err){
- console.warn(err.stack)
- res.status(500).json({message : 'server error'})
- }
- })
- app.get('/authors', async (req, res) => {
- // TODO: implement the function
- // should get all authors
- // should allow for filtering based on address and email (filters are called address and email and are sent as query parameters)
- try{
- let addressFilter = req.query.address
- let emailFilter = req.query.email
- let query = {where : {}}
- if (addressFilter){
- query.where.address = {
- [Op.like] : `%${addressFilter}%`
- }
- }
- if (emailFilter){
- query.where.email = {
- [Op.like] : `%${emailFilter}%`
- }
- }
- let authors = await Author.findAll(query)
- res.status(200).json(authors)
- }
- catch(err){
- console.warn(err.stack)
- res.status(500).json({message : 'server error'})
- }
- })
- app.post('/authors', async (req, res) => {
- try{
- let author = new Author(req.body)
- await author.save()
- res.status(201).json({message : 'created'})
- }
- catch(err){
- // console.warn(err.stack)
- res.status(500).json({message : 'server error'})
- }
- })
- app.listen(8080)
- module.exports = app
- var-4
- const express = require('express')
- const bodyParser = require('body-parser')
- const Sequelize = require('sequelize')
- const mysql = require('mysql2/promise')
- const DB_USERNAME = 'root'
- const DB_PASSWORD = 'welcome12#'
- mysql.createConnection({
- user : DB_USERNAME,
- password : DB_PASSWORD
- })
- .then(async (connection) => {
- await connection.query('DROP DATABASE IF EXISTS tw_exam')
- await connection.query('CREATE DATABASE IF NOT EXISTS tw_exam')
- })
- .catch((err) => {
- console.warn(err.stack)
- })
- const sequelize = new Sequelize('tw_exam', DB_USERNAME, DB_PASSWORD,{
- dialect : 'mysql',
- logging: false,
- define: {
- timestamps: false
- },
- })
- let Author = sequelize.define('author', {
- name : Sequelize.STRING,
- email : Sequelize.STRING,
- address : Sequelize.STRING,
- age : Sequelize.INTEGER
- })
- let Book = sequelize.define('book', {
- title : Sequelize.STRING,
- pages : Sequelize.INTEGER
- })
- Author.hasMany(Book)
- const app = express()
- app.use(bodyParser.json())
- app.get('/create', async (req, res) => {
- try{
- await sequelize.sync({force : true})
- for (let i = 0; i < 10; i++){
- let author = new Author({
- name : 'name ' + i,
- email : 'name' + i + '@nowhere.com',
- address : 'some address on ' + i + 'th street'
- })
- await author.save()
- }
- res.status(201).json({message : 'created'})
- }
- catch(err){
- console.warn(err.stack)
- res.status(500).json({message : 'server error'})
- }
- })
- app.get('/authors', async (req, res) => {
- // should get all authors
- try{
- let authors = await Author.findAll()
- res.status(200).json(authors)
- }
- catch(err){
- console.warn(err.stack)
- res.status(500).json({message : 'server error'})
- }
- })
- app.post('/authors', async (req, res) => {
- try{
- let author = new Author(req.body)
- await author.save()
- res.status(201).json({message : 'created'})
- }
- catch(err){
- // console.warn(err.stack)
- res.status(500).json({message : 'server error'})
- }
- })
- app.post('/authors/:id/books', async (req, res) => {
- // should add a book to an author
- try{
- let author = await Author.findById(req.params.id)
- if (author){
- let book = req.body
- book.authorId = author.id
- await Book.create(book)
- res.status(201).json({message : 'created'})
- }
- else{
- res.status(404).json({message : 'not found'})
- }
- }
- catch(e){
- console.warn(e)
- res.status(500).json({message : 'server error'})
- }
- })
- app.get('/authors/:id/books', async (req, res) => {
- // should list all of an authors' books
- try{
- let author = await Author.findById(req.params.id, {include : [Book]})
- if (author){
- let books = author.books
- res.status(200).json(books)
- }
- else{
- res.status(404).json({message : 'not found'})
- }
- }
- catch(e){
- console.warn(e)
- res.status(500).json({message : 'server error'})
- }
- })
- app.listen(8080)
- module.exports = app
- var-9
- app.post('/cars', (req, res, next) => {
- if (req.body.constructor === Object && Object.keys(req.body).length === 0) {
- res.status(500).json({ message: 'Body is missing' });
- }
- else {
- if (req.body.make && req.body.model && req.body.price) {
- if (req.body.price > 0) {
- let doesExist = false;
- app.locals.cars.forEach(car => {
- if (car.model == req.body.model) {
- doesExist = true;
- }
- });
- if (doesExist) {
- res.status(500).json({ message: 'Car already exists' });
- }
- else {
- let newCar = {
- make: req.body.make,
- model: req.body.model,
- price: req.body.price
- }
- app.locals.cars.push(newCar);
- res.status(201).json({ message: 'Created' });
- }
- }
- else {
- res.status(500).json({ message: 'Price should be a positive number' });
- }
- }
- else {
- res.status(500).json({ message: 'Invalid body format' });
- }
- }
- })
- var-0 REACT-EXAMPLE
- // TODO : adăugați o componentă Robot
- // afișați o componentă Robot pentru fiecare robot din stare
- // o componentă robot ar trebui să afișeze un robot și să permită ștergerea lui
- // TODO : add a Robot component
- // show a Robot component for each robot in the state
- // a robot component should show a robot and allow deletion of a robot
- class Robot extends Component {
- render() {
- let {item} = this.props
- return (
- <div>
- Hello, my name is {item.name}. I am a {item.type} and weigh {item.mass}
- <input type="button" value="delete" onClick={() => this.props.onDelete(item.id)} />
- </div>
- )
- }
- }
- export default Robot
- class RobotList extends Component {
- constructor(){
- super()
- this.state = {
- robots : []
- }
- this.deleteRobot = (id) => {
- this.store.deleteRobot(id)
- }
- }
- componentDidMount(){
- this.store = new RobotStore()
- this.setState({
- robots : this.store.getRobots()
- })
- this.store.emitter.addListener('UPDATE', () => {
- this.setState({
- robots : this.store.getRobots()
- })
- })
- }
- render() {
- // a robot component should show a robot and allow deletion of a robot
- return (
- <div>
- {
- this.state.robots.map((e, i) =>
- <Robot item={e} key={i} onDelete={this.deleteRobot} />
- )
- }
- </div>
- )
- }
- }
- export default RobotList
- import React, { Component } from 'react'
- import RobotList from './RobotList'
- class App extends Component {
- render() {
- return (
- <div>
- A list of robots
- <RobotList />
- </div>
- )
- }
- }
- export default App
- __________________________________________________________________________
- var-1 REACT-EXAMPLE
- // TODO : adăugați o componentă RobotForm
- // RobotForm ar să permită adăugarea unui robot
- // TODO : add a RobotForm component
- // RobotForm should be able to add a robot
- class RobotForm extends Component {
- constructor(props){
- super(props)
- this.state = {
- type : '',
- name : '',
- mass : ''
- }
- this.handleChange = (evt) => {
- this.setState({
- [evt.target.name] : evt.target.value
- })
- }
- }
- render() {
- return (
- <div>
- <label htmlFor="type">Type</label>
- <input type="text" id="type" name="type" onChange={this.handleChange} />
- <label htmlFor="name">Name</label>
- <input type="name" id="name" name="name" onChange={this.handleChange} />
- <label htmlFor="mass">Mass</label>
- <input type="text" id="mass" name="mass" onChange={this.handleChange} />
- <input type="button" value="add" onClick={() => this.props.onAdd({
- name : this.state.name,
- type : this.state.type,
- mass : this.state.mass
- })} />
- </div>
- )
- }
- }
- import React, { Component } from 'react'
- import RobotStore from '../stores/RobotStore'
- import Robot from './Robot'
- import RobotForm from './RobotForm'
- class RobotList extends Component {
- // add a form to allow adding robots
- constructor(){
- super()
- this.state = {
- robots : []
- }
- this.addRobot = (robot) => {
- this.store.addRobot(robot)
- }
- }
- componentDidMount(){
- this.store = new RobotStore()
- this.setState({
- robots : this.store.getRobots()
- })
- this.store.emitter.addListener('UPDATE', () => {
- this.setState({
- robots : this.store.getRobots()
- })
- })
- }
- render() {
- return (
- <div>
- {
- this.state.robots.map((e, i) =>
- <Robot item={e} key={i} />
- )
- }
- <RobotForm onAdd={this.addRobot} />
- </div>
- )
- }
- }
- export default RobotList
- __________________________________________________________________________
- var-2 REACT-EXAMPLE
- // TODO : adăugați posibilitatea de a edita un robot
- // editarea se face prin intermediul unui robot cu 2 stări, una de vizualizare și una de editare
- // TODO : add the posibility to edit a robot
- // editing is done via 2 states a view state and an edit state
- import React, { Component } from 'react'
- class Robot extends Component {
- constructor(props){
- super(props)
- let {item} = this.props
- this.state = {
- name : item.name,
- type : item.type,
- mass : item.mass,
- isEditing : false
- }
- this.handleChange = (evt) => {
- this.setState({
- [evt.target.name] : evt.target.value
- })
- }
- }
- render() {
- let {item} = this.props
- if (this.state.isEditing){
- return (
- <div>
- Hello, my name is
- <input type="text" id="type" name="type" onChange={this.handleChange} value={this.state.type} />
- . I am a
- <input type="text" id="name" name="name" onChange={this.handleChange} value={this.state.name} />
- and weigh
- <input type="text" id="mass" name="mass" onChange={this.handleChange} value={this.state.mass} />
- <input type="button" value="save" onClick={() => {
- this.props.onSave(item.id, {
- name : this.state.name,
- type : this.state.type,
- mass : this.state.mass
- })
- this.setState({isEditing : false})
- }
- } />
- <input type="button" value="cancel" onClick={() => this.setState({isEditing : false})} />
- </div>
- )
- }
- else{
- return (
- <div>
- Hello, my name is {item.name}. I am a {item.type} and weigh {item.mass}
- <input type="button" value="edit" onClick={() => this.setState({isEditing : true})} />
- </div>
- )
- }
- }
- }
- export default Robot
- __________________________________________________________________________
- var-3 REACT-EXAMPLE
- // TODO : adăugați posibilitatea de a vizualiza detaliile unui robot
- // RobotList are 2 stări una de detalii și una de listă
- // se poate trece în starea de detalii printr-un buton pe fiecare robot
- // se poate trece înapoi la listă printr-un buton de anulare
- // TODO : add the posibility to view a robot's details
- // RobotList has 2 states, one for details for a robot and one for the full list of robots
- // passing to the details state is done with a button on each robot
- // returning tothe list is done with a cancel button
- import React, { Component } from 'react'
- class Robot extends Component {
- render() {
- let {item} = this.props
- return (
- <div>
- Hello, my name is {item.name}. I am a {item.type} and weigh {item.mass}
- <input type="button" value="select" onClick={() => this.props.onSelect(item.id)} />
- </div>
- )
- }
- }
- export default Robot
- import React, { Component } from 'react'
- import RobotStore from '../stores/RobotStore'
- import Robot from './Robot'
- import RobotDetails from './RobotDetails'
- class RobotList extends Component {
- constructor(){
- super()
- this.state = {
- robots : [],
- selected : null
- }
- this.selectRobot = (id) => {
- this.store.selectRobot(id)
- }
- this.cancelSelection = () => {
- this.setState({
- selected : null
- })
- }
- }
- componentDidMount(){
- this.store = new RobotStore()
- this.setState({
- robots : this.store.getRobots()
- })
- this.store.emitter.addListener('UPDATE', () => {
- this.setState({
- robots : this.store.getRobots(),
- selected : this.store.getSelected()
- })
- })
- }
- render() {
- // a robot component should show a robot and allow deletion of a robot
- if (this.state.selected){
- return (
- <RobotDetails item={this.state.selected} onCancel={this.cancelSelection} />
- )
- }
- else{
- return (
- <div>
- {
- this.state.robots.map((e, i) =>
- <Robot item={e} key={i} onSelect={this.selectRobot} />
- )
- }
- </div>
- )
- }
- }
- }
- export default RobotList
- import React, { Component } from 'react'
- class RobotDetails extends Component {
- render() {
- let {item} = this.props
- return (
- <div>
- Details for {item.name}
- <input type="button" value="cancel" onClick={() => this.props.onCancel()} />
- </div>
- )
- }
- }
- export default RobotDetails
- __________________________________________________________________________
- var-4 REACT-EXAMPLE
- // TODO: adăugați posibilitatea de a filtra roboții după name și type
- // filtrarea se face pe baza a 2 text input-uri și se produce la fiecare tastă apăsată
- // TODO: add the possiblity to filter robots according to name and type
- // filtering is done via 2 text inputs and happens whenever a key is pressed
- import React, { Component } from 'react'
- import RobotStore from '../stores/RobotStore'
- import Robot from './Robot'
- class RobotList extends Component {
- constructor(){
- super()
- this.state = {
- robots : [],
- nameFilter : '',
- typeFilter : ''
- }
- this.handleChange = (evt) => {
- this.setState({
- [evt.target.name] : evt.target.value
- })
- }
- }
- componentDidMount(){
- this.store = new RobotStore()
- this.setState({
- robots : this.store.getRobots()
- })
- this.store.emitter.addListener('UPDATE', () => {
- this.setState({
- robots : this.store.getRobots()
- })
- })
- }
- render() {
- // a robot component should show a robot and allow deletion of a robot
- let robots = this.state.robots.filter((e) => e.name.indexOf(this.state.nameFilter) !== -1).filter((e) => e.type.indexOf(this.state.typeFilter) !== -1)
- return (
- <div>
- <div>
- <input type="text" value={this.state.filter} onChange={this.handleChange} name="nameFilter" id="nameFilter" />
- <input type="text" value={this.state.filter} onChange={this.handleChange} name="typeFilter" id="typeFilter" />
- </div>
- {
- robots.map((e, i) =>
- <Robot item={e} key={i} />
- )
- }
- </div>
- )
- }
- }
- export default RobotList
- __________________________________________________________________________
- var-9 REACT-EXAMPLE
- COUPON
- import React from 'react';
- class AddCoupon extends React.Component {
- constructor(props) {
- super(props);
- this.state = {
- category: '',
- discount: '',
- availability: ''
- };
- }
- addCoupon = () => {
- let coupon = {
- category: this.state.category,
- discount: this.state.discount,
- availability: this.state.availability
- };
- this.props.onAdd(coupon);
- }
- onChange = (e) => {
- this.setState({
- [e.target.name]:e.target.value
- })
- }
- render() {
- return (
- <div>
- <input type="text" id="category" name="category" placeholder="Category" value={this.state.category} onChange={this.onChange.bind(this)}/>
- <input type="text" id="discount" name="discount" placeholder="Discount" value={this.state.discount} onChange={this.onChange.bind(this)}/>
- <input type="text" id="availability" name="availability" placeholder="Availability" value={this.state.availability} onChange={this.onChange.bind(this)}/>
- <input type="button" value="add coupon" onClick={this.addCoupon.bind(this)}/>
- </div>
- )
- }
- }
- export default AddCoupon;
- import React from 'react';
- import AddCoupon from './AddCoupon';
- class CouponList extends React.Component {
- constructor(){
- super();
- this.state = {
- coupons: []
- };
- }
- onAddCoupon = (coupon) => {
- let temp = this.state.coupons;
- temp.push(coupon);
- this.setState({
- coupons: temp
- });
- }
- render() {
- let items = this.state.coupons.map((item, index) => {
- return <li key={index}>{item.category}</li>
- });
- return (
- <div>
- <AddCoupon onAdd={this.onAddCoupon.bind(this)}/>
- <ul>
- {items}
- </ul>
- </div>
- )
- }
- }
- export default CouponList;
- import React, { Component } from 'react';
- import CouponList from './CouponList';
- class App extends Component {
- render() {
- return (
- <div>
- <CouponList/>
- </div>
- );
- }
- }
- export default App;
- //1
- <!DOCTYPE html>
- <html>
- <head>
- <title>var - 0</title>
- <link rel="stylesheet" type="text/css" href="main.css">
- </head>
- <body>
- <div class="main">
- <div class="sidebar">
- <div class="sidebar-item">1</div>
- <div class="sidebar-item">2</div>
- <div class="sidebar-item">3</div>
- <div class="sidebar-item">4</div>
- </div>
- <div class="view">
- <div class="top">top</div>
- <div class="bottom">bottom</div>
- </div>
- </div>
- </body>
- </html>
- *{
- box-sizing: border-box;
- border : 1px solid black;
- margin : 0px;
- padding: 0px;
- font-size: xx-large;
- }
- .main{
- display : grid;
- width: 80vw;
- height: 80vh;
- text-align: center;
- line-height: 100%;
- grid-template-columns: 20vw 60vw;
- grid-template-rows: 80vh;
- grid-template-areas:
- "sidebar view"
- ;
- }
- .sidebar{
- grid-area : sidebar;
- }
- .sidebar-item{
- height : 20vh;
- }
- .view{
- grid-area : view;
- }
- .top{
- height : 20vh;
- }
- .bottom{
- height : 60vh;
- }
- //2
- <!DOCTYPE html>
- <html>
- <head>
- <title>var - 0</title>
- <link rel="stylesheet" type="text/css" href="main.css">
- </head>
- <body>
- <div class="main">
- <div class="first">1</div>
- <div class="second">2</div>
- <div class="third">3</div>
- <div class="fourth">4</div>
- <div class="fifth">5</div>
- <div class="sixth">6</div>
- </div>
- </body>
- </html>
- *{
- box-sizing: border-box;
- border : 1px solid black;
- margin : 0px;
- padding: 0px;
- font-size: xx-large;
- }
- .main{
- display : grid;
- width: 60vw;
- height: 30vh;
- text-align: center;
- line-height: 100%;
- grid-template-columns: 10vw 10vw 10vw 10vw 10vw 10vw;
- grid-template-rows: 10vh 10vh 10vh;
- grid-template-areas:
- ". first first second second ."
- "sixth sixth . . third third"
- ". fifth fifth fourth fourth ."
- ;
- }
- .first{
- grid-area : first;
- }
- .second{
- grid-area : second;
- }
- .third{
- grid-area : third;
- }
- .fourth{
- grid-area : fourth;
- }
- .fifth{
- grid-area : fifth;
- }
- .sixth{
- grid-area : sixth;
- }
- //3
- <!DOCTYPE html>
- <html>
- <head>
- <title>var - 0</title>
- <link rel="stylesheet" type="text/css" href="main.css">
- </head>
- <body>
- <div class="main">
- <div class="header">header</div>
- <div class="column">
- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
- </div>
- <div class="column">
- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
- </div>
- <div class="column">
- Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
- </div>
- </div>
- </body>
- </html>
- *{
- box-sizing: border-box;
- border : 1px solid black;
- margin : 0px;
- padding: 0px;
- font-size: xx-large;
- }
- .main{
- display : grid;
- width: 100%;
- height: 100%;
- grid-template-columns: 33.33% 33.33% 33.33%;
- grid-template-rows: 100%;
- grid-template-areas:
- "first second third"
- ;
- }
- .header{
- height:20vh;
- width:100%;
- background-color: yellow;
- position: fixed;
- top:0px;
- }
- .column{
- float:left;
- }
- //4
- <!DOCTYPE html>
- <html>
- <head>
- <title>var - 0</title>
- <link rel="stylesheet" type="text/css" href="main.css">
- </head>
- <body>
- <div class="main">
- </div>
- </body>
- </html>
- *{
- box-sizing: border-box;
- border : 1px solid black;
- margin : 0px;
- padding: 0px;
- font-size: xx-large;
- }
- .main{
- display : grid;
- width: 80vw;
- height: 80vh;
- max-width:100%;
- max-height:100%;
- grid-template-columns: 20vw 60vw;
- grid-template-rows: 80vh;
- grid-template-areas:
- "sidebar view"
- ;
- }
- .sidebar{
- grid-area : sidebar;
- }
- .sidebar-item{
- height : 20vh;
- }
- .view{
- grid-area : view;
- }
- .top{
- height : 20vh;
- }
- .bottom{
- height : 60vh;
- }
- //6
- <!DOCTYPE html>
- <html>
- <head>
- <title>var - 0</title>
- <link rel="stylesheet" type="text/css" href="main.css">
- </head>
- <body>
- <div class="main">
- <div class="sidebar">
- <div class="sidebar-item">1</div>
- <div class="sidebar-item">2</div>
- <div class="sidebar-item">3</div>
- <div class="sidebar-item">4</div>
- </div>
- <div class="view">
- <div class="top">top</div>
- <div class="bottom">bottom</div>
- </div>
- </div>
- </body>
- </html>
- *{
- box-sizing: border-box;
- border : 1px solid black;
- margin : 0px;
- padding: 0px;
- font-size: xx-large;
- }
- .main{
- display : grid;
- width: 80vw;
- height: 80vh;
- max-width:100%;
- max-height:100%;
- grid-template-columns: 20vw 60vw;
- grid-template-rows: 80vh;
- grid-template-areas:
- "sidebar view"
- ;
- }
- .sidebar{
- grid-area : sidebar;
- }
- .sidebar-item{
- height : 20vh;
- }
- .view{
- grid-area : view;
- }
- .top{
- height : 20vh;
- }
- .bottom{
- height : 60vh;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement