Embedding dynamicly named JavaScript in WordPress

tl;dr see code snippet for a simple way to enqueue multiple JavaScript files in a WordPress template.

I have recently been doing a lot of work writing small React applications to be embedded inside a WordPress website. Clients would like a rich, interactive set of pages without sacrificing their existing site.

A simple React app built using React Scripts should be minified into three separate ES5 JavaScript files. Each build will have its own unique hash in the file name.

In the past I would rename the files and hard code their names in a wp_enqueue_scripts action handler. This soon becomes tedious, so I wrote the following.

add_action( 'wp_enqueue_scripts', 'enqueue_react_script' );
function enqueue_react_script() {
    // tutorial is my CPT name
    if ( is_singular( 'tutorial' ) || is_post_type_archive( 'tutorial' ) ) {
        // register scripts
        $directory = plugin_dir_path( __FILE__ ) . 'script';
        $iterator = new DirectoryIterator( $directory );
        foreach ( $iterator as $file ) {
            if ( pathinfo( $file, PATHINFO_EXTENSION ) === 'js' ) {
                $fullName = basename( $file );
                $name = substr( basename( $fullName ), 0, strpos( basename( $fullName ), '.' ) );
                wp_enqueue_script( $name, plugin_dir_url( __FILE__ ) . 'script/' . $fullName, null, null, true );
            }
        }
    }
}