[javascirpt] Regex

To Currency

function toCurrency(price){
  return price.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}

 

Deletion from Array:

function deleteValues(array, pred) {
   var i = 0,
       lng  = array.length;
  
  for(i = lng; i >=0; i--){
    if(pred(array[i])){
      array.splice(i, 1);
    }
  }
 
  return array;
}

 

Candy:

function candies(kids){
  if (kids.length < 2) return -1;
  
  var max = Math.max.apply(null, kids);
  var extraCandies = kids.reduce(function (total, kid) {
    return total + max - kid;
  }, 0);
  return extraCandies;
}

 

_ problem:

function searchNames( logins ){
   var failedLogin;
   failedLogin = logins.filter(function(login){
     return login[0].substr(login[0].length - 1) === '_';
   });
   
   return failedLogin;
}

 

Number of occerentce:

Array.prototype.numberOfOccurrences = function(search) {
  return this.filter( function(num){ return search === num } ).length;
}

 

Worrior:

var Warrior = function(name){
  this.name = name;  
  this.health = 100;
}

Warrior.prototype.strike = function(enemy, swings){
  enemy.health = Math.max(0, enemy.health - (swings * 10));   
}

 

isDivisable:

function isDivisible(firstN, ...otherN){
  return otherN.every(n => firstN % n === 0);
}

 

Stop gninnipS My sdroW!:

function spinWords(str){
  //TODO Have fun :)
  var words = str.split(' ');
  var s = words.map( (word) => {
    if(word.length >= 5){
      word = word.split('').reverse().join('');
      console.log(word);
    }
    
    return word;
  }).join(' ');

 

posted @ 2015-11-02 02:48  Zhentiw  阅读(324)  评论(0编辑  收藏  举报