User:Krankuba

===the simplest, library-free code for implementing array intersections: === ​var arr = [1, 2, 3, 4, 5, 6, 7, 9]; var arr2 = [0, 3, 6, 7, 8, 9, 10]; arr.filter(function(n) {    return arr2.indexOf(n) != -1; }); // returns [3, 6, 9]

reverse a string:
var str = "something"; var strReversed = str.split().reverse.join(); // returns strReversed  = gnihtemos

sum all array elements:
var arr = [1, 2, 3, 4]; var arrTotal = arr.reduce(function(previousNum, currentNum) {      return previousNum + currentNum;     }); // returns arrTotal = 10

check for palindromes: function palindrome(str) { var clearString = str.toLowerCase.replace(/[^0-9a-z]/gi, ).split(); for (var i = 0; i < clearString.length/2; i++) { if (clearString[i] !== clearString[clearString.length -1 -i]) { return false; }   }   return true; } function palindrome2(str) { str = str.replace(/\W/g, ).toLowerCase; return (str == str.split().reverse.join()); } palindrome("almostsomla"); // returns true

sort numbers: arrNumbers = arrNumbers.sort(function (a, b) { return b - a;  }); //1,2,3,11,20...

capitalize every first letter:
function titleCase(str) { var arr = str.toLowerCase.split(' '); for (var i in arr) { arr[i] = arr[i].charAt(0).toUpperCase + arr[i].substring(1); }  return arr.join(' '); } titleCase("I'm a little tea pot lot, but the cot"); // returns I'm A Little Tea Pot Lot...

truncate a string:
function truncateString(str, num) { if (num >= str.length) { return str; }  else if (num >3 && num < str.length) { str2 = str.slice(0, num-3); return str2 + "..."; }   else if (num <= 3) { str2 = str.slice(0, num); return str2 + "..."; } } truncateString("Absolutely Longer", 2); // returns Ab...

splits  an  array into groups with the size of the second argument: function chunkArrayInGroups(arr, size) { var arr2 = []; var arrLength = arr.length; for (var i = 0; i < arrLength; i += size) { arr2.push(arr.splice(0, size)); }  return arr2; } chunkArrayInGroups(["a", "b", "c", "d"], 2); // returns "a","b"],["c","d"

checks if the first argument contains all the letters of the second argument:
function mutation(arr) { var firstElement = arr[0].toLowerCase; var secondElement = arr[1].toLowerCase; var arr2 = secondElement.split(); for (var i = 0; i < secondElement.length; i++) { if (firstElement.indexOf(arr2[i]) === -1) { return false; }  }    return true; } mutation(["Mary", "Army"]); // returns true

   removes  all falty characters from a string: function bouncer(arr) { var arr2 = []; for (i = 0; i < arr.length; i++) { if (typeof arr[i] != 'undefined' && arr[i]) { arr2.push(arr[i]); }  }   return arr2; } bouncer([1, null, NaN, 2, undefined]); // returns [1, 2]

removes all elements from the initial array that are present as arguments: function destroyer(arr) { var argumentsArray = []; for (var i = 1; i < arguments.length; i++) { argumentsArray.push(arguments[i]); }  function seekAndDestroy(arr) { return argumentsArray.indexOf(arr) === -1; }   return arr.filter(seekAndDestroy); } destroyer([1, 2, 3, 1, 2, 3], 2, 3, "tree"); // returns [1, 1]

 the lowest index  at which the argument will be inserted into the array: function getIndexToIns(arr, num) { // Find my place in this sorted array. var iBelongHere = 0; //defining compare function, so 2, 5, go before 10 function compareNumbers(a, b) { return a - b;  } //checking if the num argument is already in the array and added if not if ($.inArray(num, arr) === -1) { arr.push(num); }  arr.sort(compareNumbers); for ( i = 0; i < arr.length; i++) { if ( arr[i] === num ) { iBelongHere = i;     } }  return iBelongHere; } getIndexToIns([10, 20, 40, 50], 30); // returns 2 decode a string using ROT13 cypher : function rot13(str) { var arr = []; var n = 0; for (i = 0; i < str.length; i++) { n = str.charCodeAt(i); // n becomes a number if (n >= 65 && n <= 77) { // ABCDEFGHIJKLM + 13 n = n + 13; }    else if (n >=78 && n <= 90) {  // NOPQRSTUVWXYZ - 13 n = n - 13; }    n = String.fromCharCode(n);  // n becomes a string again arr.push(n); //  n goes into a new decrypted string }  return arr.join(); } rot13("SERR PBQR PNZC");

returns the sum of the two arguments and all numbers between them: function sumAll(arr) { var min = Math.min(arr[0], arr[arr.length-1]); var max = Math.max(arr[0], arr[arr.length-1]); for (i = min + 1; i < max; i++) { arr.push(i); }  function getSum(total, num) { return total + num; }  return arr.reduce(getSum); } sumAll([5, 10]); // returns 45

returns the difference between two arrays: function diffArray(arr1, arr2) { var newArr = []; var idx; for (i = 0; i < arr1.length; i++) { idx = arr2.indexOf(arr1[i]); if (idx == -1) { // if 1st array item is not in 2nd array newArr.push(arr1[i]); //add it to the new array }      }         for (i = 0; i < arr2.length; i++) { idx = arr1.indexOf(arr2[i]); if (idx == -1) { // if 1st array item is not in 2nd array newArr.push(arr2[i]); //add it to the new array }      }     return newArr; } diffArray([1, "calf", 3, "piglet", 6, 234], [234, 7, "filly", 6]);

converts the given number into a roman numeral: function convertToRoman(num) { var roman = ""; var romanNumeral = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]; var numbers = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; for(var i = 0; i < numbers.length; i++) { while(num >= numbers[i]) { roman = roman + romanNumeral[i]; num = num - numbers[i]; }   }   return roman; } convertToRoman(36);

returns an array of all objects that have matching property and value pairs (second argument): function whatIsInAName(collection, source) { var arr = []; var sourceKeys = Object.keys(source); return collection.filter(function (obj) {      for(var i = 0; i < sourceKeys.length; i++) {         if(!obj.hasOwnProperty(sourceKeys[i]) || obj[sourceKeys[i]] !== source[sourceKeys[i]]) {           return false;         }       }       return true;     }); } whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

search and replace: function myReplace(str, before, after) { if (before.charAt(0) == before.charAt(0).toUpperCase) {    var arr = after.split(); arr[0] = arr[0].toUpperCase; after = arr.join(); }   return str.replace((before), after); } myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");

DNA pairing: function pairElement(str) { var arr = []; var convert = function(elem) { switch (elem) { case "G": arr.push(["G", "C"]); break; case "C": arr.push(["C", "G"]); break; case "A": arr.push(["A", "T"]); break; case "T": arr.push(["T", "A"]); break; }    };   for (var i = 0; i < str.length; i++) { convert(str[i]); }  return arr; } pairElement("ATCGA");

find the missing letter in the array and displays it:
function fearNotLetter(str) { var strSplit = str.split(''); var x = strSplit[0].charCodeAt(0); for (var i = 0; i < str.length; i++) { if (strSplit[i].charCodeAt(0) !== (x + i)) { return String.fromCharCode(x + i); }   }  } fearNotLetter("abcdefh"); // returns g  checks if the argument is a  boolean : function booWho(bool) { if(typeof(bool) !== "boolean") { return false; }  return true; } booWho(null); // returns false <h3 style="font-weight:normal;"> returns the unique numbers presented in all arrays: function uniteUnique(arr) { var arr2 = Array.from(arguments); var newArray = []; var shitArray = []; var arr3 = []; for (i = 0; i < arr2.length; i++) { for (j = 0; j < arr2[i].length; j++ ) { arr3.push(arr2[i].length); if (newArray.indexOf(arr2[i][j]) == -1) { newArray.push(arr2[i][j]); } else { shitArray.push(arr2[i][j]); }    }   }   return newArray; } uniteUnique([1, 3, 2], [1, [5]], [2, [4]]); // returns [1,3,2,[5],[4]]

flatten a nested array (with deep recursion):
function steamrollArray(arr) { var arr2 = []; function recursiveFlatten(arr) { for(var i = 0; i < arr.length; i++) { if(Array.isArray(arr[i])) { recursiveFlatten(arr[i]); } else { arr2.push(arr[i]); }    }   }   recursiveFlatten(arr); return arr2; } steamrollArray([1, [2], [3, 4, [5]]]); // returns [1,2,3,4,5] <h3 style="font-weight:normal;"> converts  HTML characters  to their corresponding entities: function convertHTML(str) { var arr = str.split(''); for (var i = 0; i < arr.length; i++) { switch (arr[i]) { case "&": arr[i] = "&amp;"; break; case "<": arr[i] = "&lt;"; break; case ">": arr[i] = "&gt;"; break; case "'": arr[i] = "&apos;"; break; case '"':           arr[i] = "&quot;";            break;        }    }      arr = arr.join('');    return arr;   } convertHTML("<><>"); <h3 style="font-weight:normal;"> converts a string into  a-spinal-case :  function spinalCase(str) {   str = str.replace(/([a-z])([A-Z])/g, '$1 $2');  // Insert write space between bond low-upper case   str = str.replace(/\s+|_+/g, '-');  // Replace white spaces and underscores by a dash   str = str.toLowerCase;  // Convert the string into lowercase   return str; } spinalCase('This_IsSpinalTap'); // returns this-is-spinal-tap

sum all odd fibonacci numbers:
function sumFibs(num) { var prev = 0, cur = 1, fib = 0, answer = 0; while (cur <= num) { if (cur % 2 !== 0) { answer += cur; }      fib = prev + cur; prev = cur; cur = fib; }  return answer; } sumFibs(4); // returns 5 sum all  prime numbers  up to and including the argument: function sumPrimes(num) { var arr = [2]; function isPrime(num) { if (num < 2) { return false; }    for (var i = 2; i <= num / 2; i++) { if ( num % i === 0) { return false; }     }     return true; }  for (var i = 3; i <= num; i += 2) { if (isPrime(i)) { arr.push(i); }  }   var result = arr.reduce(function(total, number) {      return total + number; }, 0); return result; } sumPrimes(10); // returns 45 <h3 style="font-weight:normal;"> finds the  smallest common multiple  of the provided numbers and all numbers between them: function smallestCommons(arr) { var x = 0; var y = 0; var array = []; var newArray = createArray(arr); return newArray.reduce(function(a, b) {        return lcm(a, b);     }); function lcm(a, b) { return (Math.abs(a * b) / gcd(a, b)); }    function gcd(a, b) { var temp; while (b !== 0) { temp = b;            b = a % b;             a = temp; }        return a;     } function createArray(arr) { if (arr[0] < arr[1]) { x = arr[0]; y = arr[1]; } else { x = arr[1]; y = arr[0]; }      for (var i = x ; i <= y; i++) { array.push(i); }    return array; } } smallestCommons([1,13]); // returns 360360

returns the first number that passes the truth check provided as argument function:
function findElement(arr, func) { var test = []; for (var i = 0; i < arr.length; i++) { if (func(arr[i])) { test.push(arr[i]); }  }   if (test.length > 0) { return test[0]; } } findElement([1, 3, 5, 8, 9, 10], function(num){ return num % 2 === 0; }); // 8 <h3 style="font-weight:normal;"> drops every element of the array  until the argument function returns true : function dropElements(arr, func) { var x = arr.length; for (var i = 0; i < x; i++) { if (!func(arr[0])) { arr.shift; }    }   return arr; } dropElements([1, 2, 3, 4], function(n) {return n > 7; }); // returns [] <h3 style="font-weight:normal;">converts binary code : function binaryAgent(str) { var num = 0; var arr = []; var str3 = []; var str2 = str.split(' '); for (j = 0; j < str2.length; j++) { str3 = str2[j].split(''); num = 0; for (i = 0; i < 8; i++) { if (str3[i] == 1 && i === 0) {num += 128;} if (str3[i] == 1 && i === 1) {num += 64;} if (str3[i] == 1 && i === 2) {num += 32;} if (str3[i] == 1 && i === 3) {num += 16;} if (str3[i] == 1 && i === 4) {num += 8;} if (str3[i] == 1 && i === 5) {num += 4;} if (str3[i] == 1 && i === 6) {num += 2;} if (str3[i] == 1 && i === 7) {num += 1;} }    arr.push(String.fromCharCode(num)); }  return arr.join(''); } binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000"); <h3 style="font-weight:normal;"> checks if the second argument is  truthy  for every first argument: function truthCheck(collection, pre) { for (var i = 0; i < collection.length; i++) { if (!collection[i].hasOwnProperty(pre) || !Boolean(collection[i][pre])) { return false; }   }   return true; } truthCheck([{"single": "double"}, {"single": NaN}], "single"); // returns false <h3 style="font-weight:normal;">sum two arguments together  if numbers. if only one argument is provided, return a function that expects one argument and returns the sum: function addTogether { var isNumber = function(num) { if (typeof num !== 'number') { return undefined; } else return num; };  if (arguments.length == 1) { var z = arguments[0]; if (isNumber(z)) { return function(arg2) { if (z === undefined || isNumber(arg2) === undefined) { return undefined; } else { return z + arg2; }    };   }   } else if (arguments.length > 1) { var x = isNumber(arguments[0]); var y = isNumber(arguments[1]); if (x === undefined || y === undefined) { return undefined; } else { return x + y;        } } } addTogether(2)(3);