Skip to content

Instantly share code, notes, and snippets.

@hongymagic
Last active December 14, 2015 22:19
Show Gist options
  • Select an option

  • Save hongymagic/5157873 to your computer and use it in GitHub Desktop.

Select an option

Save hongymagic/5157873 to your computer and use it in GitHub Desktop.
Increment all the strings!

Simple alphabet based sequencer. The first item is always 'a', then

increments by counting the alphabet.

Therefore in this system, we can treat 'a' as minimum and 'z' as the maximum.

BASE = 'a'.charCodeAt 0
MIN = 0
MAX = 25

For example, here's a consecutive sequence of alphabet literals:

a, b, c, ..., y, z, aa, ab, ca, ..., zy, zz, aaa, aab, ... zzz, aaaa, ...

next = (input) ->

Convert each character in the input to an integer re-based on the integer

value of 'a'

	input    = input.split ''
	integers = input.map    (x) -> (x.charCodeAt 0) - BASE
	result   = integers.map (x) -> x

Perform a simple add 1 arithmetic on the last token. If add 1 results in a

carry operation, they must cascade through until carry is set to false.

	size = integers.length - 1
	carry = integers[integers.length - 1] is MAX
	for integer, index in integers.reverse()
		if carry or index is 0
			integer = integer + 1
			carry = no

Wrap around addition: if a number exceeds the maximum value, it wraps around

and resets at the minimum value.

		if integer > MAX
			carry = yes
			integer = MIN

		result[size - index] = integer

If wrap around occurs at the first token, then length of the input must be

increased:

'bzz' -> 'caa' // no wrap around

'zzz' -> 'aaaa' // wrap around

	if carry is yes
		result.push MIN

	result = result.map (x) -> String.fromCharCode (x + BASE)
	result.join ''

module.exports = next
{
"name": "alpha-next",
"version": "0.0.0",
"description": "ERROR: No README.md file found!",
"main": "index.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": "",
"author": "",
"license": "BSD",
"dependencies": {
"chai": "~1.5.0",
"q-io": "~1.5.4"
}
}
next = require './next'
chai = require 'chai'
expect = chai.expect
describe 'alpha-next', ->
it 'should exist!', ->
expect(next).to.be.a 'function'
it 'should increment single char', ->
expect(next('a')).to.equal 'b'
it 'should increment multi-char', ->
expect(next('aa')).to.equal 'ab'
it 'should carry properly', ->
expect(next('abz')).to.equal 'aca'
it 'should increment last carry', ->
expect(next('zzz')).to.equal 'aaaa'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment