Techumber
Home Blog Work

Javascript Simple Algorithms

Published on May 6, 2019

String spread split

const str = "Hellow World";
[...str];
// Output: ["H", "e", "l", "l", "o", "w", " ", "W", "o", "r", "l", "d"]
// is same as
str.split("");

Longest word in a string

const LongestWord = text => {
  return Math.max(...[...text].map(word => word.length));
};
// LongestWord('Hello World')
// Output: 5

Is Palindrome

const word = "mom";
[...word].every(
  (el, index, arr) =>
    el == arr.slice(arr.length - index - 1, arr.length - index)[0]
);

// Output: true

Substract two Arrays

const a1 = [1, 2, 3, 4, 5];
const a2 = [2, 3];

a1.filter(x => a2.indexOf(x) < 0);

Factorial tail call

const Factorial = (num, acc = 1) => {
  return num < 1 ? acc : Factorial(num - 1, num * acc);
};
// Factorial(4)
// Output: 24

Remove duplicate

const arr = [1,2,2,2,2,3,4,5,6];

// 1: Set

[..new Set(arr)]

// 2: Reduce && include

arr.reduce((acc, num) => acc.includes(num)?acc: [...acc, num]);

Title case a string

const toTitleCase = text => {
  return text.charAt(0).toUpperCase() + text.toLowerCase().slice(1);
};

Reverse a string

const revString = text => {
  return text.split("").reduce((acc, letter) => letter + acc);
};