Skip to content

Instantly share code, notes, and snippets.

def next_palindrome(palindrome)
palindrome_string = palindrome.to_s
# change middle digit for palindromes with odd number of digits
if palindrome_string.length.odd?
middle = palindrome_string.length / 2
if palindrome_string[middle] == "9"
palindrome_string[middle] = "0"
middle_two = middle - 1, middle + 1
else
palindrome_string[middle] = palindrome_string[middle].to_i.next.to_s
@sranso
sranso / yield.rb
Last active August 29, 2015 13:57
def one_lap_around_the_track
puts 'starting to go around the quarter-mile track!'
yield if block_given?
puts 'continuing to go around the quarter-mile track!'
puts 'finished going around the quarter-mile track!'
end
one_lap_around_the_track { puts 'hurtles!!' }
one_lap_around_the_track { puts 'shot put!!' }
one_lap_around_the_track { puts 'long jump!!' }
class MyHash
attr_reader :buckets
def initialize
@buckets = []
end
def assign_or_find_index(k)
special_function(k) % 100
end
require './hash-table'
describe MyHash do
rspec_hash = MyHash.new
describe '#assign_or_find_index' do
it 'should return a number between 0 and 100' do
random_string = (0...8).map { (65 + rand(26)).chr }.join
expect(rspec_hash.assign_or_find_index(random_string)).to be_between(0, 100)
end
// MEMOIZE, caching something
var slowFunction = function(x, y) {
return x * y + 15;
};
var answers = {};
var memoize = function(fn) {
return function() {
var args = arguments;
// EXTEND, transfer functionality from one method / class to another
var Foo = function(name) {
this.name = name;
}
var Speakable = {
speak : function() { console.log("hi, i'm " + this.name) },
highfive : function() { console.log("up top!"); }
}
// MEMOIZE, caching something
var slowFunction = function(x, y) {
return x * y + 15;
};
var answers = {};
var memoize = function(fn) {
return function() {
var args = arguments;
// MEMOIZE, caching something
// generating ids for all the functions
// "crazy closures" allow for the vars / functions to live
// and behave the way we want them to.
(function() {
var id = 0;
function generateId() { return id++; };
Function.prototype.id = function() {
var newId = generateId();
this.id = function() { return newId; };
var memoizedSlowFunction = memoize(slowFunction);
// memoizedSlowFunction is now pointing the function below,
// where fn = slowFunction
// function() {
// var keys = Array.prototype.slice.call(arguments);
// var fnId = fn.id();
// if ( ! answers[fnId] ) {
// answers[fnId] = {};
// };