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

New index.js for tiny js task #258

Merged
merged 8 commits into from
Aug 25, 2022
Merged

New index.js for tiny js task #258

merged 8 commits into from
Aug 25, 2022

Conversation

Levi123
Copy link
Contributor

@Levi123 Levi123 commented Aug 22, 2022

a Tiny JS world

Demo |
Code base

The code is submitted in a dedicated feature branch.

Only code files are submitted.

Please, review.

@github-actions
Copy link

Hey!

Congratulations on your PR! 😎😎😎

Let's do some self-checks to fix most common issues and to make some improvements to the code before reviewers put their hands on the code.

Go through the requirements/most common mistakes listed/linked below and fix the code as appropriate.

If you have any questions to requirements/common mistakes feel free asking them here or in Students' chat.

When you genuinely believe you are done put a comment stating that you have completed self-checks and fixed code accordingly.

Also, be aware, that if you would silently ignore this recommendation, a mentor can think that you are still working on fixes. And your PR will not be reviewed. 😒

A Tiny JS World -- (pre-OOP) exercise check list

Relates to Object-Oriented JavaScript task.

Check-list - definition of done

  • Code is DRY, which means that whenever you see a pattern in your code those should be eliminated as much as possible. Examples:
    • print(dog); print(cat); etc ... should be refactored employing Array.forEach as the least
    • `${obj.legs}; ${obj.name}; etc...` (yes, strings are also code) must be refactored employing appropriate Array methods
  • Object methods like keys, values, entries shouldn't be used when a particular order is required as these do not guarantee any particular order of keys/values. Same refers to for...of and for...in when applied to objects.
    Hint: List explicitly the properties used to form an object presentation string.
  • Men and women belong to the same biological species.
  • ES6 class or prototype-based OO syntax aren't used.

Universal recommendations:

  • Give variables and functions meaningful names. Avoid generic names like item, element, key, object, array or their variations. Exception: helper functions that are specifically and intentionally designed to be multipurpose.
  • Function names should start with a verb as they denote actions; variables are normally nouns; boolean variables/functions start with is, does, has etc; variable containing multiple entities and functions returning lists contain entity name in plural form.
  • Have consistent code style and formatting. Employ Prettier to do all dirty work for you.
  • Use common sense or seek for an advice whenever requirements look ambiguous or unclear.

Also take a note of the requirements above and follow them in all your future projects.

Sincerely yours,
Submissions Kottachecker 😺

@Levi123
Copy link
Contributor Author

Levi123 commented Aug 22, 2022

привіт!

Вітаю з піаром!😎😎😎

Зробіть кілька самоперевірок, щоб виправити найпоширеніші проблеми та внести деякі покращення в код, ніж перші рецензенти візьмуть участь у коді.

Перегляньте вимоги/найбільш розширені помилки, перелічені/за посиланнями нижче, і виправте код відповідно.

Якщо у вас є запит щодо вимог/типових помилок , не соромтеся поставити їх тут або в чаті студентів.

Коли ви справді вважаєте, що закінчили, додайте коментар, у якому показано, що виконали самоперевірку та відповідно виправили код.

Також майте на увазі, що якщо ви мовчки проігноруєте цю рекомендацію, наставник може подумати, що ви все будете працювати над виправленнями. І ваш піар не буде переглянуто.😒

A Tiny JS World -- контрольний список вправ (до ООП).

Відноситься до об'єктно-орієнтованого завдання JavaScript.

Чек-лист – визначення зробленого

  • Код є DRY , що означає, що коли ви бачите шаблон у своєму коді, його слід максимально усунути. приклади:

    • print(dog); print(cat); etc ... має бути перероблено, використовуючи Array.forEachяк мінімум
    • `${obj.legs}; ${obj.name}; etc...`(так, рядки також є кодом) необхідно відредагувати за допомогою відповідних Arrayметодів
  • Objectтакі методи, як keys, values, entriesне слід використовувати, коли потрібен певний порядок, після чого вони не гарантують певного порядку ключів/значень. Те саме призначають об'єкти for...ofі for...inв заявці до них.
    Підказка: явно вкажіть властивості, які використані для формування ряду представлення об'єкта.

  • Чоловіки і жінки належать до одного біологічного виду.

  • Синтаксис OO на основі ES6 classабо prototypeOO не використовується.

Універсальні рекомендації:

  • Дайте змінним і функціям осмислені імена. Уникайте загальних назв, таких як item, element, key, objectабо arrayїхніх варіацій. Віняток: допоміжні функції, які спеціально та навмисно розроблені як багатоцільові.
  • Назви функцій повинні починатися з дієслова, після чого вони позначають дії; змінні попередні є іменниками; логічні зміни/функції починаються з is, doesetc has; змінна, що містить кілька сутностей, і функції, що повертають списки, містять назву сутності у формі множини.
  • Майте наступний стиль і форматування коду. Наймайте Prettier , щоб зберегти всю брудну роботу за вас.
  • Використовуйте здоровий глузд або шукайте поради, коли вимоги виглядають неоднозначними або незрозумілими.

Також візьміть до уваги наведені вище вимоги та дотримуйтесь їх у всіх своїх майбутніх проектах.

_З повагою, _ Submissions Kottachecker 😺

Опрацьовано

Copy link
Member

@OleksiyRudenko OleksiyRudenko left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Levi123 please go through the check list once again. I figured at least two requirements not met.

Feel free asking questions if anything is not clear.

Comment on lines 68 to 75
function printObject(object){
const prop = [];
for (element in object){
prop.push(object[element]);
}
let newStr = prop.join('; ');
print(newStr);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Give variables and functions meaningful names. Avoid generic names like item, element, key, object, array or their variations. Exception: helper functions that are specifically and intentionally designed to be multipurpose.
  • Object methods like keys, values, entries shouldn't be used when a particular order is required as these do not guarantee any particular order of keys/values. Same refers to for...of and for...in when applied to objects.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Give variables and functions meaningful names. Avoid generic names like item, element, key, object, array or their variations. Exception: helper functions that are specifically and intentionally designed to be multipurpose.
  • Object methods like keys, values, entries shouldn't be used when a particular order is required as these do not guarantee any particular order of keys/values. Same refers to for...of and for...in when applied to objects.

I don't understand second point of your massage, i can't use (for...in) at all? and why?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Q: I can't use (for...in) at all? and why?

A: As per explanation above "...when a particular order is required as these do not guarantee any particular order of keys/values."

Only arrays guarantee order of elements.

As a peer developer, knowing that in objects order of keys is not important I can define new objects with properties in different order. It would be great if this didn't affect the code.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Q: I can't use (for...in) at all? and why?

A: As per explanation above "...when a particular order is required as these do not guarantee any particular order of keys/values."

Only arrays guarantee order of elements.

As a peer developer, knowing that in objects order of keys is not important I can define new objects with properties in different order. It would be great if this didn't affect the code.

I try to change my errors.

Copy link
Member

@OleksiyRudenko OleksiyRudenko left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Levi123 good improvement.
Still further improvements are needed.

Comment on lines 71 to 76
const propToPrint = [];
prop.forEach((propOfObj) => {
propToPrint.push(personToPrint[propOfObj]);
})
let newStr = propToPrint.join('; ');
print(newStr);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Think of converting property names into object's property values, then joining with '; '.
Make the method return the result. Currently it does two jobs: (1) convert data, (b) produce output, which doesn't really follow Separatoin of Concerns principles.

Use Array.map method to convert data.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@OleksiyRudenko did I understand correctly, I need to split this function into several?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should use print inside this method. You can call print in a fragment of code where you want the output to happen in. And this function will do a single job - transformation of data. You will end up with a one-liner here.

Copy link
Member

@OleksiyRudenko OleksiyRudenko Aug 25, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Levi123 while looking through your updated code version I started wondering why is it so.

I am sorry, I apparently missed one very important word here. The comment above should read

You should not use print inside this method.

My apologies. We will fix this.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Levi123переглядаючи вашу оновлену версію коду, я почав дивуватися, чому це так.

Вибачте, я, мабуть, пропустив тут одне дуже важливе слово. Коментар вище має прочитати

Ви не повинні використовувати всередині printцей метод.

Мої вибачення. Ми це виправимо.

i don't understand you

Comment on lines 94 to 98
printObjectNew(catWoman);
printObjectNew(male);
printObjectNew(female);
printObjectNew(cat);
printObjectNew(dog);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From the checklist above in the thread:

  • Code is DRY, which means that whenever you see a pattern in your code those should be eliminated as much as possible. Examples:
    • print(dog); print(cat); etc ... should be refactored employing Array.forEach as the least
    • `${obj.legs}; ${obj.name}; etc...` (yes, strings are also code) must be refactored employing appropriate Array methods

Requirements are always requirements. Double-check yourself against requirements until the principles helping to design a clean code become a habit.

@Levi123
Copy link
Contributor Author

Levi123 commented Aug 22, 2022

@OleksiyRudenko i try to fix my errors

@Levi123 Levi123 requested a review from OleksiyRudenko August 24, 2022 08:54
@OleksiyRudenko OleksiyRudenko self-assigned this Aug 25, 2022
Comment on lines 80 to 83
function arrayToString(propToPrint){
let newStr = propToPrint.join('; ');
console.log(propToPrint);
print(newStr);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function promises to convert an array to a string but it also prints.
Also remove calls to console before submitting code.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Comment on lines 87 to 90
const propToPrint = [];
prop.forEach((propOfObj) => {
propToPrint.push(personToPrint[propOfObj]);
})
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A perfect use case for Array#map method.
Also prop is a global variable. Do not use global variables where there is no need, esp. if it is used in a specific function and only there.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

// printObjectNew(male);
// printObjectNew(female);
// printObjectNew(cat);
// printObjectNew(dog);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

Make your code editor to ensure you always have an empty line at the end of file. There must be a setting. Check this

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you! Done

Comment on lines 71 to 76
const propToPrint = [];
prop.forEach((propOfObj) => {
propToPrint.push(personToPrint[propOfObj]);
})
let newStr = propToPrint.join('; ');
print(newStr);
Copy link
Member

@OleksiyRudenko OleksiyRudenko Aug 25, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Levi123 while looking through your updated code version I started wondering why is it so.

I am sorry, I apparently missed one very important word here. The comment above should read

You should not use print inside this method.

My apologies. We will fix this.

Copy link
Member

@OleksiyRudenko OleksiyRudenko left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Levi123 you did a great job, given I missed one improtant word in my feedback on previous iteration of code review.

Let's make a step back.

Read the comments below and let's transform the list of inhabitants without defining any additional functions at all.

Feel free asking questions and suggesting a relevant fragment of code.

@Levi123
Copy link
Contributor Author

Levi123 commented Aug 25, 2022

@Levi123Ви зробили чудову роботу, оскільки я пропустив одне важливе слово у своєму відгуку про попередню ітерацію перевірки коду.

Зробимо крок назад.

Прочитайте коментарі нижче і давайте трансформуємо список мешканців, не визначаючи жодних додаткових функцій.

Не соромтеся задавати запитання та пропонувати відповідний фрагмент коду.

Sorry, but i don't understand what i must do.

@OleksiyRudenko
Copy link
Member

OleksiyRudenko commented Aug 25, 2022

Remove functions used to transform data and write a fragment of code that prints presentation strings based on allCharactersArray and prop, using map, join, logic to handle friends etc.

@Levi123
Copy link
Contributor Author

Levi123 commented Aug 25, 2022

Remove functions used to transform data and write a fragment of code that prints presentation strings based on allCharactersArray and prop, using map, join, logic to handle friends etc.

check my code pls

@Levi123 Levi123 requested a review from OleksiyRudenko August 25, 2022 15:16
Copy link
Member

@OleksiyRudenko OleksiyRudenko left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Levi123 quite a decent job!
Consider mastering Array methods chaining. This will reduce number of lines of code to write and will add to code readability.

@OleksiyRudenko OleksiyRudenko merged commit 463ed54 into kottans:main Aug 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants