Niklaus Wirth

Niklaus Wirth

Translate

Personal Portfolio Webpage

CodePen


HTML



<body>
  <div class="container">
  <div id="myHead">
  <div id="#menu">
<div class="text-center">          
<ul class="list-inline myMenu">
            <<li><a href="#myHead">Home</a></li>
              <li><a href="#aboutMe">About me</a></li>
              <li><a href="#myPort">Portfolio</a></li>
              <li><a href="#myCont">Contacts</a></li>
              </ul>
</div>
</div>
    <h1 class="text-center">Yaroslav Kolesnikov<h1>
      <h3 class="text-center">Welcome to my page</h3>
<hr>
      
      <div class="list-inline myButton text-center">
        <a href="https://twitter.com/JroslavK" target="_blank" title="Twitter">
<button class="btn btn-default">
<i class="fa fa-twitter" aria-hidden="true"></i> Twitter</button></a>
     <a href="https://github.com/YaroslavW" target="_blank" title="gitHub"> 
<button class="btn btn-default">
<i class="fa fa-github" aria-hidden="true"></i> GitHub</button></a>
        <a href="https://www.facebook.com/profile.php?id=100011231734286" target="_blank" title="Facebook">
      <button class="btn btn-default">
<i class="fa fa-facebook" aria-hidden="true"></i> Facebook</button></a>
      <a href="https://www.freecodecamp.com/yaroslavw" target="_blank" title="freeCodeCamp">
<button  class="btn btn-default" >
<i class="fa fa-free-code-camp" aria-hidden="true"></i> FreeCodeCamp</button></a>
 </div>     
    </div>
      </div>
      <div class="container">
    <div id="aboutMe">
      <div class="row">
      <div class="col-xs-12 col-sm-6 col-md-6 myText">Hey . I'm Yaroslav and now I'm going through a course in Front End Developer FreeCodeCamp. I love learning new stuff related to programming and technology. My passion is to use technology based solutions, to help solve real world challenges.<br />I have a higher medical education. I love to read and travel. When I do not do the encoding, I do self-education. You can find me on FreeCodeCamp, Codecademy and Udemy <br />My dream - to live and work in a free country, where appreciate the professionalism and human rights.</div>
       
        <div class="col-xs-12 col-sm-6 col-md-6 text-center">
<img src="https://pbs.twimg.com/profile_images/484989907845120000/fTyh8IC7_400x400.jpeg" class="img-rounded"/>
</div>
         <div class="clearfix visible-md"></div>
         </div>
       </div>
      </div>
      <div class="container">
    <div id="myPort">
      <div class="row">
        <div class="col-sm-6 col-md-3">
<div class="thumbnail">
<p data-height="265" data-theme-id="0" data-slug-hash="ygxwXP" data-default-tab="js,result" data-user="YaroslavW" data-embed-version="2" data-pen-title="Simon Game" class="codepen">See the Pen <a href="http://codepen.io/YaroslavW/pen/ygxwXP/">Simon Game</a>
 by YaroslavW (<a href="http://codepen.io/YaroslavW">@YaroslavW</a>) on <a href="http://codepen.io">CodePen</a>.</p>
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script>

<div class="caption text-center"><a href="http://codepen.io/YaroslavW/pen/ygxwXP/" target="_blank">Simon Game</a> </div></a></div></div>

        <div class="col-sm-6 col-md-3">
<div class="thumbnail">
<p data-height="265" data-theme-id="0" data-slug-hash="dNjvgd" data-default-tab="js,result" data-user="YaroslavW" data-embed-version="2" data-pen-title="Pomodoro Clock" class="codepen">See the Pen <a href="http://codepen.io/YaroslavW/pen/dNjvgd/">Pomodoro Clock</a> by YaroslavW (<a href="http://codepen.io/YaroslavW">@YaroslavW</a>) on <a href="http://codepen.io">CodePen</a>.</p>
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script><div class="caption text-center">
<a href="http://codepen.io/YaroslavW/pen/dNjvgd/" taarget="_blank">Pomodoro Clock</a></div></div></div>

        <div class="col-sm-6 col-md-3"><div class="thumbnail"><p data-height="265" data-theme-id="0" data-slug-hash="dNqGaZ" data-default-tab="js,result" data-user="YaroslavW" data-embed-version="2" data-pen-title=" Tic Tac Toe Game" class="codepen">See the Pen <a href="http://codepen.io/YaroslavW/pen/dNqGaZ/"> Tic Tac Toe Game</a> by YaroslavW (<a href="http://codepen.io/YaroslavW">@YaroslavW</a>) on <a href="http://codepen.io">CodePen</a>.</p>
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script><div class="caption text-center"><a href="http://codepen.io/YaroslavW/pen/dNqGaZ/" target="_blank"> Tic Tac Toe Game</a></div></div></div>
         <div class="col-sm-6 col-md-3"><div class="thumbnail"><p data-height="265" data-theme-id="0" data-slug-hash="LxrVja" data-default-tab="js,result" data-user="YaroslavW" data-embed-version="2" data-pen-title="Build a Wikipedia Viewer" class="codepen">See the Pen <a href="http://codepen.io/YaroslavW/pen/LxrVja/">Build a Wikipedia Viewer</a> by YaroslavW (<a href="http://codepen.io/YaroslavW">@YaroslavW</a>) on <a href="http://codepen.io">CodePen</a>.</p>
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script><div class="caption text-center"><a href="http://codepen.io/YaroslavW/pen/LxrVja/" target="_blank">Wikipedia Viewer</a></div></div></div>
      </div>
      <div class="row">
        <div class="col-sm-6 col-md-3"><div class="thumbnail"><p data-height="265" data-theme-id="0" data-slug-hash="WRyVQL" data-default-tab="js,result" data-user="YaroslavW" data-embed-version="2" data-pen-title="JavaScript Calculator" class="codepen">See the Pen <a href="http://codepen.io/YaroslavW/pen/WRyVQL/">JavaScript Calculator</a> by YaroslavW (<a href="http://codepen.io/YaroslavW">@YaroslavW</a>) on <a href="http://codepen.io">CodePen</a>.</p>
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script><div class="caption text-center"><a href="http://codepen.io/YaroslavW/pen/WRyVQL/" target="_blank">JavaScript Calculator</a></div></div></div>
        <div class="col-sm-6 col-md-3"><div class="thumbnail"><p data-height="265" data-theme-id="0" data-slug-hash="egKYRa" data-default-tab="js,result" data-user="YaroslavW" data-embed-version="2" data-pen-title="Show the Local Weather" class="codepen">See the Pen <a href="http://codepen.io/YaroslavW/pen/egKYRa/">Show the Local Weather</a> by YaroslavW (<a href="http://codepen.io/YaroslavW">@YaroslavW</a>) on <a href="http://codepen.io">CodePen</a>.</p>
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script><div class="caption text-center"><a href="http://codepen.io/YaroslavW/pen/egKYRa/" target="_blank">Show the Local Weather</a></div></div></div>
        <div class="col-sm-6 col-md-3"><div class="thumbnail"><p data-height="265" data-theme-id="0" data-slug-hash="PWeMjV" data-default-tab="js,result" data-user="YaroslavW" data-embed-version="2" data-pen-title="Build a Random Quote Machine(2)  " class="codepen">See the Pen <a href="http://codepen.io/YaroslavW/pen/PWeMjV/">Build a Random Quote Machine(2)  </a> by YaroslavW (<a href="http://codepen.io/YaroslavW">@YaroslavW</a>) on <a href="http://codepen.io">CodePen</a>.</p>
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script><div class="caption text-center"><a href="http://codepen.io/YaroslavW/pen/PWeMjV/" target="_blank">Random Quote Machine  </a></div></div></div>
         <div class="col-sm-6 col-md-3"><div class="thumbnail"><p data-height="265" data-theme-id="0" data-slug-hash="GrGpXy" data-default-tab="html,result" data-user="YaroslavW" data-embed-version="2" data-pen-title="Twitchtv JSON API" class="codepen">See the Pen <a href="http://codepen.io/YaroslavW/pen/GrGpXy/">Twitchtv JSON API</a> by YaroslavW (<a href="http://codepen.io/YaroslavW">@YaroslavW</a>) on <a href="http://codepen.io">CodePen</a>.</p>
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script><div class="caption text-center"><a href="http://codepen.io/YaroslavW/pen/GrGpXy/" target="_blank">Twitchtv JSON API</a></div></div></div>
      </div>
      </div>
      </div>
    <div class="container">
    <div id="myCont">
      <div class="row">
        <div class="col-xs-8 col-sm-8 col-md-8 col-lg-8">
       <h3 class="text-center">You can write to me</h3>
          <h3 class="myEmail text-center">kolesnikovy70 @gmail.com</h3>
          <p class="myPhone text-center">8-(8888)-8-888-888-888.</p>
        </div>
      <div clas="row">
       <div class="col-xs-3 col-sm-3 col-md-3 col-lg-3">
          <a href="https://twitter.com/JroslavK" type="button" target="_blank" title="Twitter" class="btn btn-default target btn-block" target="_blank"><i class="fa fa-twitter" aria-hidden="true"></i> <span class="signa">Twitter</span></a>
          <div clas="row"> <a href="https://github.com/YaroslavW" type="button" target="_blank" title="GitHub" class="btn btn-default target btn-block" target="_blank"><i class="fa fa-github" aria-hidden="true"></i> <span class="signa">GitHub</span></a></div>
          <div clas="row"> <a href="https://www.facebook.com/profile.php?id=100011231734286" target="_blank" title="Facebook" type="button" class="btn btn-default target btn-block"><i class="fa fa-facebook" aria-hidden="true"></i> <span class="signa">Facebook</span></a></div>
          <div clas="row"><a href="https://www.freecodecamp.com/yaroslavw"target="_blank" title="freeCodeCamp" type="button" class="btn btn-default target btn-block"><i class="fa fa-free-code-camp" aria-hidden="true"></i> <span class="signa">FreecodeCamp</span></a></div>  
      </div> </div></div>
      <div class="col-xs-1 col-sm-1 col-md-1 col-lg-1"></div>
    </div>
    <div class="container">
      <div class="row">
        <div class="col-md-12">
      <div id="myFooter"><div class=" text-center">         
<ul class="list-inline myMenu">
            <li><a href="#myHead">Home</a></li>
              <li><a href="#aboutMe">About me</a></li>
              <li><a href="#myPort">Portfolio</a></li>
              <li><a href="#myCont">Contacts</a></li>
          </ul></div><hr>
        <div class="text-center">Built by Yaroslav Kolesnikov.</div>
        </div>
          </div>
      </div>
      </div>
</body>




@import url(https://fonts.googleapis.com/css?family=Lato);

#myHead{
  height:400px;
  background-image:URL('https://i.ytimg.com/vi/rSxufmWM6bo/maxresdefault.jpg');
}
.myButton {
  margin-top:5%;
}
.myMenu a{
  font-size:26px;
  color:white;
}
#myHead h1{
  color:red;
}
#myHead h3{
  color:#D8CDF1;
}
#aboutMe{
  background-color:#E9E6FF;
  height: 480px;
}
#aboutMe img{
  margin-top:50px;
  width:300px;
  height:300px;
  border-radius:4000px;
}
.myText{
  margin:0px;
  font-family:Lato;
  font-size: 1.8rem;
  padding-top:3%;
  padding-left:5%;
  
}
hr {
  border:none; 
  background:#D8CDF1;
  height:3px;
  width:50%;
} 
#myCont{
  height:auto;
  background-image:URL('http://www.newhdwallpapers.in/wp-content/uploads/2014/07/Computer-Networking-Cable-Hi-tech-Wallpaper.jpg');
}
#myCont h3{
  color:#D8CDF1;
  font-size:5rem;
  font-family:Impact;
}
#myCont .target{
  margin-top:50px;
  margin-bottom: 50px;
}
#myCont .myEmail{
  margin-top:10%;
  font-size:4rem;
  font-family:Lato;
  color: red;
}
.myPhone{
  font-size:300%;
  font-family:Momospace;
  color:#00AFB8;
  margin-top:5%;
}
#myPort{
  background-color:#E9E6FF;
}
#myFooter{
  margin-top:5%;
}
#myFooter li a{
 color: black;
}
@media screen and (max-width: 992px) { 
  span.signa {
    display: none;
  }
  #myCont .target{
  margin:10px;  
}
};







See the Pen LandingPage(for change) by YaroslavW (@YaroslavW) on CodePen.


Twitchtv JSON API

Codepen, Twitchtv JSON API

HTML



<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="animated bounceIn">
 <div class="header">
  <h1 class="title"> Twitch TV Streamers</h1>
  <nav class="navbar">
  <div class="container-fluid">
     <ul class="nav navbar-nav">
  <li><a class="navtext all" type="button">All</a></li>
  <li><a class="navtext online" type="button">Online</a></li>
  <li><a class="navtext offline" type="button">Offline</a></li>
  </ul>
  </div>
  </nav>
<div class="container-fluid">

 </div>
 <div class="streamers">
  
  <div class="streamerblock streamerblock0">
   <img src="https://x1.xingassets.com/assets/frontend_minified/img/users/nobody_m.original.jpg" class="profile0 profile img-circle">
   <a type="button" class="name0 name">Name</a>
   <p class="stream0 stream">Stream/Offline</p>
   <div class="line"></div>
  </div>
  
  <div class="streamerblock streamerblock1">
   <img src="https://x1.xingassets.com/assets/frontend_minified/img/users/nobody_m.original.jpg" class="profile profile1 img-circle">
   <a type="button" class="name name1">Name</a>
   <p class="stream stream1">Stream/Offline</p>
   <div class="line"></div>
  </div>
  
  <div class="streamerblock streamerblock2">
   <img src="https://x1.xingassets.com/assets/frontend_minified/img/users/nobody_m.original.jpg" class="profile profile2 img-circle">
   <a type="button" class="name name2">Name</a>
   <p class="stream stream2">Stream/Offline</p>
   <div class="line"></div>
  </div>
  
  <div class="streamerblock streamerblock3">
   <img src="https://x1.xingassets.com/assets/frontend_minified/img/users/nobody_m.original.jpg" class="profile profile3 img-circle">
   <a type="button" class="name name3">Name</a>
   <p class="stream stream3">Stream/Offline</p>
   <div class="line"></div>
  </div>
  
  <div class="streamerblock streamerblock4">
   <img src="https://x1.xingassets.com/assets/frontend_minified/img/users/nobody_m.original.jpg" class="profile profile4 img-circle">
   <a type="button" class="name name4">Name</a>
   <p class="stream stream4">Stream/Offline</p>
   <div class="line"></div>
  </div>
 
  <div class="streamerblock streamerblock5">
   <img src="https://x1.xingassets.com/assets/frontend_minified/img/users/nobody_m.original.jpg" class="profile profile5 img-circle">
   <a type="button" class="name name5">Name</a>
   <p class="stream stream5 ">Stream/Offline</p>
   <div class="line"></div>
  </div>
 
  <div class="streamerblock streamerblock6">
   <img src="https://x1.xingassets.com/assets/frontend_minified/img/users/nobody_m.original.jpg" class="profile profile6 img-circle">
   <a type="button" class="name name6"></a>
   <p class="stream stream6">Stream/Offline</p>
   <div class="line"></div>
  </div>
  
  <div class="streamerblock streamerblock7">
   <img src="https://x1.xingassets.com/assets/frontend_minified/img/users/nobody_m.original.jpg" class="profile profile7 img-circle">
   <a type="button" class="name name7">Name</a>
   <p class="stream stream7">Stream/Offline</p>
   <div class="line"></div>
  </div>
 </div>
 <footer>
  <div class="about">
   <p class="text-center abouttext">This is a project by Yaroslav Kolesnikov for <a type="button" class="fcc">Free Code Camp</a> 2016</p>
  </div>
 </footer>
</div>
</div>
</div>
</div>


CSS



body{
 background-color:#C6CAC1; 
}
.header{
 width:100%;
 background-color:#B2AAAA;
 text-align:center;
 border-radius:10px;
 margin:auto;
}
.title{
 padding-top:20px;
 font-family:Lato;
 color:#6441A5;
}
.myname{
 font-size:20px;
 color:#6441A5;
}
.navbar{
 margin:auto;
}
.streamers{
 width:100%;
 margin:auto;
 background:white;
 border-radius:10px;
 padding-bottom:20px;
  text-align: left;
}
nav{
 background-color:#6441A5;
 font-family:Lato;
}
.text{
 color:#6441A5;
 font-family:Lato;
}  
.abouttext{
  background-color:#B2AAAA;
  border-radius:10px;
 color:#6441A5;
 margin-top:20px;
}
.profile{
 border-radius:100%;
 width:70px;
 margin-top:2%;
 margin-bottom:2%;
 margin-left:2%;
}
.name{
 color:#6441A5;
 font-size:15px;
 display:inline-block;
}
.stream{
 color:#6441A5;
 font-size:15px;
 display:inline-block;
}
.line{
 width:100%;
 height:1px;
 background-color:#6441A5;
}

.navtext{
 font-size:1.5rem;
}



JS



var streamers =[ "freecodecamp","OgamingSC2", "RobotCaleb","brunofin12","noobs2ninjas","storbeck", "cretetion","habathcx","ESL_SC2"];
var offline;
var streamerurl;

$(document).ready(function(){
 function twitchstreamer(streamer,block){
  $.ajax({
   type: 'GET',
   url: 'https://api.twitch.tv/kraken/channels/' + streamer,
   headers: {
    'Client-ID': 'ttmj4g3n804793e2zkjpybb2grkgh3'
   },
   success: function(data) {
    console.log(data);
    
    $('.name' + block).html(data.display_name);

   
    var profilepic = data.logo;
    $('.profile' + block).attr("src", profilepic);

    $('.name' + block).click(function(){
     window.open('https://twitch.tv/'+streamer)
    })
   }
  })
 
  $.ajax({
   type: 'GET',
   url: 'https://api.twitch.tv/kraken/streams/' + streamer,
   headers: {
    'Client-ID': 'co9k9t8sd7pi3lq1p3jvc2oyaojbpf3'
   },
   success: function(idx) {
    console.log(idx);
    if(idx.stream === null){
     //Offline
     $('.stream' + block).html('Offline');
     $('.streamerblock' + block).addClass('channeloffline');
    }else{
    
     $('.stream' + block).html(idx.stream.channel.status);
     $('.streamerblock' + block).addClass('channelonline');
    }
   },
   error:function(err){
    //The channel does not exist
    console.log(err);
    $('.stream').html('This channel does not exist');
   }
  })
 }
 
 twitchstreamer(streamers[0],0);//1
 twitchstreamer(streamers[1],1);//2
 twitchstreamer(streamers[2],2);//3
 twitchstreamer(streamers[3],3);//4
 twitchstreamer(streamers[4],4);//5
 twitchstreamer(streamers[5],5);//6
 twitchstreamer(streamers[6],6);//7
 twitchstreamer(streamers[7],7);//8
 
 
 $('.all').click(function(){
  $('.channelonline').show();
  $('.channeloffline').show();
 })
 $('.online').click(function(){
  $('.channeloffline').hide();
  $('.channelonline').show();
 })
 $('.offline').click(function(){
  $('.channeloffline').show();
  $('.channelonline').hide();
 })
 
 $('.fcc').click(function(){
  openfcc();
 })
})

function openfcc(){
 window.open('https://freecodecamp.com');
}



See the Pen Twitchtv JSON API by YaroslavW (@YaroslavW) on CodePen.


Simon Game

#100DaysOfCode

CodePen



    <div class="control-wrapper">
        <button type="button" class="btn btn-primary" onClick="changeRegjme('Normal')">Normal regjme</button>
        <button type="button" class="btn btn-danger" onClick="changeRegjme('Hard')">Hard Regjme</button>
        <button type="button" class="btn btn-success" onClick="init()">Start New Game</button>
    </div>

    <div class="simon-wrapper">
        <div class="simon-info">
            <h2>Simon</h2>
            <span class="info">Count: </span><span id="count">0</span>
            <span class="info">Regjme: </span><span id="regjme">Normal</span>
            <span class="info" id="note">Click to play!</span>
        </div>
        <div id="btn0" class="btn-game top left green" onClick="clickBtn(0)"></div>
        <div id="btn1" class="btn-game top right red" onClick="clickBtn(1)"></div>
        <div id="btn2" class="btn-game bottom left yellow" onClick="clickBtn(2)"></div>
        <div id="btn3" class="btn-game bottom right blue" onClick="clickBtn(3)"></div>
    </div>




body {
    background-color: #EBEBEB;
}

.control-wrapper {
    margin: 0 auto;
    justify-content: center;
    text-align: center;
}

.simon-wrapper {
    background-color: #D6D6D6;
    border: 5px solid black;
    border-radius: 50%;
    height: 300px;
    margin: 0 auto;
    margin-top: 10%;
    overflow: hidden;
    position: relative;
    width: 300px;
}

.simon-info {
    background-color: #222;
    border-radius: 50%;
    color: white;
    height: 180px;
    margin-top: 53px;
    margin-left: 57px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 180px;
}
.simon-info h2 {
    font-size: 28px;
    font-weight: bold;
    margin-top: 20%;
    text-align: center;
    
}
.simon-info span {
    display: inline-block;
    font-weight: bold;
    text-align: center;
}
.simon-info span.info {
    margin-left: 30%;
}

.btn-game {
    float: left;
    height: 50%;
    overflow: hidden;
    width: 50%;
}
.btn-game.top {
    border-bottom: 3px solid black;
}
.btn-game.bottom {
    border-top: 3px solid black;
}

.btn-game.right {
    border-left: 3px solid black;
}

.btn-game.left {
    border-right: 3px solid black;
}

.btn-game.green {
    background-color: rgba(0, 213,29, 0.9);
}

.btn-game.red {
    background-color: rgba(213, 40, 17, 0.9);
}

.btn-game.yellow {
    background-color: rgba(255, 255, 0, 0.9);
}
.btn-game.blue {
    background-color: rgba(9, 74, 143, 0.9);
}

.btn-press {
    background-color: rgba(255,255,255,1) !important;
}




var playControl = {
    count: 0,
    regjme: "Normal",
    speed: 1200,
    wait: false

};

var model = [],
    currModel = [],
    userModel = [];

function init() {
    playControl.wait = false;
    model = [];
    userModel = [];
    playControl.count = 0;
    $('#count').text('0');
    $('#note').text("New game!");
    $('#regjme').text(playControl.regjme);

    createModel();
    showModel();
}


function color() {
    return Math.floor(Math.random() * (3 - 0 + 1) + 0);
}


function createModel() {
    model = [];
    for (var i = 20; i > 0; i--) {
        model.push(color());
    }
    return model;
}


function showModel() {
    var i = 0;
    playControl.wait = false;
    var modelLoop = setInterval(function () {
        fireBtn(model[i]);
        i++;
        if (i >= playControl.count + 1) {
            clearInterval(modelLoop);
            currModel = model.slice(0, playControl.count + 1);
            userModel = [];
            playControl.wait = true;
        }
    }, playControl.speed - playControl.count * 15);
}


function fireBtn(bNum) {
    var sound = new Audio('https://s3.amazonaws.com/freecodecamp/simonSound' + (bNum + 1) + '.mp3');
    $('#btn' + bNum).addClass('btn-press');

    setTimeout(function () {
        $('#btn' + bNum).removeClass('btn-press');
    }, 300);


    sound.play();
}


function changeRegjme(regjme) {
    playControl.regjme = regjme;
    $('#regjme').text(playControl.regjme);
}


function testModel() {
    for (var i = 0; i < userModel.length; i++) {
 
        if (userModel[i] != currModel[i]) {
            $('#note').text("Wrong!!");
            playControl.wait = false;
            if (playControl.regjme == "Normal") {
                return showModel();
            } else {
                init();
            }
        }
    }

    if (userModel.length === currModel.length) {
        $('#note').text("Correct!!");
        playControl.wait = false;
        userModel = [];
        playControl.count++;
        updateCount();
        return showModel();
    }
}


function updateCount() {
    $('#count').text(playControl.count);
}

function checkWin() {
    if (playControl.count >= 21) {
        $('#note').text("You won!! Prepare for the next round!");
        setInterval(function () {
            playControl.speed = 1000;
            init();
        }, 5000)
    }
}


function clickBtn(bNum) {
    if (playControl.wait === true) {
        fireBtn(bNum);
        userModel.push(bNum);
        testModel();
    }
}


See the Pen Simon Game by YaroslavW (@YaroslavW) on CodePen.


Tic Tac Toe Game

#100DayOfCode

codepen.io

HTML




<div class="sign-select">
 <h3>Choose your weapon:</h3>
 <button type="button" class="btn btn-default cell-X" onclick="signSelect('X', 'O')">X</button>
 <button type="button" class="btn btn-default cell-O" onclick="signSelect('O', 'X')">O</button>
</div>

<div id="game" class="game-wrapper">
 <div class="row row-top">
  <div id="cell0" class="cell" data-position=0></div>
  <div id="cell1" class="cell" data-position=1></div>
  <div id="cell2" class="cell" data-position=2></div>
 </div>
 <div class="row row-mid">
  <div id="cell3" class="cell" data-position=3></div>
  <div id="cell4" class="cell" data-position=4></div>
  <div id="cell5" class="cell" data-position=5></div>
 </div>
 <div class="row row-bot">
  <div id="cell6" class="cell" data-position=6></div>
  <div id="cell7" class="cell" data-position=7></div>
  <div id="cell8" class="cell" data-position=8></div>
 </div>
</div>



CSS



body {
 background: #F2F2F2;
}

.cell {
 float: left;
 background: #F2F2F2;
 width: 100px;
 height: 100px;
 border: 2px solid #0496ff;
 font-size: 52px;
 font-weight: bold;
 color: #fbfcff;
 justify-content: center; 
  text-align: center;
 padding-top: 15px;
}

.row-top .cell {
 border-top: none;
}

.row-cell {
 
}

.row-bot .cell {
 border-bottom: none;
}

#cell0, #cell3, #cell6 {
 border-left: none;
}

#cell2, #cell5, #cell8 {
 border-right: none;
}

.game-wrapper {
 margin: 15px auto;
 justify-content: space-around;
  text-align: center;
 width: 350px;
}

.sign-select {
 margin: auto;
 display: none;
 justify-content: center;
 padding-left: 45px;
  text-align: ;
 height: 200px;
 width: 325px;
  background: #F2F2F2;
}

.sign-select h3 {
 padding-top: 10%;
}

.sign-select .btn {
 height: 80px;
 width: 80px;
 font-size: 42px;
 font-weight: bold;
}

.cell-X {
 color: #00E700;
}

.cell-O {
 color: #fe4a49;
}



JS




var playField = ["", "", "",
    "", "", "",
    "", "", ""];

var gamer = {
 sign: '',
 wins: 0,
};

var comp = {
 sign: '',
 wins: 0,
};


var control = {
 roll: '',
 stop: false,
};


function Think() {
 if (control.roll === 'comp' && Win(gamer.sign) === false) {
  var emptSp = Empty();
  var movSp = Math.floor(Math.random() * (emptSp.length-1 - 0 + 1)) + 0;
  if (addSymb(comp.sign, emptSp[movSp]) === 'moved') {
   control.roll = 'gamer';
  }
   Win(comp.sign);
 }
}

function Empty() {
 var emptSp = [];
 for (var i=0; i< playField.length; i++) {
  if (playField[i] === "") {
   emptSp.push(i);
  }
 }
 return emptSp;
}



function Win(sign) {
 Horz(sign);
 Vert(sign);
 Diag(sign);
 Draw();
 
 if (control.stop === true) {
  init();
  return true;
 } else {
  return false;
 }
 
}

function Horz(sign) {
 if (playField[0] === sign &&
   playField[1] === sign &&
    playField[2] === sign) {
  control.stop = true;
 } else if(playField[3] === sign &&
      playField[4] === sign &&
      playField[5] === sign) {
  control.stop = true;
 } else if(playField[6] === sign &&
      playField[7] === sign &&
         playField[8] === sign) {
  control.stop = true;
 }
}

function Vert(sign) {
 if (playField[0] === sign &&
   playField[3] === sign &&
    playField[6] === sign) {
  control.stop = true;
 } else if(playField[1] === sign &&
      playField[4] === sign &&
      playField[7] === sign) {
  control.stop = true;
 } else if(playField[2] === sign &&
      playField[5] === sign &&
      playField[8] === sign) {
  control.stop = true;
 }
}

function Diag(sign) {
 if (playField[0] === sign &&
   playField[4] === sign &&
    playField[8] === sign) {
  control.stop = true;
 } else if(playField[2] === sign &&
      playField[4] === sign &&
      playField[6] === sign) {
  control.stop = true;
 }
}

function Draw() {
 if (Empty().length === 0) {
  control.stop = true;
 }
}


function clearField() {
 for (var i=0; i < playField.length; i++) {
   playField[i] = "";
   $('#cell' + i).text("");
   $('#cell' + i).removeClass('cell-X');
   $('#cell' + i).removeClass('cell-O');
 }
}


function init() {
 clearField()
 gamer.sign = '';
 comp.sign = '';
 control.roll = '';
 control.stop = false;
 $('.sign-select').show();
}

function signSelect(pSymbol, cSymbol) {
 gamer.sign = pSymbol;
 comp.sign = cSymbol;
 $('.sign-select').hide();
 
 if (gamer.sign === 'O') {
  control.roll = 'comp';
  setTimeout(function(){Think()}, 500);
 } else {
  control.roll = 'gamer';
 }
 
}


function addSymb(sign, pos) {
 if (playField[pos] === '') {
  playField[pos] = sign;
  $('#cell' + pos).addClass('cell-' + sign);
  $('#cell' + pos).text(sign);
  Win(sign);
  return 'moved';
 }
}

$('.cell').click(function(){
 if (control.roll === 'gamer') {
  var pos = this.getAttribute("data-position");
  if (addSymb(gamer.sign, pos) === 'moved') {
   control.roll = 'comp';
   setTimeout(function(){Think()}, 500);
  }
 }
 
 Win(gamer.sign);
 Win(comp.sign);
 
});

init();


See the Pen Tic Tac Toe Game by YaroslavW (@YaroslavW) on CodePen.


Pomodoro Clock

Pomodoro Clock

HTML



<audio id="bell" src="http://www.mediacollege.com/downloads/sound-effects/money/cash-register-01.wav" type="audio/mpeg"></audio>
    <div class="container-fluid text-center">
        <h1>Pomodoro Clock</h1>
        <h3>An App To Manage Your Time</h3>
        <div class="sesTimer">
            <h1 id="timeSes">Session Time</h1>
            <h1 id="timeType"></h1>
            <a href="#" class="btn btn-primary" id="minTime">-</a>
            <h2 id="num">25</h2>
            <a href="#" class="btn btn-primary" id="adTime">+</a>
            <a href="#" class="btn btn-primary" id="reset">Reset</a>
        </div>
        <div id="brTimer">
            <h1 id="timerBr">Break Time</h1>
            <a href="#" class="btn btn-primary" id="minBr">-</a>
            <h2 id="numBr">5</h2>
            <a href="#" class="btn btn-primary" id="adBr">+</a>
        </div>
        <a href="#" class="btn btn-primary" id="start">Start</a>
    </div>


CSS



@import url(https://fonts.googleapis.com/css?family=Lato);
body{
 background-image:url("http://reallondon.ru/wp-content/uploads/2013/03/18-e1386001921165.jpg");
 font-family: "Lato";
    background-size:100%;
    background-origin:padding-box;
    background-size:cover;    
    background-attachment: fixed;
    color: black;
}
h1{
 color: black;   
}
h2{
    display: inline;
}

#start {
 margin: 10px;
}
#num,
#numBr{
  color:red;
  font-weight: bold;
}


JS



$(document).ready(function() {

    $("#message").hide();
    var buzzer = $("#bell")[0];
    var count = parseInt($("#num").html());
    var breakTime = parseInt($("#numBr").html());

    $("#reset").hide();

    $("#start").click(function() {
        var counter = setInterval(timer, 1000);
        count *= 60;

        function timer() {
            
            $("#start, #minTime, #adTime,#minBr,#adBr,#numBr,#timeSes,#timeBr").hide();
            $("#timeType").show();
            $("#timeType").html("Session Time: ");

            var display = $('#num');
            timeset(count, display);
            count -= 1;
            if (count === 0) {
                buzzer.play();
                clearInterval(counter);
                var startBreak = setInterval(breakTimer, 1000);
                breakTime *= 60;
                $("#num").hide();
                breakTimer();
            }

            function breakTimer() {
                $("#numBr").show();
                $("#timeType").html("Break Time: ");

                var bdisplay = $('#numBr');
                timeset(breakTime, bdisplay);
                breakTime -= 1;
                if (breakTime === 0) {
                    clearInterval(startBreak);
                    buzzer.play();
                    $("#timeType").hide();
                    $("#reset").show();
                    $("#numBr").hide();
                }
            }
        }
    });

    function timeset(clock, display) {
        var hours, minutes, seconds;
        hours = parseInt(Math.floor(clock / 3600, 10));
        minutes = parseInt(Math.floor(clock % 3600 / 60));
        seconds = parseInt(Math.floor(clock % 3600 % 60));

        hours = hours > 0 ? "0" + hours : hours;
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        var out = display.text(hours + ":" + minutes + ":" + seconds);
        return out;
    }

    $("#reset").click(function() {
        count = 25;
        breakTime = 5;
        $("#num").html(count);
        $("#numBr").html(breakTime);
        $("#start, #minTime, #num, #adTime,#minBr,#adBr,#numBr,#timeSes,#timeBr").show();
        $("#reset").hide();
    });

    $("#minTime").click(function() {
        if (count > 1) {
            count -= 1;
            $("#num").html(count);
        }
    });

    $("#adTime").click(function() {
        count += 1;
        $("#num").html(count);

    });
    $("#minBr").click(function() {
        if (breakTime > 1) {
            breakTime -= 1;
            $("#numBr").html(breakTime);
        }
    });

    $("#adBr").click(function() {
        breakTime += 1;
        $("#numBr").html(breakTime);

    });
});


See the Pen Pomodoro Clock by YaroslavW (@YaroslavW) on CodePen.


JavaScript Calculator

JavaScript Calculator

CodePen"



<div id="calculator">
  
  <div id="screen"> 0 </div>
  
  <div>
    <button id="ac">AC</button>
    <button id="del">←</button>
    <button class="op">%</button>
    <button class="op">/</button>
  </div>
  
  <div>
    <button class="num">7</button>
    <button class="num">8</button>
    <button class="num">9</button>
    <button class="op">x</button>
  </div>
  
  <div>
    <button class="num">4</button>
    <button class="num">5</button>
    <button class="num">6</button>
    <button class="op">-</button>
  </div>
  
  <div>
    <button class="num">1</button>
    <button class="num">2</button>
    <button class="num">3</button>
    <button class="op">+</button>
  </div>
  
  <div>
    <button class="num" id="0">0</button>
    <button class="num" id=".">.</button>
    <button id="equal">=</button>
  </div>
  
</div>




body {
  background-color: #EBEBEB;
  text-align: center;
  color: white;
}

#calculator {
  margin: 80px auto;
  background-color: silver;
  width: 280px;
  padding: 4px 0px 10px 0px;
  border-radius: 10px;
  box-shadow: 10px 10px 10px rgba(0,0,0,0.7);
}

#screen {
  text-align:right !important;
  margin: 8px 11px;
  height: 30px;
  padding: 4px 5px 4px 0px;
  background-color:#F2F2F2;
  font-size: 28px;
  border-radius: 5px;
  color: black;
}

button {
  width: 60px;
  height: 40px;
  margin-bottom: 6px;
  font-size: 20px;
  background-color: #5754EF;
  border-radius: 5px;
  color: white;
  border-style: none;
  outline: 0;
  box-shadow: 2px 2px 2px black;
}

#equal {
  width: 124px;
}

#ac, #del {
  background-color: #b30000;
}

button:hover {
  box-shadow: inset 0 -1px 1px rgba(0,0,0,0), inset 0 1px 2px rgba(0,0,0,0), inset 0 0 0 60px rgba(255,255,0,.5);
}
button:active {
  padding: calc(.25em + 1px) .5em calc(.25em - 1px);
  border-color: rgba(42,35,255,1);
  box-shadow: inset 0 -1px 1px rgba(0,0,0,.1), inset 0 1px 2px rgba(0,0,0,.3), inset 0 0 0 60px rgba(255,255,0,.45);
}






var x = 0;
var y = 0;
var operator = null;
var result = null;


function fixed(floater) {
    return Math.round(floater * 1000) / 1000;
}

function doMath(x, operator, y) {
  
  x = parseFloat(x);
  y = parseFloat(y);
  switch(operator) {
    case "+":
      result = fixed(x + y);
      break;
    case "-":
      result = fixed(x - y);
      break;
    case "x":
      result = fixed(x * y);
      break;
    case "/": 
      result = fixed(x / y);
      break;
    case "%":
      result = fixed(x / y * 100);
      break;
    }
  return result;
}


$("button").click(function() {
  
 
  if ($(this).attr("class") === "num" ) {
    
    if (!operator && x !== result) {
     
      if ($(this).attr("id") === "." || $(this).attr("id") === "0") {
        x = x + ($(this).text());
        $("#screen").text(x);
      }
      else {
      x = parseFloat(x + ($(this).text()));
      $("#screen").text(x);
      }
    }
   
    else if (operator) {
    
      if ($(this).attr("id") === "." || $(this).attr("id") === "0") {
        y = y + ($(this).text());
        $("#screen").text(y);
      }
      else {
      y = parseFloat(y + ($(this).text()));
      $("#screen").text(y);
      }
    }
  }
  
  
  else if ($(this).attr("class") === "op" ) {
   
    if (y) {
      doMath(x, operator, y);
      x = res;
      y = 0;
    }
    operator = $(this).text();
    $("#screen").text(operator);
  }
  
  
  else if ( operator && ($(this).attr("id") === "equal") ) {

    doMath(x, operator, y);
    x = result;
    $("#screen").text(x);
    y = 0;
    operator = null;
  }
  

  else if ($(this).attr("id") === "ac") {
    x = 0;
    y = 0;
    operator = null;
    result = null;
    $("#screen").text(x);
  }
  
  
  else if ($(this).attr("id") === "del") {
    if (x && !operator) {
      x = 0
      $("#screen").text(x);
    }
    else if (x && operator && y) {
      y = 0;
      $("#screen").text(operator);
    }
    else {
      operator = null;
      $("#screen").text(x);
    }
  }
  
});


See the Pen JavaScript Calculator by YaroslavW (@YaroslavW) on CodePen.

CodePen

(36)Build a Wikipedia Viewer

CODEPEN

HTML



<h1 id ="title">Wikipedia Viewer</h1>
<div id="action">
<div>  <a href="http://en.wikipedia.org/wiki/Special:Random" target="_blank" id="random">
    <i class="fa fa-random"> Click here for a random article</i>
  </a></div>
  <input type="text" id="input" placeholder="Search">
  <<i class="fa fa-search" id="searchBtn"></i>
</div>
<div id="main"></div>


CSS



@import url(https://fonts.googleapis.com/css?family=Lato);

#title {
  color: white;
  text-align: center;
  font-size: 3.2rem;
}

body {
  background:#565DB7;
  font-family: 'Lato', sans-serif;
}

.result {
  background: white;
  margin: 1% 3%;
  padding: 1% 2%;
}

a {
  position: relative;
  display: block;
  color: black;
  text-decoration: none;
  font-size:2.2rem;
}

#action {
   text-align: center;
  width: 50%; 
  margin: 30px auto 30px auto;
}

#random {
  display: inline;
}

.fa {
  color: white;
}

#input {
  margin:10%;
  display: inline;
  border-radius: 15px;
  border-style: none;
  outline: none;
  padding: 15px 15px;
}

#searchBtn {
  cursor: pointer;
  font-size:2rem
}


JS



var html;
var link;

$('#input').keydown(function (key) {
  if (key.keyCode === 13) {
    search = $('#input').val();
    callIt();
  
  } 
}); 

$('#searchBtn').click(function(){
  search = $('#input').val();
  callIt();
});

function callIt() {
      $.getJSON( 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exsentences=1&exlimit=max&exintro=&exsectionformat=wiki&generator=search&redirects=&gsrsearch=' + search + '&gsrnamespace=0&callback=?', function( data ) {
  
      
      display(data.query.pages);
    });  
}

function display(data) {
  $('#main').empty();
  $.each(data, function (idx, el) {
    html = '
'; html += '

' + el.title + '

'; html += '

' + el.extract + '

'; $('#main').append(html); }); }


See the Pen Build a Wikipedia Viewer by YaroslavW (@YaroslavW) on CodePen.


Show the Local Weather

35-ый день #100DaysOfCode

http://codepen.io/YaroslavW/full/egKYRa/

HTML


<div class="info">
  <h1 ="title">Local Weather</h1>
  <h2 id="city"></h2>
  <button id="convert" class="btn btn-info">Convert to Celsius</button> 
  <h2 id="temp"></h2>
  <img id="icon"></img>
</div>


CSS


@import url(https://fonts.googleapis.com/css?family=Lato);

body {
  text-align: center;
  font-family: 'Lato', sans-serif;
}

.info {
  margin: 5px auto;
 width: 60vw;
 padding: 10px 5px 10px 5px;
 background: linear-gradient(rgba(179, 168, 211, .9), rgba(222, 199, 182, 0.9));
 border-radius: 10px;
}

@media screen and (max-width: 600px) {
  .info {
    width: 100%;
  }
}
#convert{
   border: 1px solid;
   border-radius: 5px;
   padding: .5em 2em;
}



JS


$.getJSON('http://ip-api.com/json', function (position) {
  var lat = position.lat;
  var lon = position.lon;
  console.log('https://crossorigin.me/http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&units=imperial&APPID=a391588e176db8c353dcb74504141cf5')
  $.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&units=imperial&APPID=a391588e176db8c353dcb74504141cf5', function (data) {
        
    console.log(data);
    var city = data.name;
    var f = Math.round(data.main.temp);
    var c = Math.round((data.main.temp - 32) * 5/9);
    var temp = f;
    var condition = data.weather[0].id;
    $('#city').text(city);
    $('#temp').text(temp  + "\u00B0 F");
    $('#icon').attr('src', 'http://openweathermap.org/img/w/' + data.weather[0].icon + '.png')

     if (condition >= 800 && condition <= 804) {
    $('body').css('background', 'url(https://oboi.ws//wallpapers/27_2145_oboi_solnechnaja_pustynja_2560x2048.jpg)' + 'no-repeat center center fixed');
   }
    if (condition >= 200 && condition <= 531) {
    $('body').css('background', 'url(http://hq-oboi.ru/photo/solnce_skvoz_oblaka_skachat_krasivye_1920x1200.jpg)' + 'no-repeat center center fixed');
    }
    if (condition >= 600 && condition <= 622) {
    $('body').css('background', 'url(http://www.jr1.ru/i/orig/10628-1600x1200.jpg)' + 'no-repeat center center fixed');
    }       
    $('body').css('background-size', 'cover')

    $('#convert').click(function() {
      if (temp === f) {
        temp = c;
        $('#convert').text("Convert to Fahrenheit");
        $('#temp').text(temp + "\u00B0 C");
      }
      else {
        temp = f;
        $('#temp').text(temp + "\u00B0 F");
        $('#convert').text("Convert to Celsius");
      }
    });
      
  });  
});




See the Pen Show the Local Weather(1) by YaroslavW (@YaroslavW) on CodePen.


(34)Build a Random Quote Machine

34D #100DaysOfCode


HTML


<div class="container">
  <div class="transbox">
    
   <p class="quote" id="response">Programming is usually taught by examples.
~Niklaus Wirth</p> <button id="getTweet" class=" btn-custom"> <i class="fa fa-twitter"></i> Tweet This</button> <button id="getMessage" class="btn-custom pull-right">New Quote</button> </div> <div class="footer hline text-center"> <p> Built by Yaroslav Kolesnikov.</p> </div> </div>


SCSS


@import url(https://fonts.googleapis.com/css?family=Tangerine:400,500);



body {
  background-image: url(http://www.wallpapers13.com/wp-content/uploads/2016/04/New-Zealand-view-from-the-hill-sea-empty-beach-ocean-waves-HD-Wallpapers-for-Desktop-1920x1080.jpg);
  background-repeat: no repeat;
}

.quote {
  padding-top: 50px;
  font-family:Tangerine,serif;
  font-size: 52px;
  font-weight: bold;
  color: #003333;
  line-height: 40px;
  text-align: center;
}

.btn-custom {
  margin-top: 5%;
  padding: 15px;
  background: #006666;
  color: white;
  font-weight: bold;
  border: #003333;
  border-radius: 5px;
}

.btn-custom:active {
  background: #003333;
}

.btn-custom:hover {
  background: #003333;
}

.transbox {
  margin: 10%;
  padding: 5px;
  background-color: #ffffff;
  border: 1px solid #003333;
  border-radius:5px;
  opacity: 0.6;
  filter: alpha(opacity=60);
}

.hline {
  width: 100%;
  height: 1px;
  background: #003333;
  margin-top: 20%;
  margin-bottom: 15px;
  font-weight: bold;
  color: #003333;
   
}


JS




$(document).ready(function() {
  $("#getMessage").on("click", function() {
    $.getJSON("http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en&jsonp=?", function(data) {
      if(data.quoteAuthor == "") {
        data.quoteAuthor = "Anonymous";
      }
      $("#response").html( data.quoteText + "
" + "~" + data.quoteAuthor); }); }); $("#getTweet").on("click", function() { window.open("https://twitter.com/intent/tweet?text=" + $("#response").text()); }); });


See the Pen Build a Random Quote Machine(1) by YaroslavW (@YaroslavW) on CodePen.



I prefer second version of solutions




See the Pen Build a Random Quote Machine(2) by YaroslavW (@YaroslavW) on CodePen.


(33)Arguments Optional

Arguments Optional
33-ий день программы "#100 Days Of Code"

Create a function that sums two arguments together. If only one argument is provided, then return a function that expects one argument and returns the sum.

For example, addTogether(2, 3) should return 5, and addTogether(2) should return a function.

Calling this returned function with a single argument will then return the sum:

var sumTwoAnd = addTogether(2);

sumTwoAnd(3) returns 5.

If either argument isn't a valid number, return undefined.


function addTogether() {
  var results;
  if(arguments.length <=3){
    var a1 = arguments[0];
    var a2 = arguments[1];
    if(typeof(a2)==='number'){
      if(typeof(a1) ==='number'){
      
        results = a1 +a2;
      }
    } else if(a2===undefined && typeof(a1)==='number'){
      return function(a2){
        if(typeof(a2)==='number'){
          return a1 + a2;
        }
        else return results;
      };
    }
  }
  return results;
}

addTogether(2,3);


Ответы:

addTogether(2, 3)
return 5.

addTogether(2)(3)
return 5.

addTogether("http://bit.ly/IqT6zt")
return undefined.

addTogether(2, "3")
return undefined.

addTogether(2)([3])
return undefined.


(32)Everything Be True

Everything Be True
32-ой день программы "#100 Days Of Code"

Check if the predicate (second argument) is truthy on all elements of a collection (first argument).

Remember, you can access object properties through either dot notation or [] notation.



function truthCheck(collection, pre) {

  for(var i = 0; i < collection.length; i++){
    if(!collection[i][pre])
      return false;
  }
  return true;
}

truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");



Ответы:

truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex")
return true.

truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex")
return false.

truthCheck([{"user": "Tinky-Winky", "sex": "male", "age": 0}, {"user": "Dipsy", "sex": "male", "age": 3}, {"user": "Laa-Laa", "sex": "female", "age": 5}, {"user": "Po", "sex": "female", "age": 4}], "age")
return false.

truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true}, {"name": "FastFoward", "onBoat": null}], "onBoat")
return false

truthCheck([{"name": "Pete", "onBoat": true}, {"name": "Repeat", "onBoat": true, "alias": "Repete"}, {"name": "FastFoward", "onBoat": true}], "onBoat")
return true

truthCheck([{"single": "yes"}], "single")
return true

truthCheck([{"single": ""}, {"single": "double"}], "single")
return false

truthCheck([{"single": "double"}, {"single": undefined}], "single")
return false

truthCheck([{"single": "double"}, {"single": NaN}], "single")
return false


Функция с функцией, как аргумент (31)Drop it

Drop it
31-ый день программы "#100 Days Of Code"

Drop the elements of an array (first argument), starting from the front, until the predicate (second argument) returns true.

The second argument, func, is a function you'll use to test the first elements of the array to decide if you should drop it or not.

Return the rest of the array, otherwise return an empty array.

Функцию можно описать так: Пока есть аргумент в виде массива, то будет выполняться, полученная вторым аргументом, функция, которая добавит в массив только те элементы, которые подойдут под условие заданное полученной функцией.

Here are some helpful links:



function dropElements(arr, func) {
  
  
    while(!func(arr[0])){
       arr.shift();
    }
  
  return arr;
}

dropElements([1, 2, 3], function(n) {return n < 3; });


Ответы:

dropElements([1, 2, 3, 4], function(n) {return n >= 3;})
return [3, 4].

dropElements([0, 1, 0, 1], function(n) {return n === 1;})
return [1, 0, 1].

dropElements([1, 2, 3], function(n) {return n > 0;})
return [1, 2, 3].

dropElements([1, 2, 3, 4], function(n) {return n > 5;})
return [].

dropElements([1, 2, 3, 7, 4], function(n) {return n > 3;})
return [7, 4].

dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;})
return [3, 9, 2].


(30)Pairwise

Pairwise
30-ый день программы "#100 Days Of Code"

Given an array arr, find element pairs whose sum equal the second argument arg and return the sum of their indices.

If multiple pairs are possible that have the same numeric elements but different indices, return the smallest sum of indices. Once an element has been used, it cannot be reused to pair with another.

For example pairwise([7, 9, 11, 13, 15], 20) returns 6. The pairs that sum to 20 are [7, 13] and [9, 11]. We can then write out the array with their indices and values.



Index01234
Value79111315


Below we'll take their corresponding indices and add them.

7 + 13 = 20 → Indices 0 + 3 = 3

9 + 11 = 20 → Indices 1 + 2 = 3

3 + 3 = 6 → Return 6



Создали пустой массив, куда будем добавлять наши номера. Отдельно создал переменную ответ

Исключили те случаи, когда наша функция должна вернуть 0 -пустой массив на входе pairwise([], 100) should return 0.

Два цикла перебора массива находят варианты при которых сумма двух чисел будет равна аргументу и добавлять их позиции в новый массив. Чтобы избежать повторов, мы в условие прописываем, что данных чисел там еще не должно быть

(arr[i]+arr[j]===arg&& sum.indexOf(i) ==-1 && sum.indexOf(j) ==-1)

В конце мы получаем сумму всех значений массива.

sum = answers.reduce(function(a,b){
    return a+b;
  });

И вернуть именно это значение!

Вообще то, я думаю, что переменная sum здесь лишняя. Можно было вполне обойтись и без нее. Но ... пока что я учусь и потому, оставил для наглядности :-) !

Here are some helpful links:



function pairwise(arr, arg) {
  var answers = [];
  var sum = 0;
  if(arr.length < 1){return 0;}
  for(var i = 0; i < arr.length; i++){
    for(var j = i + 1; j < arr.length; j++){
      if(arr[i] + arr[j]===arg && answers.indexOf(i)== -1 && answers.indexOf(j)== -1){
        answers.push(i,j);
      }
    }
  }
  sum = answers.reduce(function(a,b){
    return a + b;
  });
  return sum;
}

pairwise([1,4,2,3,0,5], 7);

Ответы:

pairwise([1, 4, 2, 3, 0, 5], 7)
return 11.

pairwise([1, 3, 2, 4], 4)
return 1.

pairwise([1, 1, 1], 2)
return 1.

pairwise([0, 0, 0, 0, 1, 1], 1)
return 10.

pairwise([], 100)
return 0.


(29)Map the Debris


день программы "#100 Days Of Code"
Return a new array that transforms the element's average altitude into their orbital periods.
The array will contain objects in the format {name: 'name', avgAlt: avgAlt}.
You can read about orbital periods on wikipedia.
The values should be rounded to the nearest whole number. The body being orbited is Earth.
The radius of the earth is 6367.4447 kilometers, and the GM value of earth is 398600.4418 km3s-2.



Here are some helpful links:

function orbitalPeriod(arr) {
 var GM = 398600.4418;
  var earthRadius = 6367.4447;
var answer =[];

  var radius;
  
  for (var i = 0; i < arr.length; i++){
    answer[i]= {};
   answer[i].name = arr[i].name;
    
    radius =earthRadius + arr[i].avgAlt;
    answer[i].orbitalPeriod = Math.round(2 * Math.PI *Math.sqrt((Math.pow(radius,3))/GM));

}
return answer;

}

orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]);



Ответы:
orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}])
return [{name: "sputnik", orbitalPeriod: 86400}].

orbitalPeriod([{name: "iss", avgAlt: 413.6}, {name: "hubble", avgAlt: 556.7}, {name: "moon", avgAlt: 378632.553}])
return [{name : "iss", orbitalPeriod: 5557}, {name: "hubble", orbitalPeriod: 5734}, {name: "moon", orbitalPeriod: 2377399}].

(28)Make a Person

Make a Person
28-ой день программы "#100 Days Of Code"

Fill in the object constructor with the following methods below:

getFirstName()
getLastName()
getFullName()
setFirstName(first)
setLastName(last)
setFullName(firstAndLast)

Run the tests to see the expected output for each method.

The methods that take an argument must accept only one argument and it has to be a string.

These methods must be the only available means of interacting with the object.

Here are some helpful links:



var Person = function(firstAndLast) {
  var namesArr = firstAndLast.split(" ");
  
  this.getFirstName = function(){
    return namesArr[0];
  };
  this.getLastName = function(){
    return namesArr[1];
  };
  this.getFullName = function(){
    return namesArr.join(" ");
  };
  this.setFirstName = function(first){
    namesArr[0] = first;
  };
  this.setLastName = function(last){
    namesArr[1] = last;
  };
  this.setFullName = function(firstAndLast){
    namesArr = firstAndLast.split(' ');
  };
    return firstAndLast;
};

var bob = new Person('Bob Ross');
bob.getFullName();




(27)Friendly Date Ranges


27-ой день программы "#100 Days Of Code"

Convert a date range consisting of two dates formatted as YYYY-MM-DD into a more readable format.

The friendly display should use month names instead of numbers and ordinal dates instead of cardinal (1st instead of 1).

Do not display information that is redundant or that can be inferred by the user: if the date range ends in less than a year from when it begins, do not display the ending year.

Additionally, if the date range begins in the current year (i.e. it is currently the year 2016) and ends within one year, the year should not be displayed at the beginning of the friendly range.

If the range ends in the same month that it begins, do not display the ending year or month.

Examples:

makeFriendlyDates(["2016-07-01", "2016-07-04"]) should return ["July 1st","4th"]

makeFriendlyDates(["2016-07-01", "2018-07-04"]) should return ["July 1st, 2016", "July 4th, 2018"].



function makeFriendlyDates(str) {
   
 
  var months = ['January','February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  
   function convertDate(str) {
    var dateStr = str.split('-');
    return (new Date(Date.UTC(dateStr[0], dateStr[1] - 1, dateStr[2])));

  }
  var dateA = convertDate(str[0]);
  var dateB = convertDate(str[1]);
  
  function dayEnd (val){
   if(val==1 || val ==21 || val == 31){
     return val +'st';
   }else if(val == 2 || val == 22){
     return val + 'nd';
   } else if(val == 3 || val == 33){
     return val +'rd';
   }else{
     return val + 'th';
   }
  }

   function monthDiff(dateA, dateB) {
    var monthB = dateB.getUTCFullYear() * 12 + dateB.getUTCMonth();
    var monthA = dateA.getUTCFullYear() * 12 + dateA.getUTCMonth();
    return monthB - monthA;
  }

  
  function dayDiff(dateA, dateB) {
    if(dateB.getUTCMonth() === dateA.getUTCMonth()){
      return dateA.getUTCDate()-dateB.getUTCDate();
    }
    return 0;
  }

  
  function getMonth(date) {
    return months[date.getUTCMonth()];
  }
 


  
 function displayDate() {

   
    if (dateB.getTime() - dateA.getTime() === 0) {
      return [getMonth(dateA) + ' ' + dayEnd(dateA.getUTCDate()) + ', ' + dateA.getUTCFullYear()];
    }

    
    if (dateA.getUTCMonth() === dateB.getUTCMonth() && dateA.getUTCFullYear() === dateB.getUTCFullYear()) {
      return [getMonth(dateA) + ' ' + dayEnd(dateA.getUTCDate()), dayEnd(dateB.getUTCDate())];
    }

    
    if (monthDiff(dateA, dateB) < 12 && dateA.getUTCFullYear() !== dateB.getUTCFullYear() ) {
      return [getMonth(dateA) + ' ' + dayEnd(dateA.getUTCDate()), getMonth(dateB) + ' ' + dayEnd(dateB.getUTCDate())];
    }

    
    if (monthDiff(dateA, dateB) <= 12 && dayDiff(dateA, dateB)>0) {
      return [getMonth(dateA) + ' ' + dayEnd(dateA.getUTCDate())+', '+dateA.getUTCFullYear(), getMonth(dateB) + ' ' + dayEnd(dateB.getUTCDate())];
    }

    if (monthDiff(dateA, dateB) < 12) {
      return [getMonth(dateA) + ' ' + dayEnd(dateA.getUTCDate())+', '+dateA.getUTCFullYear(), getMonth(dateB) + ' ' + dayEnd(dateB.getUTCDate())];
    }

   
    return [getMonth(dateA) + ' ' + dayEnd(dateA.getUTCDate()) + ', ' + dateA.getUTCFullYear(), getMonth(dateB) + ' ' + dayEnd(dateB.getUTCDate()) + ', ' + dateB.getUTCFullYear()];
  }
  
  

  return displayDate();
}

makeFriendlyDates(['2016-07-01', '2016-07-04']);



Ответы:

makeFriendlyDates(["2016-07-01", "2016-07-04"])
return ["July 1st","4th"].

makeFriendlyDates(["2016-12-01", "2017-02-03"])
return ["December 1st","February 3rd"].

makeFriendlyDates(["2016-12-01", "2018-02-03"])
return ["December 1st, 2016","February 3rd, 2018"].

makeFriendlyDates(["2017-03-01", "2017-05-05"])
return ["March 1st, 2017","May 5th"]

makeFriendlyDates(["2018-01-13", "2018-01-13"])
return ["January 13th, 2018"].

makeFriendlyDates(["2022-09-05", "2023-09-04"])
return ["September 5th, 2022","September 4th"].

makeFriendlyDates(["2022-09-05", "2023-09-05"])
return ["September 5th, 2022","September 5th, 2023"].


(26) No repeats please

No repeats please
26-ой день программы "#100 Days Of Code"

Return the number of total permutations of the provided string that don't have repeated consecutive letters. Assume that all characters in the provided string are each unique.

For example, aab should return 2 because it has 6 total permutations (aab, aab, aba, aba, baa, baa), but only 2 of them (aba and aba) don't have the same letter (in this case a) repeating.

Более подробно о первом варианте решения, можно прочитать здесь! macengr.wordpress.com



function permAlone(str) {
 
  if(str.length===0){
    return 1;
  }
   var amount=0;
  for(var i = 0; i < str.length; i++){
    if(str[i]!== arguments[1]){
      amount +=permAlone(str.substring(0,i)+str.substring(i+1),str[i]);
      
    }
  }
  return amount;
}

permAlone('aab');



Using a Heap Algorithm to generate all permutations


function permAlone(str) {
  
  var arr = str.split('');
  var permutations = [];
  var regex = /(.)\1+/g;
  
  function swap(index1, index2) {
    var aux = arr[index1];
    arr[index1] = arr[index2];
    arr[index2] = aux;
  }
  
  function generate(int) {
    if (int === 1) {
      permutations.push(arr.join(''));
    } else {
      for (var i = 0; i < int - 1; i++) {
        generate(int - 1);
        if (int % 2 === 0) {
          swap(i, int-1);
        } else {
          swap(0, int-1);
        }
      }
      generate(int - 1);
    }  
  }      
  
  generate(arr.length);
  
  var filtered = permutations.filter(function(string) {
    return !string.match(regex);
  });
  
  return filtered.length;

Ответы:

permAlone("aab")
return a number.

permAlone("aab")
return 2.

permAlone("aaa")
return 0.

permAlone("aabb")
return 8.

permAlone("abcdefa")
return 3600.

permAlone("abfdefa")
return 2640.

permAlone("zzzzzzzz")
return 0.

permAlone("a")
return 1.

permAlone("aaab")
return 0.

permAlone("aaabb")
return 12.


(25) Inventory Update

Inventory Update
25-ый день программы "#100 Days Of Code"

Compare and update the inventory stored in a 2D array against a second 2D array of a fresh delivery. Update the current existing inventory item quantities (in arr1). If an item cannot be found, add the new item and quantity into the inventory array. The returned inventory array should be in alphabetical order by item.



function updateInventory(arr1, arr2) {
    // All inventory must be accounted for or you're fired!
  for(var i = 0; i < arr1.length; i++){
    for(var j = 0; j < arr2.length; j++){
     if(arr1[i][1] ===arr2[j][1]){
       arr1[i][0] += arr2[j][0];
         arr2.splice(j, 1);
          j--;
     }     
   }
  }
   arr1 = arr1.concat(arr2); 
  arr1.sort(function(a,b){
    return a[1] > b[1];
  });
    return arr1;
}

// Example inventory lists
var curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"]
];

var newInv = [
    [2, "Hair Pin"],
    [3, "Half-Eaten Apple"],
    [67, "Bowling Ball"],
    [7, "Toothpaste"]
];

updateInventory(curInv, newInv);



Ответы:

The function updateInventory
return an array.

updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]).length
return an array with a length of 6.

updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])
return [[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]].

updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [])
return [[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]].

updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])
return [[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]].

updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]])
return [[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]].


(24)Exact Change

Exact Change
24-ый день программы "#100 Days Of Code"

Design a cash register drawer function checkCashRegister() that accepts purchase price as the first argument (price), payment as the second argument (cash), and cash-in-drawer (cid) as the third argument.

cid is a 2D array listing available currency.

Return the string "Insufficient Funds" if cash-in-drawer is less than the change due. Return the string "Closed" if cash-in-drawer is equal to the change due.

Otherwise, return change in coin and bills, sorted in highest to lowest order.




function checkCashRegister(price, cash, cid) {
  var change=[];
  // Here is your change, ma'am.
 var money =[["PENNY", 1], ["NICKEL", 5], ["DIME", 10], ["QUARTER", 25], ["ONE", 100], ["FIVE", 500], ["TEN", 1000], ["TWENTY", 2000], ["ONE HUNDRED", 10000]];
  var debt = cash * 100 - price*100;
  var cashInDrawer = 0;
  var rating = 0;
  
  for(i = money.length - 1; i >= 0; i--){
    cid[i][1] = Math.round(cid[i][1] * 100);
    cashInDrawer += cid[i][1];
    rating = 0;
    if(debt >= money[i][1]){
      while(cid[i][1] - money[i][1] >= 0){
        if(debt - money[i][1] >= 0){
          cid[i][1] -= money[i][1];
          debt -=money[i][1];
          cashInDrawer -= money[i][1];
          rating += money[i][1];
        } else {
          break;
        }
      }
      change.push([money[i][0], rating/100]);
    }
  }
  
  if(debt > 0){
    return "Insufficient Funds";
  } else if(cashInDrawer === 0){
    return "Closed";
  }
  return change;
}

// Example cash-in-drawer array:
// [["PENNY", 1.01],
// ["NICKEL", 2.05],
// ["DIME", 3.10],
// ["QUARTER", 4.25],
// ["ONE", 90.00],
// ["FIVE", 55.00],
// ["TEN", 20.00],
// ["TWENTY", 60.00],
// ["ONE HUNDRED", 100.00]]

checkCashRegister(19.50, 20.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);



Ответы:

checkCashRegister(19.50, 20.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]])
return an array.

checkCashRegister(19.50, 20.00, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])
return a string.

checkCashRegister(19.50, 20.00, [["PENNY", 0.50], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])
return a string.

checkCashRegister(19.50, 20.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]])
return [["QUARTER", 0.50]].

checkCashRegister(3.26, 100.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]])
return [["TWENTY", 60.00], ["TEN", 20.00], ["FIVE", 15.00], ["ONE", 1.00], ["QUARTER", 0.50], ["DIME", 0.20], ["PENNY", 0.04]].

checkCashRegister(19.50, 20.00, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])
return "Insufficient Funds".

checkCashRegister(19.50, 20.00, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1.00], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])
return "Insufficient Funds".

checkCashRegister(19.50, 20.00, [["PENNY", 0.50], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 0], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]])
return "Closed".


(23)Symmetric Difference

(23)Symmetric Difference
23-ий день программы "#100 Days Of Code"



function sym(args) {
  return Array.prototype.reduce.call(arguments,(a,b)=>a.filter(c=>b.every(d=>c!=d)).concat(b.filter(c=>a.every(d=>c!=d))),[]).filter((e,i,a)=>a.indexOf(e)===i);
}

sym([1, 2, 3], [5, 2, 1, 4]);



const sym = (...args) => {    
  return args.reduce((acc, curr) => {
    // change curr to hold unique values
    const set = new Set(curr)
    curr = Array.from(set)
    
    return acc.filter(a => !curr.includes(a)).concat(curr.filter(b => !acc.includes(b)))
  }, [])
}

sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])

Ответы:

sym([1, 2, 3], [5, 2, 1, 4])
return [3, 4, 5].

sym([1, 2, 3], [5, 2, 1, 4])
contain only three elements.

sym([1, 2, 5], [2, 3, 5], [3, 4, 5])
return [1, 4, 5]

sym([1, 2, 5], [2, 3, 5], [3, 4, 5])
contain only three elements.

sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])
return [1, 4, 5].

sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])
contain only three elements.

sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])
return [2, 3, 4, 6, 7].

sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])
contain only five elements.

sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])
return [1, 2, 4, 5, 6, 7, 8, 9].

sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])
contain only eight elements.


Запись коллекции (22) Record Collection

Record Collection
22-ой день программы "#100 Days Of Code"

Текст задания привожу полностью:

You are given a JSON object representing a part of your musical album collection. Each album has several properties and a unique id number as its key. Not all albums have complete information.

