Skip to content

Instantly share code, notes, and snippets.

@vincentwoo
Last active December 17, 2015 01:29
Show Gist options
  • Save vincentwoo/5528285 to your computer and use it in GitHub Desktop.
Save vincentwoo/5528285 to your computer and use it in GitHub Desktop.

JavaScript

Imagine you have the following function, which is a function that takes a really long time to square a number. It takes a number to square, and a callback that it will eventually call with the result of squaring that number.

function slowSquare(x, callback) {
  setTimeout(function() {
    callback(x * x);
  }, 500);
}

An example of calling slowSquare:

slowSquare(5, function(result) {
  console.log('The result is: ' + result);
});

/*
  yields the following:
  undefined
  > The result is: 25
*/

Write a function named squareTenTimes that takes a number and a callback, and eventually calls the callback with the result of using slowSquare to square the number 10 times.

squareTenTimes(2, function(result) {
  console.log('2^10 = ' + result);
});

//> 2^10 = 1024

// Bonus: write slowTenTimes(number, operation, callback), which
// calls the function "operation" on "number" ten times, feeding the
// result into the next operation each time, but only once every
// 500ms. Eventually calls "callback" with the final result.

Ruby

The ROT13 cipher is an ancient cipher that, given a message, returns a message where each letter has been replaced by the letter exactly 13 letters after it in the alphabet ordering. Letters near the end of the alphabet wrap around. The translation table looks like:

ABCDEFGHIJKLMNOPQRSTUVWXYZ
NOPQRSTUVWXYZABCDEFGHIJKLM

and therefore the message HELLO becomes URYYB and vice versa, because applying ROT13 twice is a no-op.

Please implement rotx in Ruby, which given a rotation number and a string outputs that string rotated by that many letters. It should preserve capitalization and ignore any non-alphabetic character. It should also take a parameter that decrypts the string instead of encrypting it. For example:

def rotx(x, string, decrypt = false)
  # Your implementation here...
end

rotx 10, 'Hello, World'
# => "Rovvy, Gybvn"
rotx 10, 'Rovvy, Gybvn', true
# => "Hello, World"

# Bonus: rotation numbers greater than 26 should work as well
rotx 36, 'Hello, World'
# => "Rovvy, Gybvn"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment