Skip to content

Instantly share code, notes, and snippets.

@yakovkhalinsky
Last active December 27, 2015 16:59
Show Gist options
  • Save yakovkhalinsky/7358693 to your computer and use it in GitHub Desktop.
Save yakovkhalinsky/7358693 to your computer and use it in GitHub Desktop.
Split string into an array by specified lengths of characters and pad each element with a specified character. Given a value ```str = 'abcdefg``` Running this function ```splitBy str, 2, '-'``` should produce an array ```['ab', 'cd', 'ef', 'g-']```
# str: The string we wish to split up
# length: how many characters of 'str' should each array element contain
# padWith: what to padd the last element with
splitBy = (str, length, padWith) ->
pad = (str) ->
str = "#{str}#{padWith}" for i in [str.length...length]
str
pad (str.slice i, i+length), length, padWith for i in [0...str.length] by length
str = 'abcdefgdlkhjatbhjsdfhjkadskjh'
console.log splitBy str, 4, '_'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment