Andres Bernal

Andres Bernal

Developer.

© 2019

Js code

js code

Paleta de colores

color: #000000 //black
color: #9F111B //red
color: #B11623 //redstate
color: #292C37 //blue
color: #CCCCCC //silver

JAVASCRIPT

  • message
    const hello = () => "Hello!!";
    console.log(hello());
    
  • Find the Index (Part 1)
search = (arr, index) => arr.indexOf(index)
  • Find the Index (Part 2)
search = (arr, index) => arr.indexOf(indes)
  • Maximum Edge of a Triangle
let nextEdge = (side1,side2) => (side1+side2)-1
  • Return the Next Number from the Integer Passed
let addition=n=>n+1
  • Return the First Element in an Array
let getFirstValue = (arr) => arr[0]
  • The Farm Problem
    animals = (chickens, caws, pigs) => chickens * 2 + (caws + pigs) * 4
    
  • Return the Sum of Two Numbers
let addition=(a,b)=>a+b
  • Profitable Gamble

let profitableGamble=(prob,prize,Pay)=>prob*prize-Pay>0
  • Is the Number Less than or Equal to Zero?
 
 let lessThanOrEqualToZero=a=>!(a>0)

 or 
 
 lessThanOrEqualToZero=num=> num <= 0;

  • Is the Number Less than or Equal to Zero?
 
 let lessThanOrEqualToZero=a=>!(a>0)

 or 
 
 lessThanOrEqualToZero=num=> num <= 0;

  • Check if an Integer is Divisible By Five
divisibleByFive = n => n%5===0
//or
divisibleByFive = n => !(n%5)
  • Check if an Integer is Divisible By Five
let triArea=(b,h)=>b*h/2
  • Concatenate First and Last Name into One String
 let concatName = (a, b) => b + ", " + a
 //or
  let concatName = (a, b) => `${b}, ${a}`;
  • Return the Remainder from Two Numbers
 let remainder = (x,y) => x % y
  • Recursion: Length of a String
 let length=s=>s.length
  • Compare Strings by Count of Characters
let comp = (str1, str2) => str1.length == str2.length
  • Is the String Empty?
    let isEmpty=s=>!s
    //or
    
    • Concatenating Two Integer Arrays
let concat = (a,b) => a.concat(b)
//or
const concat = (x, y) => [...x, ...y];
  • Volume of a Box
let volumeOfBox = sizes => sizes.width * sizes.length * sizes.height
  • Multiple of 100
let divisible=n=>n%100==0
  • Check if an Array Contains a Given Number
     let check=(arr,ele)=>arr.includes(ele)
     //or 
     let check = (arr, ele) => arr.indexOf(ele) != -1
    
  • String or Integer?
const intOrString=param=>
	+param?"int":"str"
//or
const intOrString = p => typeof p === 'string' ? 'str' : 'int';

  • Check String for Spaces
const hasSpaces = string => / /.test(string)
//or
const hasSpaces = (s) => s.includes(" ")

  • Extract City Facts
  cityFacts({
  name: "Paris",
  population: "2,140,526",
  continent: "Europe"
}) ➞ "Paris has a population of 2,140,526 and is situated in Europe"

cityFacts({
  name: "Tokyo",
  population: "13,929,286",
  continent: "Asia"
}) ➞ "Tokyo has a population of 13,929,286 and is situated in Asia"

  
let cityFacts=city=>city.name+" has a population of "+city.population+" and is situated in "+city.continent
  
//or

let cityFacts = city => `${city.name} has a population of ${city.population} and is situated in ${city.continent}`

  • Name Greeting!
    let helloName=n=>`Hello ${n}!`
    
  • Reverse an Array
let reverse=a=>a.reverse()
  • Stack the Boxes
    let stackBoxes = n => n * n
    
  • Find the Index

let find_index=(arr, string)=>arr.indexOf(string)
  • Is the Word Singular or Plural?

let isPlural=word=>word.endsWith('s')
  • Case Insensitive Comparison
const match = (s1, s2) => s1 === s2.toLowerCase();

-Is the Number Even or Odd?

let isEvenOrOdd=n=>n%2?'odd':'even'

  • To the Power of _____

let calculateExponent = Math.pow
  • Char-to-ASCII
let ctoa = c => c.charCodeAt()
  • The 3 Programmers Problem
let programmers = (one, two, three) => Math.max(one, two, three) - Math.min(one, two, three)
  • Return the Last Element in an Array
let getLastItem=arr=>arr.pop()
  • Limit a Number’s Value

const limitNumber = (num, low, h) => num < low ? low : num > higth ? higth : num;

Testing K^K == N?

let kToK = (n, k) => Math.pow(k, k)==n
  • Count the Arguments
let numArgs = (...i) => i.length
  • Count Syllables
numberSyllables = w => w.split('-').length
  • Slice of Pie
let equalSlices = (total, people, each) => total >= people*each
  • Return the Total Number of Parameters
numberArgs=(...a)=>a.length

  • Truthy or Falsy?

let isTruthy=input=>input?1:0
  • Return the First and Last Elements in an Array
const firstLast = arr => [arr.shift(), arr.pop()]
  • String to Integer and Vice Versa
const toInt = s => +s;

const toStr = i => ''+i;
  • Between Words
let isBetween = (first,last,word) => word > first && word < last;
  • Find the Total Number of Digits the Given Number Has
let findDigitAmount=n=>(''+n).length
//or
let findDigitAmount = n => n.toString().length
  • Both Zero, Negative or Positive
    const both = (a, b) => Math.sign(a) === Math.sign(b);
    //or
    const both = (n1, n2) => Math.sign(n1) === Math.sign(n2)
    
  • Get Word Count
    const countWords = str => str.split(' ').length;
    
  • Check if Number is within a Given Range
const isInRange = (num, range) => num >= range.min && num <= range.max;
  • Add, Subtract, Multiply or Divide?

function operation(num1, num2) {
	if (num1 + num2 == 24) {return "added"}
	if (num1 - num2 == 24) {return "subtracted"}
	if (num1 * num2 == 24) {return "multiplied"}
	if (num1 / num2 == 24) {return "divided"}
	return null
}

  • Convert Number to Corresponding Month Name
function month_name(num) {
	const mapping = {
		1: 'January',
		2: 'February',
		3: 'March',
		4: 'April',
		5: 'May',
		6: 'June',
		7: 'July',
		8: 'August', 
		9: 'September', 
		10:	'October', 
		11:	'November', 
		12:	'December'
	};
	return mapping[num];
}
  • Array from Comma-Delimited String
toArray("watermelon, raspberry, orange")
➞ ["watermelon", "raspberry", "orange"]

toArray("x1, x2, x3, x4, x5")
➞ ["x1", "x2", "x3", "x4", "x5"]

toArray("a, b, c, d")
➞ ["a", "b", "c", "d"]

toArray("")
➞ []

function toArray(str) {
	return str.length > 0 ? str.split(', '): [];
}
  • Return First and Last Parameter
function firstArg() {
	return arguments[0];
}

function lastArg() {
	return arguments[arguments.length-1];
}
  • Message

const howManyTimes = num => `Ed${'a'.repeat(num)}bit`;

//or

function howManyTimes(num) {
  return 'Ed' + 'a'.repeat(num)+'bit'

}
  • Capture the Rook
//yourRook, opponentsRook
let canCapture = ([y, o]) => y[0] == o[0] ? !0 : y[1] == o[1];

  • Find the Bug: Checking Even Numbers

checkAllEven=a=>a.every(x=>x%2==0)

  • Check if the Same Case
    const sameCase = s => /^([A-Z]+|[a-z]+)$/.test(s)
    
  • Maximum Difference
let difference = nums => Math.max(...nums) - Math.min(...nums)
  • Unlucky 13
    let unlucky13 = a => a.filter(a => a % 13)
    
  • Semantic Versioning
retrieveMajor = s => s.split('.')[0]
retrieveMinor = s => s.split('.')[1]
retrievePatch = s => s.split('.')[2]
  • Exists a Number Higher?
let existsHigher=(a,n)=>a.some(b=>b>=n)
//or
let existsHigher = (a, b) => Math.max(...a) >= b;
  • Remove Null from an Array
let removeNull=a=>a.filter(b=>b)
//or
let letremoveNull=a=>a.filter(b=>b!=null)
  • Word Endings
let addEnding =  (a, e)=> a.map(a => a+e)
  • Next Element in Arithmetic Sequence
let nextElement = a => a.pop()+(a[1]-a[0]);

  • Filter out Strings from an Array

Create a function which filters out strings from an array and returns a new array containing only integers.

filterList([1, 2, 3, "x", "y", 10]) ➞ [1, 2, 3, 10]

filterList([1, "a", 2, "b", 3, "c"]) ➞ [1, 2, 3]

filterList([0, -32, "&@A", 64, "99", -128]) ➞ [0, -32, 64,

const filterList = l => l.filter(x => x === +x);

//or
const filterList=l=>l.filter(e=>Number.isInteger(e))

  • Smaller String Number
smallerNum("21", "44") ➞ "21"

smallerNum("1500", "1") ➞ "1"

smallerNum("5", "5") ➞ "5"
let smallerNum = (n1,n2) => Math.min(n1,n2)+''
  • Strange Pair
let isStrangePair=(a,b)=>!a&&!b||a[0]==b[b.length-1]
  • Fix the Error / Comparing Arrays (Part #2)
let checkEquals = (a1,a2) => a1.join()==a2.join()

//or
const checkEquals = (x, y) => (String(x) === String(y))

Odd Up, Even Down


const transform = a => a.map(x => x % 2 ? x + 1 : x - 1)
transform = x => x.map(a => (a%2 === 0) ? a-1 : a+1);

Generate a Countdown of Numbers in an Array

const countdown = start => [...Array(start + 1).keys()].reverse();

//or

const countdown = a => Array(a + 1)
  .fill()
  .map((b, c) => c)
  .reverse();


  • Fix the Error: Vowel Edition
let removeVowels = s => s.replace(/[aeiou]/g, '')
  • Additive Inverse
 let additiveInverse=a=>a.map(x=>-x)

  var x =[];
	return  x.map(x => x*(-1));

Calculate Determinant of a 2x2 Matrix

let calcDeterminant = ([[a, b], [c, d]]) => a * d - b * c;
const calcDeterminant = ([[a, b], [c, d]]) =>a*d-b*c
  • Reverse Coding Challenge #3
let mysteryFunc = (a,n)=>a.map(e=>e%n)
  • Check Factors
let checkFactors = (a, n) => a.every(f => !(n%f))
  • Palindrome?
let checkPalindrome = s => s.split('').reverse().join('') == s
  • Recursion: Sum
const sum = (n) => n * (n+1) / 2; 

Hurdle Jump

hurdleJump=(a,n)=>a.every(b=>n>=b)

hurdleJump = (h, j) => Math.max(...h) <= j
  • Regex Series: String Contains at Least One Digit
    let x = /\d/
    
    • Get Student Names
 getStudentNames([
  { name: "Steve" },
  { name: "Mike" },
  { name: "John" }
]) ➞ ["Steve", "Mike", "John"]
getStudentNames = a => a.map(b => b.name)
  • Fix the Error: Mutating Arrays
const minusOne = y => y.slice(0, 4)
//or
minusOne = arr => arr.slice(0, -1);
  • Recursion: Reverse a String
let reverse = a => a.split("").reverse().join("")

Retrieve the Subreddit


const subReddit = a => a.split('/')[4];

const subReddit = link => link.slice(25, -1);
  • Remove the First and Last Characters
let removeFirstLast = s => s.slice(1, -1)||s;
  • Missing Third Angle
missingAngle = (x, y) => (x + y == 90 ? "right" : (x + y) < 90 ? "obtuse" : "acute")

  • Typing Game
const correctStream = (u, c) => u.map((x, i) => c[i] === x ? 1 : -1)
//or

correctStream = (u, c) => u.map(x => x == c[c.indexOf(x)] ? 1: -1)

  • Even Number Generator
let findEvenNums=n=>(h=Math.floor(n/2),Array(h).fill(0).map((x,i)=>i*2+2));
  • Little Dictionary

let dictionary = (i, W) => W.filter(w => w.startsWith(i))
  • Re-Form The Word
const getWord = (l, r) => l[0].toUpperCase() + l.slice(1) + r;

//or

getWord = (a, b) => a.charAt(0).toUpperCase() + a.slice(1) + b
  • Find the Largest Number in an Array
findLargestNum = a => Math.max(...a)
  • Multi-division

abcmath=(a,b,c)=>a*Math.pow(2,5)%c===0
  • Find the Smallest Number in an Array
function findSmallestNum(arr) {
  return Math.min(...arr);
}
  • Fix the Error: Filtering out Empty Arrays
removeEmptyArrays=a=>a.filter(x=>x!=false);
  • Convert Number to String of Dashes

    Go=(n)=>"-".repeat(n);
    
  • Hot Pics of Danny Devito!


const preventDistractions=str=>/anime|vine|roasts|Danny\sDevito/g.test(str)?'NO!'
:'Safe watching!';

//or

const preventDistractions = str => /anime|meme|vine|roasts|Danny Devito/.test(str) ? 'NO!' : 'Safe watching!';

Even Odd Partition


evenOddPartition=(a)=>[a.filter(x=>x %2==0),a.filter(x=> x %2 !==0)]
  • Recursion: Array Sum
const sum=r=>r.reduce((s,n)=>s+n,0);

Vowel Replacer

replaceVowels=(s,ch)=>s.replace(/[aeiou]/g,ch)

Is the Object Empty?

const isEmpty = o => !Object.keys(o)[0]
  • Multiply by Length
MultiplyByLength=a=>a.map(x=>x*a.length)

Get the File Extension

const getExtension = a => a.map(w => w.split('.')[1]);

X and Y Coordinates

convertCartesian = (a, b) => a.map((a, c) => [a, b[c]])

  • State Names and Abbreviations

filterStateNames=(a,t)=>t==='abb'?a.filter(b=>b.length===2):a.filter(b=>b.length>2)

Repeating Letters N Times

let repeat = (s, n) => [...s].map(x => x.repeat(n)).join('')

Filter by Digit Length

let  filterDigitLength = (a, n) => a.filter(x => (''+x).length == n)
  • Most Left Digit

const leftDigit = n => +n.match(/\d/gm)[0];

Say Hello to Guests

let greetPeople = n => n.map(v=>`Hello ${v}`).join(", ");
  • Flip the Boolean
reverse=b=>typeof b!=="boolean"?"boolean expected":!b
  • Calculate the Profit
profit({
  costPrice: 32.67,
  sellPrice: 45.00,
  inventory: 1200
}) ➞ 14796

profit({
  costPrice: 225.89,
  sellPrice: 550.00,
  inventory: 100
}) ➞ 32411

profit({
  costPrice: 2.77,
  sellPrice: 7.95,
  inventory: 8500
}) ➞ 44030

const profit=i=>Math.round((i.sellPrice-i.costPrice)*i.inventory)

Check if a String Contains only Identical Characters

let isIdentical = s => new Set(s).size == 1

Hamming Distance

String1: "abcbba"
String2: "abcbda"

Hamming Distance: 1 - "b" vs. "d" is the only difference.
let hammingDistance=([...str1], [...str2])=>str1.filter((a,b)=>a!=str2[b]).length
  • Nth Smallest Element
    const nthSmallest = (arr, n) => arr.sort()[n - 1] || null;
    
  • Shuffle the Name

let nameShuffle = s => s.split` `.reverse().join` `
  • Check if a Number is a Palindrome
isPalindrome = a => (a + "").split("").reverse().join("") == a
  • Product of All Odd Integers

const oddProduct = a => a.reduce((t, c) => t * (c%2 ? c : 1), 1);
  • Product Divisible by Sum?
divisible = a => !(a.reduce((a, b) => a*b) % a.reduce((a, b) => a+b))

Minimum Removals to Make Sum Even

const minimumRemovals = a => a.reduce((t,c) => t+c)%2

Return the Four Letter Strings

isFourLetters = a => a.filter(w => w.length == 4)
  • Check if String Ending Matches Second String

checkEnding=(a,b)=>a.endsWith(b)
  • Eliminate Odd Numbers within an Array
noOdds = a => a.filter(v => ~v%2)
//or

noOdds = a => a.filter(x => 1-x%2)
  • Lexicographically First and Last
let firstAndLast = s => [[...s].sort().join(''),[...s].sort().reverse().join('')]
//or

const firstAndLast = s => [
  [...s].sort().join(""),
  [...s]
    .sort()
    .reverse()
    .join("")
];

  • Same Number of Unique Elements
    const same = (a, b) => new Set(a).size == new Set(b).size;
    
  • Letters Only
let lettersOnly = s => s.replace(/[^a-z]/gi, "");
  • Repeat the Same Item Multiple Times
repeat = (s,n) => Array(n).fill(s)

  • Alphabet Soup
AlphabetSoup = s => [...s].sort().join``

//or
AlphabetSoup=s=>s.split``.sort().join``

  • Total Number of Unique Characters
const countUnique = (a, b) => new Set(a+b).size;
  • Add up the Numbers from a Single Number
let addUp = n => n * (n + 1) / 2
  • Reverse the Order of a String

reverse = s => [...s].reverse().join('')
  • Regex Series: Even Number?
let x = /[02468]$/
  • Retrieve the Last N Elements
let last=(a, n)=>n==0?[]:n>a.length?'invalid':a.slice(-n)
  • Hashes and Pluses

const hashPlusCount = str => [str.split('#').length - 1, str.split('+').length - 1];

//or

let hashPlusCount = s =>
[(s.match(/#/g)||[]).length,(s.match(/\+/g)||[]).length];

  • Mirror Array
const mirror = arr => [...arr, ...arr.reverse().slice(1)];

  • Find the Smallest and Biggest Numbers
    minMax = a => [Math.min(...a),Math.max(...a)]
    
  • Amplify the Multiples of 4
const amplify = num => [...Array(num).keys()].map(x => (x + 1) % 4 == 0 ? (x + 1) * 10 : x + 1);
  • Return the Index of the First Vowel
const firstVowel = s => s.search(/[aeiou]/i);
  • Prefixes vs. Suffixes

let isPrefix = (word, prefix) => word.startsWith(...prefix);
let isSuffix = (word, suffix) => word.endsWith(suffix.slice(1
  • Factorial of a Positive Integer
    factorial = a => (a ? a * factorial(--a) : 1)
    

Largest Swap

largestSwap = n => (''+n)[0]>=(''+n)[1]

Omnipresent Value


const isOmnipresent = (a, v) => a.every(x => x.includes(v))

Convert to Decimal Notation

convertToDecimal=a=>a.map(b=>parseFloat(b)/100)

Secret Society


let societyName = a => a.map(x=>[...x][0]).sort().join('');

//or
const societyName=arr=>arr.map(x=>x[0]).sort().join("")

Count Instances of a Character in a String

charCount = (a, b) => --b.split(a).length
  • Matchstick Houses
matchHouses = a => a && a*5+1
  • Bitwise Operations

bitwiseAND = (a, b) => a&b
bitwiseOR = (a, b) => a|b
bitwiseXOR = (a, b) => a^b
  • Say β€œHello” Say β€œBye”
const sayHelloBye=(name,num)=> 
(num?"Hello ":"Bye ")+name[0].toUpperCase()+name.slice(1)
  • Basic Statistics: Mean
const mean=x=>(x.reduce((t,n)=>t+n)/x.length).toFixed(1)*1;
  • Transforming Words into Binary Strings

const convertBinary = s => s.replace(/[a-m]/gi, 0).replace(/\D/g, 1);
  • Transform into an Array with No Duplicates
set=(arr) => [...new Set(arr)]

  • First and Last Index

charIndex = (w, c) => w.includes(c) ? [w.indexOf(c),w.lastIndexOf(c)] : undefined;}

or const charIndex = (str, c) => str.includes(c) ? [str.indexOf(c), str.lastIndexOf(c)] : undefined;

//or
charIndex=(word, char)=>
	word.indexOf(char) === -1 
	? undefined 
	: [word.indexOf(char), word.lastIndexOf(char)]

  • Filter out Strings from an Array
filterArray = arr => arr.filter(Number.isInteger)
  • Which Function Returns the Larger Number?
let whichIsLarger=(f, g)=>f()==g()?'neither':f()>g()?'f':'g'

  • Spelling it Out
const spelling = a => a.split('').map((b, c) => a.slice(0, ++c));
  • *Reverse the Case**

reverseCase=s=>s.split(``).map(a=>a!==a.toUpperCase()?a.toUpperCase():a.toLowerCase()).join(``)
  • Sum of Cubes
sumOfCubes = n => n.reduce((a,c) => a+Math.pow(c,3),0)

const sumOfCubes = a => a.reduce((b, c) => b + (c * c * c),0);
  • Recursion: Factorials
factorial = n => n < 1? 1: n*factorial(n-1);
  • Chat Room Status
function chatroomStatus(users) {
	return users.length === 0 ? 
		'no one online' :
		users.length <= 2 ? 
		users.join(' and ') + ' online': 
		users.slice(0, 2).join(', ') + 
		' and ' + (users.length - 2) + ' more online' 
}

//or
function chatroomStatus(users) {
	return users.length > 2 ? `${users[0]}, ${users[1]} and ${users.length - 2} more online`
		: users.length == 2 ? `${users[0]} and ${users[1]} online` 
		: users.length == 1 ? `${users[0]} online`
		: 'No one online';
}
  • Special Arrays
    const isSpecialArray = a => a.every((v, i) => v%2 == i%2);
    
  • Repeating Letters
    doubleChar = s => s.replace(/./g, x => x+x)