Write a function which takes an album's id (like 2548), a property prop (like "artist" or "tracks"), and a value (like "Addicted to Love") to modify the data in this collection.

If prop isn't "tracks" and value isn't empty (""), update or set the value for that record album's property.

Your function must always return the entire collection object.

There are several rules for handling incomplete data:

If prop is "tracks" but the album doesn't have a "tracks" property, create an empty array before adding the new value to the album's corresponding property.

If prop is "tracks" and value isn't empty (""), push the value onto the end of the album's existing tracks array.

If value is empty (""), delete the given prop property from the album.



Попробовал разные варианты решения. Этот мне понравился больше всего. Вначале отсекаем пустую строку. Если строка пустая, то удаляем свойства.

Если свойство не traks, то изменяем значение.

Если в альбоме нет свойства traks, то добавляем его и создаем пустой массив



// Setup
var collection = {
    "2548": {
      "album": "Slippery When Wet",
      "artist": "Bon Jovi",
      "tracks": [ 
        "Let It Rock", 
        "You Give Love a Bad Name" 
      ]
    },
    "2468": {
      "album": "1999",
      "artist": "Prince",
      "tracks": [ 
        "1999", 
        "Little Red Corvette" 
      ]
    },
    "1245": {
      "artist": "Robert Palmer",
      "tracks": [ ]
    },
    "5439": {
      "album": "ABBA Gold"
    }
};
// Keep a copy of the collection for tests
var collectionCopy = JSON.parse(JSON.stringify(collection));

// Only change code below this line
function updateRecords(id, prop, value) {
   if(value===''){
    delete collection[id][prop];
  } else if(prop !="tracks"){
    collection[id][prop] = value;
  } else {
  if(!collection[id].hasOwnProperty('tracks')){
    collection[id][prop] = [];
   
  } 
    collection[id][prop].push(value);
  }
  
  return collection;
}

// Alter values below to test your code
updateRecords(5439, "artist", "ABBA");




Ответы:

After updateRecords(5439, "artist", "ABBA"),
artist should be "ABBA"

After updateRecords(5439, "tracks", "Take a Chance on Me"),
tracks should have "Take a Chance on Me" as the last element.

After updateRecords(2548, "artist", ""),
artist should not be set

After updateRecords(1245, "tracks", "Addicted to Love"),
tracks should have "Addicted to Love" as the last element.

After updateRecords(2468, "tracks", "Free"),
tracks should have "1999" as the first element.

After updateRecords(2548, "tracks", ""),
tracks should not be set


Выбрать № тел. США (21)Validate US Telephone Numbers

Выбрать № тел. США
21-ый день программы "#100 Days Of Code"

Несмотря на кажущуюся простоту задания, оно забрало у меня достаточно много времени. Время было потрачено с пользой на углубленное изучение дополнительного материала по регулярным выражениям!

Учитывая то, что нам предложено в задании сделать возврат именно в булевом выражении, то я остановился на методе test()

Решил воспользоваться подсказкой, которую дали в задании. Для этого приведу его полностью:

Return true if the passed string is a valid US phone number.

The user may fill out the form field any way they choose as long as it is a valid US number. The following are examples of valid formats for US numbers (refer to the tests below for other variants):

555-555-5555
(555)555-5555
(555) 555-5555
555 555 5555
5555555555
1 555 555 5555

For this challenge you will be presented with a string such as 800-692-7753 or 8oo-six427676;laskdjf. Your job is to validate or reject the US phone number based on any combination of the formats provided above. The area code is required. If the country code is provided, you must confirm that the country code is 1. Return true if the string is a valid US phone number; otherwise return false.

В общем, я решил пойти путем простым и просто выбрать номера, которые будут являться допустимыми стандартами США

Так как, метод test() вернет значение true если номера заданы по стандарту, то мне осталось просто прописать это в условие. Для наглядности, я вынес его в отдельную переменную.

^ - начало, $- конец строки(якоря) И далее - первая единица или пробел , ? - ленивый поиск В скобочную группу выбрал первые три цифры в скобках или без, Далее пробел или "-" в наборе (диапазоне), затем три цифры и опять или пробел или дефис и четыре цифры. Ну и везде - ленивый поиск.

В этом задании задействованы почти все классы, символы и прочее, что можно было почерпнуть в учебнике.

Думаю, что для более подробного изучения, мне стоит к этому еще не раз вернуться. Пока что, я постарался выбрать и объяснить решение именно так.



function telephoneCheck(str) {

    var re = /^1? ?(\(\d{3}\)|\d{3})[ -]?\d{3}[ -]?\d{4}$/;
   

    return re.test(str);
}

telephoneCheck("555)-555-5555");



Ответы:

telephoneCheck("555-555-5555")
return a boolean.

telephoneCheck("1 555-555-5555")
return true.

telephoneCheck("1 (555) 555-5555")
return true.

telephoneCheck("5555555555")
return true.

telephoneCheck("555-555-5555")
return true.

telephoneCheck("(555)555-5555")
return true.

telephoneCheck("1(555)555-5555")
return true.

telephoneCheck("555-5555")
return false.

telephoneCheck("5555555")
return false.

telephoneCheck("1 555)555-5555")
return false.

telephoneCheck("1 555 555 5555")
return true.

telephoneCheck("1 456 789 4444")
return true.

telephoneCheck("123**&!!asdf#")
return false.

telephoneCheck("55555555")
return false.

telephoneCheck("(6505552368)")
return false

telephoneCheck("2 (757) 622-7382")
return false.

telephoneCheck("0 (757) 622-7382")
return false.

telephoneCheck("-1 (757) 622-7382")
return false

telephoneCheck("2 757 622-7382")
return false.

telephoneCheck("10 (757) 622-7382")
return false.

telephoneCheck("27576227382")
return false.

telephoneCheck("(275)76227382")
return false.

telephoneCheck("2(757)6227382")
return false.

telephoneCheck("2(757)622-7382")
return false.

telephoneCheck("555)-555-5555")
return false.

telephoneCheck("(555-555-5555")
return false.

telephoneCheck("(555)5(55?)-5555")
return false.


Аргументы дополнительные (20) Arguments Optional

Аргументы дополнительные
20-ый день программы "#100 Days Of Code"

Наша задача - Создайте функцию, которая суммирует два аргумента вместе. Если только один аргумент указан, то возвращает функцию, которая ожидает один аргумент и возвращает сумму.


For example, addTogether(2, 3) should return 5, and addTogether(2) should return a function.
Calling this returned function with a single argument will then return the sum:
var sumTwoAnd = addTogether(2);
sumTwoAnd(3) returns 5.

Далее создадим переменную для результата и начинаем создание условий "Если"

Если длина всего псевдомассива аргументов три и менее, то первый аргумент будет равен первой переменной а второй - другой. Создали эти переменные.

Честно говоря, я посмотрел в результаты, которые будет принимать и отдавать наша функция и немножко поленился делать проверку на !isNaN(), но ниже я приведу решение полностью

Теперь нам на помощь приходит typeof(). Проверяем, является ли второй аргумент числом и если да, то проверим и второй. Если оба - числа, то вернем их сумму.

Иначе, если второй аргумент не определен, а первый это число, то вернем функцию (как по условию задания), которая заведомо вернет undifened

Предложены ссылки:



function addTogether() {
  var results;
  if(arguments.length <=3){
    var a1 = arguments[0];
    var a2 = arguments[1];
    if(typeof(a2)==='number'){
      if(typeof(a1) ==='number'){
      
        results = a1 +a2;
      }
    } else if(a2===undefined && typeof(a1)==='number'){
      return function(a2){
        if(typeof(a2)==='number'){
          return a1 + a2;
        }
        else return results;
      };
    }
  }
  return results;
}

addTogether(2,3);



С проверкой на NaN


unction addTogether() {
  var response;
  if (arguments.length <= 3) { 
    var a = arguments[0];
    var b = arguments[1];
    if (!isNaN(b) && typeof(b) === 'number') { 
      if (!isNaN(a) && typeof(a) === 'number') {
        response = a + b;
      } 
    } else if (b === undefined && typeof(a) === 'number') {
      return function(b) {
        if (!isNaN(b) && !isNaN(a) && typeof(b) === 'number' && arguments.length === 1) { return a + b; }
        else return response;
      };
    }
  }  
  return response;
}

addTogether(2)(3);

Ответы:

convertHTML("abc")
return abc.



addTogether(2, 3)
return 5.

addTogether(2)(3)
return 5.

addTogether("http://bit.ly/IqT6zt")
return undefined.

addTogether(2, "3")
return undefined.

addTogether(2)([3])
return undefined.


Функция повтора строки заданное кол-во раз (19) -Repeat a string repeat a string

Функция повтора строки заданное кол-во раз

-Repeat a string repeat a string
19-ый день программы "#100 Days Of Code"

Не знаю, стоит ли здесь что - либо объяснять, но попробую.

Итак, мы должны повторить строку определенное кол-во раз (равное - num). Для этого есть метод str.repeat(num)

Он позволяет нам проделать эту операцию сразу.

В условии, так же сказано, что при num < 0 , функция должна вернуть пустую строку.

Я написал это условие через if



function repeatStringNumTimes(str, num) {
  
  if(num > 0){
    return str.repeat(num);
  } else {
    str = "";
  }
  return str;
}

repeatStringNumTimes("abc", 3);



Ответы:

repeatStringNumTimes("*", 3)
return "***".

repeatStringNumTimes("abc", 3)
return "abcabcabc"

repeatStringNumTimes("abc", 4)
return "abcabcabcabc"

repeatStringNumTimes("abc", 1)
return "abc".

repeatStringNumTimes("*", 8)
return "********"

repeatStringNumTimes("abc", -2)
return ""