Tag Archives: Function

JavaScript Snippet – Recurse A Directory Synchronously

Recently I took a look at making HTML5 programs that will work on Mac, Linux and Windows via Electron and needed a way to recurse a directory synchronously in Node.js. I ended up with the following code:

The above function allows us to recursively get the contents of a directory. It also provides the ability to filter out files and sub-directories. The following is an example of using it to simply get all files and directories within a specified directory:

var dir = recurseDirSync('/Users/jsmith/Movies');

// Example directory structure:
  isFile: false,
  path: '/Users/jsmith/Movies/',
  stat: ,
  files: [
      isFile: true,
      path: '/Users/jsmith/Movies/Scrooge McDuck.mp4',
      stat: ,
      isFile: false,
      path: '/Users/jsmith/Movies/The Other Movies/',
      stat: ,
      files: [...]

As you can see, get the files and sub-directories of a directory is very easy. You can also easily filter with this function. Let’s say we want to only include directories and MP4s:

recurseDirSync('/Users/jsmith/Movies', function(path, isFile, stat) {
  return !isFile || /\.mp4$/i.test(path);

Once again, using this helper function makes something that could’ve been complex a lot easier. Feel free to use and even modify this function. :cool:

PHP Snippet – array_splice_assoc(…)

Recently I was working on something that required inserting key-value pairs into an array after a specific key in PHP. As I was looking through stackoverflow answers I realized that there was no awesome answer that really jumped out at me. Therefore I decided to take a few minutes to just write my own array_splice_assoc() function to get the job done:

As you can see this function takes the same parameters that array_splice() does but the difference is that the offset can be a string in this key which refers to the key after which the new array elements should be inserted.

One important thing to note is that if you try to insert a key-value pair in which the key exists before or at the offset, your key-value pair will not be inserted. On the other hand if you try to insert a key-value pair in which the key exists after offset, your value will replace the previous one.

Have fun! :cool:

PHP – Re-indexing 2D Array By A Specific Key

Today I was working on a personal project and wanted to be able to use a native PHP function to re-index a 2D array so that the key for each sub-array was pulled from a value in that sub-array. Unfortunately I wasn’t able to find a way to simply do it natively although it may exist. Therefore I wrote this array_by_column() function:

To use it you can simply supply the 2D array as the first argument and the key (or column name) as the second parameter.