[04.12.22] Codewars

5854 단어 CodewarsCodewars

How good are you really?

Description

There was a test in your class and you passed it. But you want to know if you're better than the average student in your class.
You receive an array with your peers' test scores. Now calculate the average and compare your score!
Return True if you're better, else False!

My answer

function betterThanAverage(classPoints, yourPoints) {
   let sum = 0;
   for (let i = 0; i < classPoints.length; i++) {
     sum = sum + classPoints[i];
   };
  let average = sum / classPoints.length;
  let result;
  average < yourPoints ? result = true : result = false;
  
  return result;
}

Other solutions

function betterThanAverage(classPoints, yourPoints) {
  return yourPoints > classPoints.reduce((a, b) => a + b, 0) / classPoints.length; 
}

Wrap up

reduce function

array.reduce(callback[, initialValue])

Parameters

callbackFn
  1. accumulator
  2. currentValue
  3. currentIndex(optional)
  4. array(optional)
initialValue(optional)

Examples

let total = [ 0, 1, 2, 3 ].reduce(
  ( accumulator, currentValue ) => accumulator + currentValue,
  0
);
// total is 6
// To sum up the values contained in an array of objects, you mush supply an initialValue, so that each item passes through your funtcion.
let initialValue = 0;
let sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) {
    return accumulator + currentValue.x;
}, initialValue)
// sum is 6
let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  ( previousValue, currentValue ) => previousValue.concat(currentValue),
  []
)
// flattened is [0, 1, 2, 3, 4, 5]
const myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
let myArrayWithNoDuplicates = myArray.reduce(function (previousValue, currentValue) {
  if (previousValue.indexOf(currentValue) === -1) {
    previousValue.push(currentValue)
  }
  return previousValue
}, [])
console.log(myArrayWithNoDuplicates)
const numbers = [-5, 6, 2, 0,];
const doubledPositiveNumbers = numbers.reduce((previousValue, currentValue) => {
  if (currentValue > 0) {
    const doubled = currentValue * 2;
    previousValue.push(doubled);
  }
  return previousValue;
}, []);
console.log(doubledPositiveNumbers); // [12, 4]

source: mdn web docs

Sum of positive

Description

You get an array of numbers, return the sum of all of the positives ones.
Note: if there is nothing to sum, the sum is default to 0.

My answer

function positiveSum(arr) {
  let newArray = arr.filter(num => num > 0);
  let result = newArray.reduce(function (acc, cur) {
    return acc + cur;
  }, 0);
  
  return result;
}

Other solutions

function positiveSum(arr) {
  var total = 0;    
  for (i = 0; i < arr.length; i++) {    // setup loop to go through array of given length
    if (arr[i] > 0) {                   // if arr[i] is greater than zero
      total += arr[i];                  // add arr[i] to total
    }
  }
  return total;                         // return total
}
function positiveSum(arr) {
   return arr.reduce((a,b)=> a + (b > 0 ? b : 0),0);
}

Square Every Digit

Description

In this kata, you are asked to square every digit of a number and concatenate them.
For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
Note: The function accepts an integer and returns an integer

My answer

function squareDigits(num){
  let stringArray = [...num.toString()];
  let array = stringArray.map(x => (parseInt(x) * parseInt(x)).toString());
  
  return parseInt(''.concat(...array));
}

Other solutions

function squareDigits(num){
  var array = num.toString().split('').map( function(int) {
    var i = parseInt(int);
    return i * i;
  });
  
  return parseInt(array.join(""));
}
function squareDigits(num){
  return Number(('' + num).split('').map(function (val) { return val * val;}).join(''));
}
function squareDigits(num){
  let result = num
    .toString()
    .split("")
    .map( num => parseInt(num) )
    .map( num => num * num )
    .join("")
   
  return parseInt(result)
}

Wrap up

concat function

string.concat(string2, string3[, ..., stringN)

Parameters

strN

One or more strings to concatenate to str.

Examples

let hello = 'Hello, '
console.log(hello.concat('Kevin', '. Have a nice day.'))
// Hello, Kevin. Have a nice day.

let greetList = ['Hello', ' ', 'Venkat', '!']
"".concat(...greetList)  // "Hello Venkat!"

"".concat({})    // [object Object]
"".concat([])    // ""
"".concat(null)  // "null"
"".concat(true)  // "true"
"".concat(4, 5)  // "45"

source: mdn web docs

좋은 웹페이지 즐겨찾기