Skip to content

Instantly share code, notes, and snippets.

@ChrisDobby
ChrisDobby / colNamesToNumbers.ts
Created February 6, 2023 19:08
Spreadsheet programs often use the A1 Reference Style to refer to columns. Given a column name in this style, return its column number.
const colNamesToNumbers = (name: string) => name.split('').reduce((acc, ch) => acc * 26 + ch.charCodeAt(0) - 64, 0)
@ChrisDobby
ChrisDobby / numBalanced.ts
Created February 20, 2023 08:12
Given a string of parenthesis, return the number of parenthesis you need to add to the string in order for it to be balanced.
const numBalanced = (str: string) => {
const { open, closed } = str.split('').reduce(({ open, closed }, s) => ({ open: open + (s === '(' ? 1 : 0), closed: closed + (s === ')' ? 1 : 0) }), { open: 0, closed: 0 })
return Math.abs(open - closed)
}
@ChrisDobby
ChrisDobby / repeatedGroups.ts
Created February 28, 2023 14:13
Given a list of numbers, return all groups of repeating consecutive numbers
const repeatedGroups = (numbers: number[]) =>
numbers
.reduce<number[][]>(
(acc, num) => (acc.length === 0 || !acc[acc.length - 1].includes(num) ? [...acc, [num]] : [...acc.slice(0, acc.length - 1), [...acc[acc.length - 1], num]]),
[]
)
.filter(nums => nums.length > 1)
@ChrisDobby
ChrisDobby / scramble.ts
Created March 6, 2023 17:11
Write a function that takes an input sentence, and mixes up the insides of words (anything longer than 3 letters)
const scrambleLetters = (letters: string) =>
letters
.split('')
.sort(() => Math.random() - 0.5)
.join('')
const scramble = (str: string) =>
str
.split(' ')
.map(word => (word.length > 3 ? `${word[0]}${scrambleLetters(word.slice(1, word.length - 1))}${word[word.length - 1]}` : word))
@ChrisDobby
ChrisDobby / fractionMath.ts
Last active March 13, 2023 08:24
Write a function that can do the 4 basic operations (add, subtract, multiply and divide) on two fractions. Return the most simplified form of the result.
type FractionString = `${number}/${number}`
type Fraction = { numerator: number; denominator: number }
type Operation = 'add' | 'subtract' | 'multiply' | 'divide'
const simplify = ({ numerator, denominator }: Fraction) => {
const commonDivisor = (n: number, d: number) => (d === 0 ? n : commonDivisor(d, n % d))
const divisor = commonDivisor(numerator, denominator)
return { numerator: numerator / divisor, denominator: denominator / divisor }
}