Skip to content

Instantly share code, notes, and snippets.

@cecyc
Last active April 23, 2021 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cecyc/fcd0c856d7fd4e016a4b72b2fe7be002 to your computer and use it in GitHub Desktop.
Save cecyc/fcd0c856d7fd4e016a4b72b2fe7be002 to your computer and use it in GitHub Desktop.
const axios = require('axios');
// JS STUDY NOTES
const removeFirstTwoChars = (list) => {
const [, , ...arr] = list;
return arr;
}
console.log(removeFirstTwoChars([1,2,3,4,5,6,7]));
// Basic string manipulation
const createPhoneNumber = (str) => {
if (str.length !== 10) {
throw new Error('Length must be 10');
}
const specialChars = /[^\w\s]/
if (specialChars.test(str)) {
throw new Error('Number must not include special characters');
}
const phoneParts = [];
// phoneParts.push(str.slice(0,3));
// phoneParts.push(str.slice(3,6));
// phoneParts.push(str.slice(6,10));
for (let i = 0; i < str.length; i++) {
if (i === 2 || i === 5) {
phoneParts.push(str[i] + '-');
} else {
phoneParts.push(str[i]);
}
}
return phoneParts.join('');
}
console.log(createPhoneNumber('7138858290'));
// filter dupe strings
const arr = ['blue', 'green', 'blue', 'red'];
const filteredColors = arr.filter((element, index, array) => {
return array.indexOf(element) === index
});
console.log(filteredColors);
// sort an array of strings
console.log(arr.sort());
// sort a string by splitting into array, sorting array, joining array
const str = 'foobar';
const strParts = str.split('');
console.log(strParts.sort().join(''));
// call and apply provide their own context
// call passes in a new context and arguments,
// apply passes in a new context and arguments as a list
// bind provides its own context, but it applies when the function is used, not immediately
// classes
class Cat {
constructor(name) {
this.name = name;
}
meow () {
return `meow ${this.name}`;
}
}
const catlyn = new Cat('Catlyn');
console.log(catlyn.meow());
class Kitty extends Cat {
constructor(name) {
super(name);
}
purr () {
return 'Purrrrrrr';
}
}
const kitteh = new Kitty('Kit Kat');
console.log(kitteh.purr());
console.log(kitteh.meow());
// filter
const arr = [1,2,4,5,10,6,3];
const odd = arr.filter((num) => { return num % 2 !== 0 } );
console.log(odd);
// find if string is balanced (has the same number of parens on each side)
const isBalanced = (str) => {
const openParens = ['(', '{', '['];
const parenMap = {
'(': ')',
'{': '}',
'[': ']',
}
const chars = [];
for (let char of str) {
if (openParens.includes(char)) {
chars.push(char);
} else {
const lastChar = chars.pop();
if (char !== parenMap[lastChar]) {
return false;
}
}
}
return chars.length === 0;
}
console.log(isBalanced('{}'));
// reduce, flatten, filter
const nums = [2,2,2];
const sumOfNums = nums.reduce((sum, n) => {
return sum + n;
}, 0);
console.log(sumOfNums);
const arr = [1, 2, [3, 10, [11, 12]], [1, 2, [3, 4]], 5, 6];
const flatten = arr.flat(2);
const deduped = flatten.filter((element, index, array) => {
return array.indexOf(element) === index;
})
const flatSorted = arr.flat(2).filter((element, index, array) => {
return array.indexOf(element) === index;
}).sort((a, b) => a - b);
console.log(flatSorted);
function flattenArray(data) {
// our initial value this time is a blank array
const initialValue = [];
// call reduce on our data
return data.reduce((total, value) => {
// if the value is an array then recursively call reduce
// if the value is not an array then just concat our value
return total.concat(Array.isArray(value) ? flattenArray(value) : value);
}, initialValue);
}
console.log(flattenArray(arr));
// use reduce to sort data by type
const pokemon = [
{ name: "charmander", type: "fire" },
{ name: "squirtle", type: "water" },
{ name: "bulbasaur", type: "grass" }
]
const pokeMap = pokemon.reduce((acc, item) => {
acc[item.name] = { 'type': item['type'] };
return acc;
}, {});
console.log(pokeMap);
// reduce to map data by classroom, sum weights
const getMapFromArray = data =>
data.reduce((acc, item) => {
acc[item.name] = { type: item.type };
return acc;
}, {});
const data = {
'awards': [
{
classroom: 'Chemistry',
student: 'Johnny',
weight: 2
},
{
classroom: 'Chemistry',
student: 'Johnny',
weight: 2
},
{
classroom: 'Chemistry',
student: 'Tom',
weight: 1
},
{
classroom: 'Chemistry',
student: 'Tom',
weight: 2
},
{
classroom: 'Physics',
student: 'Johnny',
weight: 2
},
{
classroom: 'Physics',
student: 'Johnny',
weight: 2
},
{
classroom: 'Physics',
student: 'Tom',
weight: 1
},
{
classroom: 'Physics',
student: 'Tom',
weight: 2
},
]
}
const byClassroom = data['awards'].reduce((acc, item) => {
function setWeight () {
if (acc[item.classroom][item.student]) {
acc[item.classroom][item.student] += item.weight;
} else {
acc[item.classroom][item.student] = item.weight;
}
}
if (acc[item.classroom]) {
setWeight();
} else {
acc[item.classroom] = {};
setWeight();
}
return acc;
}, []);
console.log(byClassroom);
// reduce array of arrays into hash with fruit, quantity as key, value
const fruit = [['banana', 31], ['apples', 8], ['grapes', 5]];
const fruitMap = fruit.reduce((acc, fruit) => {
acc[fruit[0]] = fruit[1]
return acc;
}, {});
console.log(fruitMap);
// sample set timeout
set timeout
console.log('Start');
setTimeout(() => {
console.log('Please hold...')
}, 3000);
console.log('End');
// sample URL get with promises
const getPokemon = (name) => {
const BASE_URL = 'https://pokeapi.co/api/v2/pokemon';
axios.get(`${BASE_URL}/${name}`).then((res) => {
console.log(res.data.species);
}).catch((err) => console.log(err));
}
getPokemon('ditto');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment