Skip to content

Instantly share code, notes, and snippets.

@bu7ch
Created November 7, 2019 10:30
Show Gist options
  • Save bu7ch/8940afad91fbaafbca5b6fcfcfbafde3 to your computer and use it in GitHub Desktop.
Save bu7ch/8940afad91fbaafbca5b6fcfcfbafde3 to your computer and use it in GitHub Desktop.
CPro#6 Tests_week
// Le JS-recall
const selectElementsStartingWithVowel = function(array) {
const vowels = ['a', 'e', 'i', 'o', 'u'];
function startingWithVowel(word) {
const firstChar = word.charAt(0);
return vowels.indexOf(firstChar) !== -1;
}
return array.filter(startingWithVowel);
};
const removeNullElements = function(array) {
function notNull(word) {
return word !== null;
}
return array.filter(notNull);
};
const removeNullAndFalseElements = function(array) {
function notNullOrFalse(word) {
return word !== null && word !== false;
}
return array.filter(notNullOrFalse);
};
const reverseWordsInArray = function(array) {
function reverseChars(word) {
return word.split("").reverse().join("");
}
return array.map(reverseChars);
};
const everyPossiblePair = function(array) {
const everyPossiblePair = [];
const copyOfArray = array.slice().reverse();
for (const student1 of array) {
copyOfArray.pop();
for (let student2 of copyOfArray) {
everyPossiblePair.push([student1, student2].sort());
}
}
return everyPossiblePair.sort();
};
const allElementsExceptFirstThree = function(array) {
return array.slice(3);
};
const addElementToBeginning = function(array, element) {
array.unshift(element);
return array;
};
const sortByLastLetter = function(array) {
function compareLastLetter(word1, word2) {
return word1.slice(-1) > word2.slice(-1);
}
return array.sort(compareLastLetter);
};
const getFirstHalf = function(string) {
return string.slice(0, (string.length + 1) / 2);
};
const makeNegative = function(number) {
return -Math.abs(number);
};
const numberOfPalindromes = function(array) {
// recursive function to test if an array of letters is palindrome
function isPalindrome(wordArray) {
if (wordArray.length < 2) {
return true;
}
const first = wordArray.shift();
const last = wordArray.pop();
if (first !== last) {
return false;
} else {
return isPalindrome(wordArray);
}
}
function incrementIfPalindrome(count, word) {
const wordArray = word.split("");
return isPalindrome(wordArray) ? count + 1 : count;
}
return array.reduce(incrementIfPalindrome, 0);
};
const shortestWord = function(array) {
function returnMin(previousMin, word) {
return previousMin.length < word.length ? previousMin : word;
}
return array.reduce(returnMin);
};
const longestWord = function(array) {
function returnMax(previousMax, word) {
return previousMax.length > word.length ? previousMax : word;
}
return array.reduce(returnMax);
};
function sumNumbers(arrayOfNumbers) {
function sumNumber(prevSum, number) {
return prevSum + number;
}
return arrayOfNumbers.reduce(sumNumber, 0);
}
const repeatElements = function(array) {
// concat does not affect array, and creates whole new array
return array.concat(array);
};
const stringToNumber = function(string) {
return Number(string);
};
const calculateAverage = function(array) {
return sumNumbers(array) / array.length;
};
const getElementsUntilGreaterThanFive = function(array) {
// generator function. only in ES6 / js 1.7 or higher
function* getGenerator(array) {
for (let number of array) {
if (number > 5) break;
yield number;
}
}
return [number for (number of getGenerator(array))];
};
const convertArrayToObject = function(array) {
const newObject = {};
if (array.length % 2) throw "array has odd number of elements";
for (i = 0; i < array.length; i += 2) {
newObject[array[i]] = array[i + 1];
}
return newObject;
};
const getAllLetters = function(array) {
function addIfUnique(letters, newLetter) {
if (letters.indexOf(newLetter) === -1) letters.push(newLetter);
return letters;
}
return array.join("").split("").sort().reduce(addIfUnique, []);
};
const swapKeysAndValues = function(object) {
const newObject = {};
for (let key in object) {
newObject[object[key]] = key;
}
return newObject;
};
const sumKeysAndValues = function(object) {
return sumNumbers([Number(key) + Number(object[key]) for (key in object)]);
};
const removeCapitals = function(string) {
function isNotCapital(character) {
const charCode = character.charCodeAt(0);
return (charCode > 64 && charCode < 91) ? false : true;
}
return string.split("").filter(isNotCapital).join("");
};
const roundUp = function(number) {
return Math.ceil(number);
};
const formatDateNicely = function(date) {
function padZeros(number, width) {
const numberString = String(number);
const zeros = [];
for (let i = 0; i < width - numberString.length; i ++) {
zeros.push('0');
}
return zeros.join("") + numberString;
}
const day = padZeros(date.getDate(), 2);
const month = padZeros(date.getMonth() + 1, 2);
const year = date.getFullYear();
return day + '/' + month + '/' + year;
};
const getDomainName = function(string) {
const domainPattern = /^.+@(.+)\..+$/;
return string.match(domainPattern)[1];
};
const titleize = function(string) {
const insignificantWords = ["the", "and"];
function titleizeWord(word, insignificantWords) {
if (insignificantWords.indexOf(word) !== -1) return word;
return word[0].toUpperCase() + word.slice(1).toLowerCase();
}
const titleizedArray = [];
const firstWordOfSentence = true;
for (let word of string.split(" ")) {
if (firstWordOfSentence) {
titleizedArray.push(titleizeWord(word, []));
firstWordOfSentence = false;
} else {
titleizedArray.push(titleizeWord(word, insignificantWords));
}
if (word.slice(-1) === '.') firstWordOfSentence = true;
}
return titleizedArray.join(" ");
};
const checkForSpecialCharacters = function(string) {
function isNormal(currentCharacter) {
const charCode = currentCharacter.charCodeAt(0);
return (charCode < 48 || charCode > 122) ? false : true;
}
return !(string.split("").every(isNormal));
};
const squareRoot = function(number) {
return Math.sqrt(number);
};
const factorial = function(number) {
function factorial(number) {
if (number < 1 || number !== parseInt(number)) {
throw "wtf?";
} else if (number === 1) {
return 1;
} else {
return number * factorial(number - 1);
}
}
return factorial(number);
};
const findAnagrams = function(string) {
function permute(array) {
if (array.length === 1) return [array];
const fullPermutations = [];
for (let i in array) {
const subset = array.slice(0);
subset.splice(i, 1);
for (let permutation of permute(subset)) {
permutation.unshift(array[i]); // would be faster to push
fullPermutations.push(permutation);
}
}
return fullPermutations;
}
function joinLetters(array) {
return array.join("");
}
return permute(string.split("")).map(joinLetters);
};
const convertToCelsius = function(number) {
return Math.round((number - 32) / 1.8);
};
const letterPosition = function(array) {
function convertToPosition(character) {
return character.toLowerCase().charCodeAt(0) - 96;
}
return array.map(convertToPosition);
};
------------------------------------------------------------------------------------
// Airport challenge -JS
//Airport.js
'use strict';
class Airport {
constructor(weather) {
this._weather = typeof weather !== 'undefined' ? weather : new Weather();
this._hangar = []; }
planes() { return this._hangar; }
clearForLanding(plane) {
if (this._weather.isStormy()) {
throw new Error('cannot land during storm');
} this._hangar.push(plane);
}
clearForTakeOff() {
if (this._weather.isStormy()) {
throw new Error('cannot takeoff during storm');
} this._hangar = [];
}
isStormy() { return false; }
}
// Plane.js
'use strict';
class Plane {
constructor() { }
land(airport) {
airport.clearForLanding(this);
this._location = airport;
}
takeoff() {
this._location.clearForTakeOff();
}
}
//Weather.js
'use strict';
class Weather {
constructor() {
this._CHANCE_OF_STORMY = 0.5;
}
isStormy() {
return (Math.random() > this._CHANCE_OF_STORMY);
}
}
--------------------------------------------------------------------------------------
// gradeschool
function clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
export class GradeSchool {
constructor() {
this.db = {};
}
add(student, level) {
this.db[level] = this.grade(level).concat(student).sort();
}
grade(level) {
return this.db[level] ? clone(this.db[level]).sort() : [];
}
roster() {
return clone(this.db);
}
}
----------------------------------------------------
//robot simulator.js
export class InvalidInputError extends Error {
constructor(message) {
super();
this.message = message || 'Invalid Input';
}
}
export class Robot {
constructor() {
this.coordinates = [0, 0];
this.bearing = 'north';
}
at(xcoord, ycoord) {
this.coordinates = [xcoord, ycoord];
}
orient(direction) {
const validDirections = ['north', 'south', 'east', 'west'];
if (!validDirections.includes(direction)) {
throw new InvalidInputError('Invalid Robot Bearing');
}
this.bearing = direction;
return `The robot is pointed ${direction}`;
}
advance() {
if (this.bearing === 'north') {
this.coordinates[1] += 1;
} else if (this.bearing === 'south') {
this.coordinates[1] -= 1;
} else if (this.bearing === 'east') {
this.coordinates[0] += 1;
} else if (this.bearing === 'west') {
this.coordinates[0] -= 1;
}
}
turnLeft() {
if (this.bearing === 'north') {
this.orient('west');
} else if (this.bearing === 'south') {
this.orient('east');
} else if (this.bearing === 'east') {
this.orient('north');
} else if (this.bearing === 'west') {
this.orient('south');
}
}
turnRight() {
if (this.bearing === 'north') {
this.orient('east');
} else if (this.bearing === 'south') {
this.orient('west');
} else if (this.bearing === 'east') {
this.orient('south');
} else if (this.bearing === 'west') {
this.orient('north');
}
}
static instructions(s) {
return [...s].map((character) => {
switch (character) {
case 'L':
return 'turnLeft';
case 'R':
return 'turnRight';
case 'A':
return 'advance';
default:
throw new InvalidInputError(`${character} is not a valid instruction character.`);
}
});
}
place(args) {
this.coordinates = [args.x, args.y];
this.bearing = args.direction;
}
evaluate(s) {
Robot.instructions(s).forEach((instruction) => {
this[instruction]();
});
}
}
-----------------------------------------------------------
//word-count.js
export class Words {
count(input) {
this.counts = {};
this.words = input.match(/\S+/g);
this.words.forEach((word) => {
const lcWord = word.toLowerCase();
this.counts[lcWord] = Object.prototype.hasOwnProperty.call(this.counts, lcWord)
? this.counts[lcWord] + 1 : 1;
});
return this.counts;
}
}
--------------------------------------------------------------------
//difference-of-square
export class Squares {
constructor(max) {
this.max = max;
}
get squareOfSum() {
let sum = 0;
for (let x = 1; x <= this.max; x += 1) {
sum += x;
}
return sum * sum;
}
get sumOfSquares() {
let sum = 0;
for (let x = 1; x <= this.max; x += 1) {
sum += x * x;
}
return sum;
}
get difference() {
return this.squareOfSum - this.sumOfSquares;
}
}
------------------------------------------------------------
//minesweeper.js
const MINE = '*';
const DELTAS = [
[-1, -1],
[-1, 0],
[-1, 1],
[1, 1],
[1, 0],
[1, -1],
[0, 1],
[0, -1],
];
function adjacentSquareIsOnBoard(board, x, d) {
return board[x + d[0]];
}
function adjacentSquareHasMine(board, x, y, d) {
return board[x + d[0]][y + d[1]] === MINE;
}
function countAdjacentMines(board, x, y) {
return DELTAS
.filter(d => adjacentSquareIsOnBoard(board, x, d))
.filter(d => adjacentSquareHasMine(board, x, y, d))
.length;
}
function cellToMineOrCount(cell, inputBoard, x, y) {
if (cell === MINE) {
return MINE;
}
return countAdjacentMines(inputBoard, x, y) || ' ';
}
function stringify(board) {
return board.map(row => row.join(''));
}
function noDataPresent(rows) {
return rows.length === 0 || rows[0].length === 0;
}
export function annotate(rows) {
if (noDataPresent(rows)) {
return rows;
}
const inputBoard = rows.map(row => [...row]);
return stringify(
inputBoard.map(
(row, x) => [...row].map((cell, y) => cellToMineOrCount(cell, inputBoard, x, y)),
),
);
}
-------------------------------------------------------------------------
//scrabble-score.js
const letterScores = {
a: 1,
e: 1,
i: 1,
o: 1,
u: 1,
l: 1,
n: 1,
r: 1,
s: 1,
t: 1,
d: 2,
g: 2,
b: 3,
c: 3,
m: 3,
p: 3,
f: 4,
h: 4,
v: 4,
w: 4,
y: 4,
k: 5,
j: 8,
x: 8,
q: 10,
z: 10,
};
const letterScore = letter => letterScores[letter] || 0;
export const score = word => [...word.toLowerCase()]
.reduce((sum, currChar) => sum + letterScore(currChar), 0);
----------------------------------------------------------------------------
//queen-attack.js
const W = 8;
const H = 8;
const STARTING = { black: [7, 3], white: [0, 3] };
function samePosition({ white, black }) {
return white[0] === black[0] && white[1] === black[1];
}
function buildRow(cell, colCount) {
return Array(...Array(colCount)).map(() => cell);
}
function concatRows(row, rowCount) {
return [...Array.prototype.concat.apply(buildRow(row, rowCount)).join('')];
}
function constructBoard() {
let row = buildRow('_ ', W).join('');
row = `${row.substring(0, row.length - 1)}\n`;
return concatRows(row, H);
}
function placePieces(self) {
const board = self.board;
board[(self.black[0] * W * 2) + (self.black[1] * 2)] = 'B';
board[(self.white[0] * W * 2) + (self.white[1] * 2)] = 'W';
}
export class QueenAttack {
constructor(params = STARTING) {
if (samePosition(params)) {
throw new Error('Queens cannot share the same space');
}
this.black = params.black;
this.white = params.white;
this.board = constructBoard();
placePieces(this);
this.canAttack = () => {
if (this.black[0] === this.white[0] || this.black[1] === this.white[1]) {
return true;
}
return Math.abs(this.black[0] - this.white[0]) === Math.abs(this.black[1] - this.white[1]);
};
this.toString = () => this.board.join('');
return this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment