As always, I think it's fun to try to express the high-level logic in lines which are close to natural language. And then have some lower-level functions with the more common style, of course.
function getGrade(...all_marks) { this_years_rules='students get grade A when average of marks is at least 90, B when 80 or more, a D if they reach at least 60, and F otherwise'; return grade_of_student_with(average_of(all_marks)).applying(this_years_rules); function grade_of_student_with(average_of_marks) { return { applying:rules=>rules.split(',') .map(rule=>/ ([A-Z]) \D*([0-9]*)/.exec(rule).slice(1)) .filter(([grade,threshold])=>average_of_marks>=(+threshold||0)) [0][0] }; } function average_of(numbers) { return numbers.reduce((sum,n)=>sum+n,0)/numbers.length; } }
function getGrade (s1, s2, s3) {let avg = (s1 + s2 + s3) / 3;if (avg >= 90) {return "A"- function getGrade(...all_marks) {
- this_years_rules='students get grade A when average of marks is at least 90, B when 80 or more, a D if they reach at least 60, and F otherwise';
- return grade_of_student_with(average_of(all_marks)).applying(this_years_rules);
- function grade_of_student_with(average_of_marks) {
- return {
- applying:rules=>rules.split(',')
- .map(rule=>/ ([A-Z]) \D*([0-9]*)/.exec(rule).slice(1))
- .filter(([grade,threshold])=>average_of_marks>=(+threshold||0))
- [0][0]
- };
- }
else if (avg >= 80) {return "B"- function average_of(numbers) {
- return numbers.reduce((sum,n)=>sum+n,0)/numbers.length;
- }
else if (avg >= 70) {return "C"}else if (avg >= 60) {return "D"}else {return "F"}- }
const chai = require("chai"); const assert = chai.assert; const Test = require("@codewars/test-compat"); describe("Solution", function() { it("Hey! Good job!", function() { Test.assertEquals(getGrade(69, 94, 31), "D"); Test.assertEquals(getGrade(95, 89, 92), "A"); Test.assertEquals(getGrade(68, 91, 95), "B"); Test.assertEquals(getGrade(0, 65, 13), "F"); }); });
- const chai = require("chai");
- const assert = chai.assert;
- const Test = require("@codewars/test-compat");
- describe("Solution", function() {
- it("Hey! Good job!", function() {
- Test.assertEquals(getGrade(69, 94, 31), "D");
- Test.assertEquals(getGrade(95, 89, 92), "A");
- Test.assertEquals(getGrade(68, 91, 95), "B");
- Test.assertEquals(getGrade(0, 65, 13), "F");
- });
- });
67 bytes
I sometimes like to have the top-level logic read (almost) like plain english.
Here's a first shot at that :)
function rps(player_one, player_two) { let rules='rock breaks scissors, scissors cut paper, paper covers rock'; if(both_players_play_same_item()) { return "Draw!"; } else if(player_one_beats_player_two()) { return "Player 1 won!"; } else { return "Player 2 won!"; } function both_players_play_same_item() { return player_one==player_two; } function player_one_beats_player_two() { return rules.match(player_one+' [^,]+ '+player_two); } }
const rps = (p1, p2) => {if (p1 === p2) return "Draw!";var rules = {rock: "scissors", paper: "rock", scissors: "paper"};if (p2 === rules[p1]) {- function rps(player_one, player_two) {
- let rules='rock breaks scissors, scissors cut paper, paper covers rock';
- if(both_players_play_same_item()) {
- return "Draw!";
- } else if(player_one_beats_player_two()) {
- return "Player 1 won!";
}else {- } else {
- return "Player 2 won!";
- }
};- function both_players_play_same_item() {
- return player_one==player_two;
- }
- function player_one_beats_player_two() {
- return rules.match(player_one+' [^,]+ '+player_two);
- }
- }
Even shorter :)
Building upon previous idea, trying a more concise but less readable representation of the various game combinations.
function rps(a,b) { return a==b ? 'Draw!' : `Player ${1+['sr','ps','rp'].includes(a[0]+b[0])} won!`; }
function rps(player1, player2) {return player1 == player2 ? 'Draw!' :player1 == 'rock' && player2 == 'scissors' ||player1 == 'scissors' && player2 == 'paper' ||player1 == 'paper' && player2 == 'rock' ? 'Player 1 won!' : 'Player 2 won!';- function rps(a,b) {
- return a==b
- ? 'Draw!'
- : `Player ${1+['sr','ps','rp'].includes(a[0]+b[0])} won!`;
- }
def print_String(): # Printing the index of a string in the list. lst = ['double', 'switch', 'off', 'on', 'jump'] print(lst.index('double')) # Reversing the items in the list print('Reversed List:',lst[::-1])
- def print_String():
- # Printing the index of a string in the list.
- lst = ['double', 'switch', 'off', 'on', 'jump']
print (lst.index('double'))- print(lst.index('double'))
- # Reversing the items in the list
print ('Reversed List:',lst.reverse())- print('Reversed List:',lst[::-1])
This solution both avoids the repetition of Number.integer(n/divisor) AND allows for any number of divisors.
This slight shuffle makes the function more robust when given non-array values. Not sure that's a desirable feature :-/
const flatten = a => Array.isArray(a) ? a.reduce((acc,item) => acc.concat(flatten(item)), []) : a;
const flatten = arr =>arr.reduce((acc, item) => acc.concat(Array.isArray(item) ? flatten(item) : item), []);- const flatten = a =>
- Array.isArray(a) ? a.reduce((acc,item) => acc.concat(flatten(item)), []) : a;
describe("Test cases", function() { it("[1, 2, [3, 5], [[4, 3], 2]]", function() { Test.assertSimilar(flatten([1, 2, [3, 5], [[4, 3], 2]]), [1, 2, 3, 5, 4, 3, 2]); }); it("[[1, [5], [], [[-3, 'hi']]], 'string', 10, [[[5]]]]", function() { Test.assertSimilar(flatten([[1, [5], [], [[-3, 'hi']]], 'string', 10, [[[5]]]]), [1, 5, -3, 'hi', 'string', 10, 5]); }); it("not arrays", function() { Test.assertEquals(flatten(123), 123); Test.assertEquals(flatten('abc'), 'abc'); }); });
const flatten = arr =>arr.reduce((acc, item) => acc.concat(Array.isArray(item) ? flatten(item) : item), []);- describe("Test cases", function() {
- it("[1, 2, [3, 5], [[4, 3], 2]]", function() {
- Test.assertSimilar(flatten([1, 2, [3, 5], [[4, 3], 2]]), [1, 2, 3, 5, 4, 3, 2]);
- });
- it("[[1, [5], [], [[-3, 'hi']]], 'string', 10, [[[5]]]]", function() {
- Test.assertSimilar(flatten([[1, [5], [], [[-3, 'hi']]], 'string', 10, [[[5]]]]), [1, 5, -3, 'hi', 'string', 10, 5]);
- });
- it("not arrays", function() {
- Test.assertEquals(flatten(123), 123);
- Test.assertEquals(flatten('abc'), 'abc');
- });
- });