Skip to content

Instantly share code, notes, and snippets.

@anatomic
Created June 12, 2018 22:21
Show Gist options
  • Save anatomic/b05d610d9522f96f82a55defc323a354 to your computer and use it in GitHub Desktop.
Save anatomic/b05d610d9522f96f82a55defc323a354 to your computer and use it in GitHub Desktop.
first-repeated-letter created by anatomic - https://repl.it/@anatomic/first-repeated-letter
// Needs to return the first repeated letter
// Points for reduced O complexity
// Challenge: Write a function that given a string, returns the first char that is repeated
// Example, the first letter to be repeated in this sentence is 't'
import {
safeLift,
isString,
head,
tail,
pipeK,
Maybe,
} from 'crocks';
const hasRepeat = 'foo bar baz';
const noRepeat = 'a b c d e f g';
const example = `The first letter to be repeated in this sentence is 't'`;
// split :: a -> Maybe (Array Char)
const split = safeLift(isString, s => [...s]);
// toLower :: a -> Maybe String
const toLower = safeLift(isString, s => s.toLowerCase()); // can remove this if case sensitive
// isRepeat :: Char -> Array Char -> Bool
const isRepeat = x => xs => xs.some(c => c === x && c !== " ");
// firstRepeatingChar :: Array Char -> Maybe Char
const getRepeat = l =>
Maybe.of(isRepeat).ap(head(l)).ap(tail(l)).option(false)
? head(l)
: tail(l).chain(getRepeat);
const firstRepeatingChar = pipeK(Maybe.of, toLower, split, getRepeat);
firstRepeatingChar(example);
// firstRepeatingChar(hasRepeat);
// firstRepeatingChar(noRepeat);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment