Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Owa Aquino
Owa Aquino
19,277 Points

Javascript Challenge : A Triangle

Hi Treehouse Classmates!

THIS IS NOT A QUESTION.

One thing I love about Treehouse is not only they have great and awesome teachers. They also give you challenges and quizzes to harness your skills and be much better. But that's not enough for me. I wanna be challenged more so I'll be able to understand it so much. So every course or video I watch and learned I create my own code challenges but only for myself. Then I told myself why not share it with you guys?

So here it is (because I'm still starting on my Front-End Development Track and currently in the Javascript courses my challenge is also about Javascript)

Challenge:

  1. ask for 3 numbers from a user.
  2. If the user enters 3 equal #. Display a message that the type of triangle is Equilateral.
  3. If Only 2 # are equal. Display a message that type of triangle is Isosceles.
  4. If no equal # are entered. Display a message that type of triangle is Scalene.
  5. If the user enters strings. Display that enters invalid.
  6. If a user does not enter 3 numbers. Display that enters is invalid.

Comment your answer below. I'll comment mine at the end of the day.

MORE IMPORTANT IS TO HAVE FUN.

Cheers!

P.S There is no wrong answer just different solutions. :)

Apologies for my bad English. :P

1 Answer

Thomas Nilsen
Thomas Nilsen
14,957 Points

Here is one way to go.

function triangles(n1, n2, n3) {
    function isInvalid(n) {
        return typeof n !== 'number';
    }

    if(isInvalid(n1) || isInvalid(n2) || isInvalid(n3)) throw new TypeError('Not a number');

    var len = Object.keys([n1, n2, n3].reduce((a,b) => { a[b] = (a[b] || 0) + 1; return a; }, {})).length;

    return len === 3 ? 'Scalene' :
           len === 2 ? 'Isosceles' : 'Equilateral';
}

console.log(triangles(2, 2, 2));