Skip to content

Instantly share code, notes, and snippets.

View AdrianSkar's full-sized avatar

Adrian Skar AdrianSkar

View GitHub Profile
// Falsy bouncer
function bouncer(arr) {
return arr.filter(function(val) {
return Boolean(val) !== false; // Same as: return (val);
});
}
bouncer([7, "ate", "", false, null, 9, NaN]);
// Mutations
function mutation(arr) {
var a = arr[0].toLowerCase();
var b = arr[1].toLowerCase();
for (i=0; i<b.length; i++){
if (a.indexOf(b[i]) < 0){
return false;
}
@AdrianSkar
AdrianSkar / slasher_flick.js
Last active May 13, 2018 18:21
[JS] fCC exercise: codepen.io/adrianskar/pen/yjEveL
function slasher(arr, howMany) {
return arr.slice(howMany);
/* With the splice() method:
arr.splice(0, howMany);
return arr;
*/
/* Using loops:
var newarr = [];
function chunkArrayInGroups(arr, size) {
var newarr=[];
for (i=arr.length, y=0; i>0; i-=size, y+=size){
newarr.push(arr.slice(y, size+y));
}
/* Simpler using just one var but calculates arr.length on each iteration
for (i=0; i<arr.length; i+=size){
newarr.push(arr.slice(i, i+size));
}*/
function truncateString(str, num) {
if (num <= 3) {
return str.substr(0, num) + '...';
}
if (num >= str.length) {
return str;
}
return str.substr(0, num - 3) + '...';
}
function repeatStringNumTimes(str, num) {
if (num < 0){return "";}
var res="";
for (i=num; i>0; i--){
res+=str;
}
return res;
//Using recursion: return str + repeatStringNumTimes(str, num-1);
}
@AdrianSkar
AdrianSkar / confirm_end.js
Last active May 10, 2018 16:35
fCC JS exercise: "Confirm the ending" https://codepen.io/adrianskar/pen/odEZVP
function confirmEnding(str, target) {
return str.substr(-target.length) === target;
// With the substring() method: return str.substring(str.length - target.length) === target;
// Using the endsWith() method: return str.endsWith(target);
}
function largestOfFour(arr) {
for (i=arr.length-1; i>=0; i--){
arr[i] = Math.max.apply(null, arr[i]); // I was thinking on doing it with max and reduce buy this looks cleaner
// Using ES6's spread operator: arr[i] = Math.max(...arr[i]);
}
return arr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
function titleCase(str) {
var a = str.split(' '), word=[]; //Split input and create new array var
for (i=a.length-1; i>=0; i--){
a[i] = a[i].toLowerCase(); //Lowercase everything
word[i] = a[i].charAt(0).toUpperCase() + a[i].substr(1,a[i].length-1); /*Uppercase just the first char on every word and put the rest of the word after it.
a[i].length-1 is optional according to MDN and will extract characters to the end of the string too*/
}
return word.join(" "); //Join and return new string
function findLongestWord(str) {
//Split input by spaces
var a = str.split(" "); // Use /\W|_/ instead to match non alphanumeric or underscore chars
//New array for lengths
var b = []; // c=""; for later returning which one (not needed for this exercise)
for (i=a.length-1; i>=0 ; i--){