top | item 2771202

Ask HN: What's your most-used function that you wrote yourself?

58 points| jawns | 14 years ago | reply

Obviously, I'm looking for relatively short examples.

Interpret "function" broadly.

90 comments

order
[+] noblethrasher|14 years ago|reply
I wrote a C#/.NET function (extension method) called `Becomes` that I use as a replacement for the various `TryParse` methods.

Example:

    let n be an int
    n.Becomes("2") //returns 2
    n.Becomes("sdfsd") //returns n

    0.Becomes("12") returns 12
    0.Becomes("sdssdf") returns 0
Non-contrived example:

    var person = Person.Get(0.Becomes(Request.QueryString["id"]));
Basically, given the expression

    n.Becomes(SOME_STRING)
if `SOME_STRING` can be parsed as whatever the type of `n` is then it returns the the parsed result, else it returns (the value of) `n`.

More technically, `Becomes` returns a `ParseAttemptResult<T>` that is implicitly convertible to `T`. It also has `true` and `false` operators so that it can be used in an expression expecting a `Boolean` (e.g. `if` and the ternary operator`?:`).

Github Repo: https://github.com/noblethrasher/Parser-Helpers/blob/master/...

[+] 51Cards|14 years ago|reply
I offer up this little item since I'm a bit of a stickler for applications using proper grammar. This is nothing complex but I use it all the time. I have versions of the same routine in every language I work in.

   function plural(count, itemName, pluralWord, singLead, plurLead, singFollow, plurFollow) {
      if (((typeof pluralWord != 'undefined') && (typeof pluralWord.valueOf() == 'string')) && (pluralWord.length > 0))
         var outP = count + ' ' + ((count == 1) ? itemName : pluralWord);
      else
         var outP = count + ' ' + itemName + ((count == 1) ? '' : 's');
      
      var follow = (count == 1) ? singFollow : plurFollow;
      outP += (((typeof follow != 'undefined') && (typeof follow.valueOf() == 'string')) && (follow.length > 0) ? ' ' + follow : '');

      var lead = (count == 1) ? singLead : plurLead;
      return (((typeof lead != 'undefined') && (typeof lead.valueOf() == 'string')) && (lead.length > 0) ? lead + ' ' : '') + outP;
   }
Usage - first simple pluralization:

  alert('There ' + plural(c,'dog','','is','are') + ' in my house');
  c = 1 --> There is 1 dog in my house.
  c <> 1 --> There are 2 dogs in my house.

  alert(plural(c,'dog','','','','is','are') + ' in my house');
  c = 1 --> 1 dog is in my house.
  c <> 1 --> 2 dogs are in my house.
And for non-simple pluralization:

  alert('There ' + plural(c,'company','companies','is','are') + ' on the list');
  c = 1 --> There is 1 company on the list.
  c <> 1 --> There are 2 companies on the list.

  alert(plural(c,'company','companies','','','is','are') + ' on the list');
  c = 1 --> 1 company is on the list.
  c <> 1 --> 2 companies are on the list.
[+] alexgartrell|14 years ago|reply
I stole this from mongrel2, but the check macro is pretty good for error handling in C

  #define check(A, M, ...)                       \
      if(!(A)) {                                 \
        fprintf(stderr, M "\n", ##__VA_ARGS__);  \
        goto error;                              \
      }                                          \
    }
And you use it like this

  FooClass *create_foo_class()
  {
    FooClass *fc = NULL;
    int rc;
    fc = malloc(sizeof(*fc));
    check(fc != NULL, "allocation failed");

    rc = do_something_to_foo_class(fc);
    check(rc == 0, "do_something_to_foo_class(...) failed");
    
    return fc;
  error:
    if(fc != NULL) free(fc);
    /* Other cleanup */
    return NULL;
  }
[+] patio11|14 years ago|reply
Possibly the most critical code in my application:

  #Non-destructive.  Returns the input array/list in randomized order.  Uses approximately O(n) time and O(n) space.
  def self.shuffle_array(array)
    shallow_copy = array.map {|a| a}
    shallow_copy.size.downto(1) {|n| shallow_copy.push(shallow_copy.delete_at(rand(n)))
    shallow_copy
  end
[+] klochner|14 years ago|reply
Your function isn't close to linear. Here are my benchmarks for 10 iterations of sorting:

   patio11:
     100000 -- 120.469834
      10000 -- 1.218803
       1000 -- 0.019961
        100 -- 0.000958

   Array.shuffle:
      100000 -- 0.054125
       10000 -- 0.002993
        1000 -- 0.000302
         100 -- 4.1e-05
[+] rue|14 years ago|reply
Hopefully you've since migrated to Array#shuffle.
[+] ssp|14 years ago|reply
Doesn't that run in quadratic time - or can delete_at() somehow avoid copying all the tail elements in the array?
[+] klochner|14 years ago|reply
history function for ruby console (irb) sessions:

   def history(num=100)
     h = Readline::HISTORY.to_a
     start = [0,h.size-num-1].max
     h.zip((0..h.size).to_a)[start...h.size].each do |cmd,i|         
       puts " #{(i).to_s.rjust(4)}  #{cmd}"
     end
   end
I keep it in my .irbrc file, really useful to avoid stepping through command history to find previous commands.
[+] dholowiski|14 years ago|reply
connect_to_db(); in PHP. it knows if im in a development or production environment, knows the proper username and password, and connects. Very basic i know, and im sure everyone has written a similar function, but super useful.
[+] Vindexus|14 years ago|reply
Probably this one, which I use for testing

    function becho($value, $key = NULL)
    {
        echo '<br /><span style="background: #FFFFFF; color: #000000;">' . (NULL != $key ? $key . ' = ' : '') . $value . '</span>';
    }
I also like this one

    function s($num)
    {
         return $num == 1 ? '' : 's';
    }
Which I use like

    echo 'Showing ' . $results . ' result' . s($results) . '.';
[+] clyfe|14 years ago|reply

    function echo_r($x){
        echo '<pre>';
        print_r($x);
        echo '</pre>';
    }
[+] swah|14 years ago|reply
Kinda ugly, but:

    (defun my-rename-symbol-at-point ()
      (interactive)
      (let* ((curword (thing-at-point 'symbol))
        (to-word nil))
      (if (null curword)
        (message "No symbol at point!")
        (progn
          (setq to-word (read-string (concat "Replace " curword " with: ")))
          (save-excursion
            (goto-char (point-min))
            (replace-regexp re-curword to-word))))))
[+] alts|14 years ago|reply
Haskell:

    (\>) x f = f x
Allows me to write in a more readable manner

    [1..10]
        \> map (*2)
        \> filter (<5)
[+] nxn|14 years ago|reply
Heh, wrote the same function, except called mine $> because it's really just a flipped $.
[+] contextfree|14 years ago|reply
Inspired by F#'s |> (which was of course inspired by Unix pipes) ?
[+] code_duck|14 years ago|reply
A PHP 'get or else' which replaces

   $some_var = isset($array[$key]) ? $array[$key] : $default;
[+] nxn|14 years ago|reply
A few months ago I was writing a little application where I was doing a lot of asynchronous calls in javascript and having to track their completion to do some other stuff, it resulted in this:

  // Synchronizes asynchronous calls: sync(functions..., completionHandler)
  var sync = function() {
    var argLength = arguments.length - 1
      , completed = 0
      , callback  = arguments[argLength]
    
    for (var i = 0; i < argLength; i++) {
      arguments[i](function() {
        completed++;
        (completed == argLength) && callback && callback();
      });
    }
  };
It pretty much takes a number of functions that perform asynchronous operations and execute a callback function upon completion of whatever the async operation is. Once they're all complete it calls the last function it received as a 'completion handler'. Example that I wrote out without bothering to test at all (treat it as pseudo-code):

  var pageData = null;
  sync
    ( function(cb) { $('#pageContainer').fadeOut('slow', cb); }
    , function(cb) {
        $.ajax(
          { url: 'page.html'
          , success: function(msg) {
              pageData = msg;
              cb();
            }
          }
        );
      }
    , function() {
        $('#pageContainer').html(pageData).fadeIn('slow');
      }
    );
So that will start by beginning the jQuery fadeOut animation on the pageContainer html element, while immediately doing an ajax call to get another page's data. Once both operations are complete, it will take the new page data, put it into the pageContainer element, and fade it back in.
[+] dmix|14 years ago|reply
A designers most used function:

In SCSS I use a very simple mixin for rounded corners, something I use frequently when designing sites.

  @mixin radius($dist) {
    border-radius:$dist;
    -moz-border-radius:$dist;
    -webkit-border-radius:$dist;
    -khtml-border-radius:$dist;
    -webkit-background-clip:padding-box;
  }
Then in the class just add:

  @include radius(5px);
[+] georgefox|14 years ago|reply
Shouldn't border-radius (i.e., no vendor prefix) be last?
[+] abalashov|14 years ago|reply
We have a SIP call accounting, rating and routing product that is driven by a SIP proxy that calls a lot of Postgres stored procedures on the backend. (The SIP proxy's configuration is written in a pseudo-programmatic, interpreted scripting language, but one lacking in many basic features and data structure primitives that can be taken for granted in the runtime of a general-purpose programming language, so most of the business layer is in the database of necessity, in addition to all the other reasons for doing it that way.)

All throughout the platform, there are many points at which the ANI/caller ID and the dialed digits (the user part of the request URI) must be "translated", which is a fancy phone switch term for stripping one or more digits and then prepending one or more digits. It was such a common operation that it was genericised into our most oft-used PL/PgSQL utility function:

  -- Character stripping and prefix prepending transformation, which is applied
  -- to the ANI and DNIS at virtually all entry and exit points in the call
  -- processing machine.
  
  CREATE OR REPLACE FUNCTION strip_prepend_transform(_token varchar,
  						   _strip_digits integer,
  						   _prepend_prefix varchar)
  RETURNS varchar
  AS $$
    DECLARE 
      _strip_len		smallint := 0; 
    BEGIN
      IF _strip_digits > 0 THEN
  	-- If the strip length given for some reason exceeds the 
  	-- actual string length, trim it down so that those digits
  	-- that do exist are still trimmed.
  
        IF _strip_digits > LENGTH(_token) THEN
          _strip_len = LENGTH(_token);
        ELSE
  	  _strip_len = LENGTH(_token) - _strip_digits;
        END IF;
  
        _token := SUBSTRING(_token FROM (_strip_digits + 1) FOR _strip_len);
      END IF;
  
      IF LENGTH(_prepend_prefix) > 0 AND _prepend_prefix <> '' THEN
        _token := (_prepend_prefix || _token);
      END IF;
  
      RETURN _token;
    END
  $$ LANGUAGE 'plpgsql';
[+] JesseAldridge|14 years ago|reply
I use the following like so: from($('.foo_element'), 'text')

That way if I change the html structure I don't have to to change a million jquery selectors, I can just change the from function in one place.

    // Access one particular element from another.
    function from(start, end) {
      start = $(start)
      if(start.parent().hasClass('headline') && end == 'node')
        return start.parent().parent()
      if(end == 'nodes')  return start.children('.node')
      if(end == 'headline')  return start.children('.headline')
      if(end.indexOf('.') != 0)  end = '.' + end
      if(start.hasClass('headline'))  return $(start.children(end))
      return start.find('> .headline > ' + end)
    }
(I'm still somewhat new to Javascript, so this may be a well-known pattern.)
[+] neilk|14 years ago|reply
Maybe I don't understand your use case, but it seems to me your function is masking some other problems. You say you're new to JS, so here's a little unsolicited advice...

If you find yourself retyping the same jQuery selectors over and over, or that the structure changes a lot, then you should be encapsulating that somehow into some other function or object. Instead you're writing a do-it-all function that takes more strokes to type than the original jQuery selectors!

I haven't seen the structure in question, but when I see a class called something very generic like "node", I suspect something else is wrong. If the class isn't specific and at least somewhat meaningful to a person, then you might be solving the problem at the wrong level, using classes when a rethink of the structure might be better.

Also... lack of semicolons is bad style. Lack of braces for if clauses is bad style. Fix it, you'll thank me later. :)

[+] waterhouse|14 years ago|reply
"src". Takes the name of a variable (usually a function) and searches my source directory for definitions of that variable. The way it recognizes definitions is fairly ad-hoc (it recognizes "def", "mac", "defmemo", and a few others; it doesn't attempt to recognize forms like "(let x 2 (def ...))").

  arc> src.src
  From: /Users/waterhouse/Dropbox/arc3.1/a
  (mac src (name (o strict t))
    `(src-fn ',name
             ',strict))
  Found 1 results in 1 different files.
"aps". Apropos; derived from the Common Lisp function. Returns all bound variable names of which the supplied argument is a substring.

  arc> aps.mat-
  (fermat-prime mat-add mat-add-mod mat-det mat-det2 mat-expt mat-id
  mat-mod-expt mat-mul mat-mul-mod mat-order mat-trans)
[+] ramidarigaz|14 years ago|reply
A little bit of python that makes it easier to do shell-style scripting.

    def call(cmd):
	args = shlex.split(str(cmd))
	p = Popen(args, stdout=PIPE, stderr=PIPE)
	text = p.stdout.read()
	if not text:
		text = p.stderr.read()
	return text
[+] btraut|14 years ago|reply
The other <pre> and print_r()-based solutions don't work quite as well when you're writing an AJAX-based app. I use error_log for everything:

  // PHP error_log() wrapper
  function el($var, $die = true) {
     error_log(var_export($var, true));
  
     if ($die) {
        die();
     }
  }
Also, Paul Irish's Javascript log() function is amazing. It can be found in boiler plate, but here's the gist:

  // Javascript console.log() wrapper
  window.log = function() {
     log.history = log.history || [];
     log.history.push(arguments);
  
     if (this.console) {
        console.log(Array.prototype.slice.call(arguments));
     }
  };
[+] joeyh|14 years ago|reply
In multiple languages (perl, haskell), I find myself writing a function that runs a system command and returns False (or sometimes, throws an exception) if it failed nonzero.

Also, in haskell I use these frequently to have monadic versions of some common flow control functions (some nonstandard libraries have similar functions to these but it's easier to write my own):

  whenM c a = c >>= flip when a
  unlessM c a = c >>= flip unless a
  (>>?) = whenM
  (>>!) = unlessM
  -- low fixity allows eg, foo bar >>! error $ "failed " ++ meep
  infixr 0 >>?
  infixr 0 >>!
[+] jrockway|14 years ago|reply
The perl core has a way of detecting non-zero exit statuses:

    $ perl -Mautodie=system -e 'system("/bin/false")'
    "/bin/false" unexpectedly returned exit value 1 at (eval 5) line 13
     at -e line 1
Pretty nice.