import { StyleSheet } from 'react-native';
import { flatten } from 'lodash';

export const cachedStyles = {};
export const styleHasher = JSON.stringify; // todo: how bad is this?

// Uses cached or generates a new StyleSheet for a given style prop
const createStyleSheet = (stylesToGenerate) => {
  let styles = flatten([stylesToGenerate]); // Need to make sure we're working with a flat array
  const styleSheet = {}; // passed to StyleSheet.create later

  // Load style from cache or add style to stylesheet
  styles.forEach((style, index) => {
    if (typeof style !== 'object' || !style) return;
    const hash = styleHasher(style);
    if (cachedStyles[hash]) {
      styles[index] = cachedStyles[hash];
    } else {
      styleSheet[`${index}`] = style;
    }
  });

  // Generate the new stylesheet
  const generatedStyleSheet = StyleSheet.create(styleSheet);

  // Process the generated stylesheet
  Object.keys(generatedStyleSheet).forEach((key) => {
    const index = parseInt(key, 0);
    const generatedStyle = generatedStyleSheet[key];
    const hash = styleHasher(styles[index]);

    // add generated style to cache
    cachedStyles[hash] = generatedStyle;

    // swap generated style into result list
    styles[index] = generatedStyle;
  });

  if (styles.length === 1) styles = styles[0]; // eslint-disable-line
  return styles;
};

export default createStyleSheet;

@@ -763,24 +763,66 @@
    %7D%0A  %7D);%0A%0A
+  if (Object.keys(styleSheet).length) %7B%0A  
   // Generat
@@ -844,16 +844,18 @@
 sheet%0A  
+ 
+ 
 const ge
@@ -906,16 +906,18 @@
 heet);%0A%0A
+  
   // Pro
@@ -948,16 +948,18 @@
 sheet%0A  
+ 
+ 
 Object.k
@@ -1002,24 +1002,26 @@
 y) =%3E %7B%0A    
+  
 const index 
@@ -1040,24 +1040,26 @@
 ey, 0);%0A    
+ 
+ 
 const genera
@@ -1095,24 +1095,26 @@
 t%5Bkey%5D;%0A    
+  
 const hash =
@@ -1139,24 +1139,26 @@
 s%5Bindex%5D);%0A%0A
+  
     // add g
@@ -1185,16 +1185,18 @@
 che%0A    
+  
 cachedSt
@@ -1225,16 +1225,18 @@
 Style;%0A%0A
+  
     // s
@@ -1272,24 +1272,26 @@
 lt list%0A    
+  
 styles%5Bindex
@@ -1310,21 +1310,27 @@
 dStyle;%0A
+  
   %7D);
+%0A  %7D
 %0A%0A  if (

Fix issue where StyleSheet.create() is called when it doesn't have to be