<commit_before>(function() {
  var app = angular.module('tinatasks', ["components", "firebase"]);
  var ref = new Firebase("https://tinacg.firebaseio.com/tinatasks");

  app.controller('TaskController', ['$rootScope', '$scope', '$firebase', function($rootScope, $scope, $firebase) {
    function init(authData) {
      // $scope.loginStatus = "Welcome back " + authData.password.email + "! Your token expires " + (new Date(authData.expires * 1000));
      $scope.loggedIn = true;

      $scope.notification = authData.password.email + " token expires " + (new Date(authData.expires * 1000));

      var tabsRef = ref.child(authData.uid).child("tabs");
      var sync = $firebase(tabsRef);
      $scope.tabs = sync.$asArray();

      $scope.addTab = function(tabName) {
        $scope.tabs.$add({ name: tabName })
          .then(function() { $scope.refreshTaskRefs(); })
          .then(function() { $scope.notification = "Added tab " + tabName; });
      };

      var tasksRef = [];
      var tasksSync = [];
      $scope.tasks = [];

      var tasksRootRef = ref.child(authData.uid).child("tasks");
      var tasksRootSync = $firebase(tasksRootRef);
      $scope.tasksRoot = tasksRootSync.$asObject();

      $scope.refreshTaskRefs = function() {
        angular.forEach($scope.tabs, function(tab, tabId) {
          tasksRef[tab.name] = ref.child(authData.uid).child("tasks").child(tab.name);
          tasksSync[tab.name] = $firebase(tasksRef[tab.name]);
          $scope.tasks[tab.name] = tasksSync[tab.name].$asArray();

          $scope.tasks[tab.name].$loaded().then(function() {
            $scope.refreshAllTasks();
          });

        });
      };

      $scope.tabs.$loaded().then(function () {
        $scope.refreshTaskRefs();
        //$rootScope.panes[1].select();
        angular.forEach($scope.tabs, function(tab, tabId) {
          // console.log("populate " + tab.name);
          $scope.populateAllTasks(tab.name);
        });
      });

      $scope.updateTask = function(tasks, task) {
        tasks.$save(task)
          .then(function() { $scope.notification = "Changed task " + task.description; });
      }

      $scope.addTask = function(tabName, taskDone, taskDescription, taskCategory, taskDueDate) {
        taskDescription = taskDescription || "My Task";
        taskCategory = taskCategory || "~uncategorized";
        taskDueDate = taskDueDate || "soon";

        $scope.tasks[tabName].$add({ done: taskDone,
                                     description: taskDescription,
                                     category: taskCategory,
                                     createDate: (new Date()).getTime(),
                                     dueDate: taskDueDate,
                                   })
          .then(function() { $scope.notification = "Added " + tabName + "/" + taskDescription; })
          .then(function() { $scope.refreshAllTasks(); });

        $scope.taskDone = false;
        $scope.taskDescription = "";
        $scope.taskCategory = "";
        $scope.taskDueDate = "";

        $scope.$broadcast("newTaskAdded");
      };

      // tasks[tab.name].$remove(task)
      $scope.removeTask = function(tasks, task) {
        tasks.$remove(task)
          .then(function() { $scope.notification = "Removed task " + task.description; })
          .then(function() { $scope.refreshAllTasks(); });
      };

      $scope.deleteTabTasks = function(tabName) {
        tasksRootSync.$remove(tabName)
          .then(function() { $scope.notification = "Deleted tab tasks for " + tabName; })
          .then(function() { $scope.refreshAllTasks(); });
      };

      $scope.removeTab = function(tab) {
        tasksRootSync.$remove(tab.name)
          .then(function() { $scope.tabs.$remove(tab)
                             .then(function() { $scope.notification = "Removed tab " + tab.name; }); })
          .then(function() { $scope.refreshAllTasks(); });
      };

      // ARRAY FOR ALL TASKS

      $scope.allTasks = [];

      $scope.cleanAllTasks = function() {
        $scope.allTasks = [];
      }

      $scope.populateAllTasks = function(tabName) {
        angular.forEach($scope.tasks[tabName], function(task) {
          $scope.allTasks.push(task);
        });
      };

      $scope.refreshAllTasks = function() {
        $scope.cleanAllTasks();
        angular.forEach($scope.tabs, function(tab, tabId) {
          $scope.populateAllTasks(tab.name);
        });
      };

      // TIME AND MOMENT.JS

      $scope.getms = function(s) {
        var m = moment(s, "D/M/YY H:mm:ss");
        var result = m.valueOf();
        if (isNaN(result)) {
          result = 0;
        }
        return result;
      };

      $scope.getFormattedDate = function(ms) {
        var result = moment(ms).locale('pt-BR').format('ddd D-MMM-YY H:mm:ss');
        if (result === 'Invalid date') {
          result = 'data invalida';
        }
        if (ms === undefined) {
          result = "";
        }
        return result;
      };

      $scope.getShortDate = function(ms) {
        // var result = moment(ms).locale('pt-BR').format('D-MMM H:mm:ss');
        var result = moment(ms).locale('pt-BR').format('D-MMM');
        return result;
      };

      $scope.parseDate = function(s) {
        if (s === 'soon') {
          return 9999999999000;
        } else if (s === 'now') {
          return moment().valueOf();
        } else {
          return moment(s, "D/M/YY H:mm:ss").valueOf();
        }
      };

      $scope.millisToString = function(ms)
      {
        if (ms < 0 || ms > 3159999999000) {
          return "∞";
        }
        var seconds = Math.floor(ms / 1000);
        var numyears = Math.floor(seconds / 31536000);
        var numdays = Math.floor((seconds % 31536000) / 86400);
        var numhours = Math.floor(((seconds % 31536000) % 86400) / 3600);
        var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
        var numseconds = (((seconds % 31536000) % 86400) % 3600) % 60;

        var result = "";

        if (numyears > 0) {
          result += numyears + "y ";
        }
        if (numdays > 0) {
          result += numdays + "d ";
        }
        if (numhours > 0) {
          result += numhours + "h ";
        }
        if (numminutes > 0) {
          result += numminutes + "m ";
        }
        // if (numseconds > 0) {
        //  result += numseconds + "s";
        // }
        return result;
      }

      $scope.momentNow = function() {
        return moment().valueOf();
      };

      $scope.now = $scope.momentNow();
      $scope.nowFull = moment().locale('pt-BR').format();

      $scope.dueDateOrder = function(task) {
        return $scope.parseDate(task.dueDate);
      }

      function numdays(ms) {
        var seconds = Math.floor(ms / 1000);
        var days = Math.floor(seconds / 86400);

        return days;
      }

      function daysSince01(dmyStr) {
        var dmyParts = dmyStr.split("/");
        var day = Number(dmyParts[0]);
        var month = Number(dmyParts[1]);
        var year = Number(dmyParts[2]);

        var leapYearsPassed = Math.floor(year / 4);

        if (year % 4 === 0 && month > 2) {
          leapYearsPassed -= 1;
        }

        return leapYearsPassed + (year * 365) + moment(dmyStr, "D/M/YY").dayOfYear();
      }

      // pass moment() now to a function that returns D/M/Y

      $scope.daysDiff = function(then, now) {
        // var nineteenseventy = moment("1/1/1970 0:00:00", "D/M/YYYY H:mm:ss");
        // var then_since1970 = numdays(moment(then, "D/M/YY H:mm:ss").valueOf());
        // var now_since1970 = numdays(moment().valueOf());
        // return Math.max(0, then_since1970 - now_since1970);
        // var result = daysSince01(then.split(" ")[0]) - daysSince01(moment().locale('pt-BR').format("D/M/YY"))
        var result = Math.floor((moment(then.split(" ")[0], "D/M/YY").startOf("day") - moment().startOf("day")) / 86400000);

        var iso_weekday = moment(then.split(" ")[0], "D/M/YY").isoWeekday();
        var diaDaSemana = ['', 'seg', 'ter', 'qua', 'qui', 'sex', 'sab', 'dom'];

        if (then === 'now') {
          result = 0;
          iso_weekday = moment().isoWeekday();
        }

        function parenthesize(s) {
          return "(" + s + ")";
        }

        if (isNaN(result) || result < 0) {
          result = "";
        } else {
          if (result === 1) {
            return "in " + result + " day " + parenthesize(diaDaSemana[iso_weekday]);
          } else if (result === 0) {
            return "today " + parenthesize(diaDaSemana[iso_weekday]);
          } else {
            return "in " + result + " days " + parenthesize(diaDaSemana[iso_weekday]);
          }
        }
      };
    }

    function clean() {
      $scope.notification = "Please log in";
      $scope.tabs = [];
      $scope.loggedIn = false;
    }

    $scope.logout = function() {
      ref.unauth();
      document.location.href = "login.html";
    }

    var authData = ref.getAuth();
    if (authData) {
      init(authData);
    } else {
      clean();
    }
  }]);

  app.directive("focusOn", function() {
    return function(scope, elem, attr) {
      scope.$on(attr.focusOn, function(e) {
        elem[0].focus();
      });
    };
  });
})();
<commit_msg>ignore case of now<commit_after>(function() {
  var app = angular.module('tinatasks', ["components", "firebase"]);
  var ref = new Firebase("https://tinacg.firebaseio.com/tinatasks");

  app.controller('TaskController', ['$rootScope', '$scope', '$firebase', function($rootScope, $scope, $firebase) {
    function init(authData) {
      // $scope.loginStatus = "Welcome back " + authData.password.email + "! Your token expires " + (new Date(authData.expires * 1000));
      $scope.loggedIn = true;

      $scope.notification = authData.password.email + " token expires " + (new Date(authData.expires * 1000));

      var tabsRef = ref.child(authData.uid).child("tabs");
      var sync = $firebase(tabsRef);
      $scope.tabs = sync.$asArray();

      $scope.addTab = function(tabName) {
        $scope.tabs.$add({ name: tabName })
          .then(function() { $scope.refreshTaskRefs(); })
          .then(function() { $scope.notification = "Added tab " + tabName; });
      };

      var tasksRef = [];
      var tasksSync = [];
      $scope.tasks = [];

      var tasksRootRef = ref.child(authData.uid).child("tasks");
      var tasksRootSync = $firebase(tasksRootRef);
      $scope.tasksRoot = tasksRootSync.$asObject();

      $scope.refreshTaskRefs = function() {
        angular.forEach($scope.tabs, function(tab, tabId) {
          tasksRef[tab.name] = ref.child(authData.uid).child("tasks").child(tab.name);
          tasksSync[tab.name] = $firebase(tasksRef[tab.name]);
          $scope.tasks[tab.name] = tasksSync[tab.name].$asArray();

          $scope.tasks[tab.name].$loaded().then(function() {
            $scope.refreshAllTasks();
          });

        });
      };

      $scope.tabs.$loaded().then(function () {
        $scope.refreshTaskRefs();
        //$rootScope.panes[1].select();
        angular.forEach($scope.tabs, function(tab, tabId) {
          // console.log("populate " + tab.name);
          $scope.populateAllTasks(tab.name);
        });
      });

      $scope.updateTask = function(tasks, task) {
        tasks.$save(task)
          .then(function() { $scope.notification = "Changed task " + task.description; });
      }

      $scope.addTask = function(tabName, taskDone, taskDescription, taskCategory, taskDueDate) {
        taskDescription = taskDescription || "My Task";
        taskCategory = taskCategory || "~uncategorized";
        taskDueDate = taskDueDate || "soon";

        $scope.tasks[tabName].$add({ done: taskDone,
                                     description: taskDescription,
                                     category: taskCategory,
                                     createDate: (new Date()).getTime(),
                                     dueDate: taskDueDate,
                                   })
          .then(function() { $scope.notification = "Added " + tabName + "/" + taskDescription; })
          .then(function() { $scope.refreshAllTasks(); });

        $scope.taskDone = false;
        $scope.taskDescription = "";
        $scope.taskCategory = "";
        $scope.taskDueDate = "";

        $scope.$broadcast("newTaskAdded");
      };

      // tasks[tab.name].$remove(task)
      $scope.removeTask = function(tasks, task) {
        tasks.$remove(task)
          .then(function() { $scope.notification = "Removed task " + task.description; })
          .then(function() { $scope.refreshAllTasks(); });
      };

      $scope.deleteTabTasks = function(tabName) {
        tasksRootSync.$remove(tabName)
          .then(function() { $scope.notification = "Deleted tab tasks for " + tabName; })
          .then(function() { $scope.refreshAllTasks(); });
      };

      $scope.removeTab = function(tab) {
        tasksRootSync.$remove(tab.name)
          .then(function() { $scope.tabs.$remove(tab)
                             .then(function() { $scope.notification = "Removed tab " + tab.name; }); })
          .then(function() { $scope.refreshAllTasks(); });
      };

      // ARRAY FOR ALL TASKS

      $scope.allTasks = [];

      $scope.cleanAllTasks = function() {
        $scope.allTasks = [];
      }

      $scope.populateAllTasks = function(tabName) {
        angular.forEach($scope.tasks[tabName], function(task) {
          $scope.allTasks.push(task);
        });
      };

      $scope.refreshAllTasks = function() {
        $scope.cleanAllTasks();
        angular.forEach($scope.tabs, function(tab, tabId) {
          $scope.populateAllTasks(tab.name);
        });
      };

      // TIME AND MOMENT.JS

      $scope.getms = function(s) {
        var m = moment(s, "D/M/YY H:mm:ss");
        var result = m.valueOf();
        if (isNaN(result)) {
          result = 0;
        }
        return result;
      };

      $scope.getFormattedDate = function(ms) {
        var result = moment(ms).locale('pt-BR').format('ddd D-MMM-YY H:mm:ss');
        if (result === 'Invalid date') {
          result = 'data invalida';
        }
        if (ms === undefined) {
          result = "";
        }
        return result;
      };

      $scope.getShortDate = function(ms) {
        // var result = moment(ms).locale('pt-BR').format('D-MMM H:mm:ss');
        var result = moment(ms).locale('pt-BR').format('D-MMM');
        return result;
      };

      $scope.parseDate = function(s) {
        if (s === 'soon') {
          return 9999999999000;
        } else if (s.toLowerCase() === 'now') {
          return moment().valueOf();
        } else {
          return moment(s, "D/M/YY H:mm:ss").valueOf();
        }
      };

      $scope.millisToString = function(ms)
      {
        if (ms < 0 || ms > 3159999999000) {
          return "∞";
        }
        var seconds = Math.floor(ms / 1000);
        var numyears = Math.floor(seconds / 31536000);
        var numdays = Math.floor((seconds % 31536000) / 86400);
        var numhours = Math.floor(((seconds % 31536000) % 86400) / 3600);
        var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
        var numseconds = (((seconds % 31536000) % 86400) % 3600) % 60;

        var result = "";

        if (numyears > 0) {
          result += numyears + "y ";
        }
        if (numdays > 0) {
          result += numdays + "d ";
        }
        if (numhours > 0) {
          result += numhours + "h ";
        }
        if (numminutes > 0) {
          result += numminutes + "m ";
        }
        // if (numseconds > 0) {
        //  result += numseconds + "s";
        // }
        return result;
      }

      $scope.momentNow = function() {
        return moment().valueOf();
      };

      $scope.now = $scope.momentNow();
      $scope.nowFull = moment().locale('pt-BR').format();

      $scope.dueDateOrder = function(task) {
        return $scope.parseDate(task.dueDate);
      }

      function numdays(ms) {
        var seconds = Math.floor(ms / 1000);
        var days = Math.floor(seconds / 86400);

        return days;
      }

      function daysSince01(dmyStr) {
        var dmyParts = dmyStr.split("/");
        var day = Number(dmyParts[0]);
        var month = Number(dmyParts[1]);
        var year = Number(dmyParts[2]);

        var leapYearsPassed = Math.floor(year / 4);

        if (year % 4 === 0 && month > 2) {
          leapYearsPassed -= 1;
        }

        return leapYearsPassed + (year * 365) + moment(dmyStr, "D/M/YY").dayOfYear();
      }

      // pass moment() now to a function that returns D/M/Y

      $scope.daysDiff = function(then, now) {
        // var nineteenseventy = moment("1/1/1970 0:00:00", "D/M/YYYY H:mm:ss");
        // var then_since1970 = numdays(moment(then, "D/M/YY H:mm:ss").valueOf());
        // var now_since1970 = numdays(moment().valueOf());
        // return Math.max(0, then_since1970 - now_since1970);
        // var result = daysSince01(then.split(" ")[0]) - daysSince01(moment().locale('pt-BR').format("D/M/YY"))
        var result = Math.floor((moment(then.split(" ")[0], "D/M/YY").startOf("day") - moment().startOf("day")) / 86400000);

        var iso_weekday = moment(then.split(" ")[0], "D/M/YY").isoWeekday();
        var diaDaSemana = ['', 'seg', 'ter', 'qua', 'qui', 'sex', 'sab', 'dom'];

        if (then.toLowerCase() === 'now') {
          result = 0;
          iso_weekday = moment().isoWeekday();
        }

        function parenthesize(s) {
          return "(" + s + ")";
        }

        if (isNaN(result) || result < 0) {
          result = "";
        } else {
          if (result === 1) {
            return "in " + result + " day " + parenthesize(diaDaSemana[iso_weekday]);
          } else if (result === 0) {
            return "today " + parenthesize(diaDaSemana[iso_weekday]);
          } else {
            return "in " + result + " days " + parenthesize(diaDaSemana[iso_weekday]);
          }
        }
      };
    }

    function clean() {
      $scope.notification = "Please log in";
      $scope.tabs = [];
      $scope.loggedIn = false;
    }

    $scope.logout = function() {
      ref.unauth();
      document.location.href = "login.html";
    }

    var authData = ref.getAuth();
    if (authData) {
      init(authData);
    } else {
      clean();
    }
  }]);

  app.directive("focusOn", function() {
    return function(scope, elem, attr) {
      scope.$on(attr.focusOn, function(e) {
        elem[0].focus();
      });
    };
  });
})();
<|endoftext|>


<commit_before>import React, { PropTypes } from "react"

export const nameWithContext = (Lower, prop = "name") => {
  const getDisplayName = (Lower) => ((Lower.displayName || Lower.name).replace(/Tag$/, ""))

  const buildInputName = (namespaces, name = "") => (
    [ ...namespaces, name ].map((field, index) => ( index === 0 ? field : `[${field}]` )).join("")
  )

  const higher = (props, context) => {
    const replacedProp = buildInputName(context.railsFormNamespaces, props[prop])
    const replacedProps = Object.assign({}, props, { [prop]: replacedProp })
    return <Lower {...replacedProps} />
  }

  higher.displayName = getDisplayName(Lower)
  higher.contextTypes = { railsFormNamespaces: PropTypes.arrayOf(PropTypes.string) }

  return higher
}

export const whitelistProps = (props, ...omit) => {
  const alwaysOmit = [ "key", "ref", ...omit ]
  const cloned = { ...props }
  alwaysOmit.forEach((key) => delete cloned[key])
  return cloned
}
<commit_msg>Fix IE bug when calculating displayName<commit_after>import React, { PropTypes } from "react"

export const nameWithContext = (Lower, prop = "name") => {
  const getDisplayName = (component) => component.displayName || component.name || "Component"

  const buildInputName = (namespaces, name = "") => (
    [ ...namespaces, name ].map((field, index) => ( index === 0 ? field : `[${field}]` )).join("")
  )

  const higher = (props, context) => {
    const replacedProp = buildInputName(context.railsFormNamespaces, props[prop])
    const replacedProps = Object.assign({}, props, { [prop]: replacedProp })
    return <Lower {...replacedProps} />
  }

  higher.displayName = getDisplayName(Lower).replace(/Tag$/, "")
  higher.contextTypes = { railsFormNamespaces: PropTypes.arrayOf(PropTypes.string) }

  return higher
}

export const whitelistProps = (props, ...omit) => {
  const alwaysOmit = [ "key", "ref", ...omit ]
  const cloned = { ...props }
  alwaysOmit.forEach((key) => delete cloned[key])
  return cloned
}
<|endoftext|>


<commit_before>'use strict';

var path = require('path');

var namespaceDelimiters = ['::', ':', '\\.', '/'];
var namespaceDelimitersRegExp = new RegExp(namespaceDelimiters.join('|'), 'g');

exports = module.exports = {

  /**
   * Set the value at the end of the path to val.
   * @param {object} obj    - object on which the `val` will be set
   * @param {array}  fields - path where `val` should be set
   * @param {*}      val    - the value
   */
  setValueAtPath : function (obj, fields, val) {
     for (var i = 0, n = fields.length; i < n && obj !== undefined; i++) {
       var field = fields[i];

       if (typeof obj[field] === 'undefined' || (obj[field] !== Object(obj[field])) ) {
         obj[field] = [];
       }

       if (i === n - 1) {
         obj[field].push(val);
       } else {
         obj = obj[field];
       }
     }
   },

  /**
   * Get file extension
   * @param  {string} filename - filename to retrieve extension from
   * @return {string}            extension
   */
  getExtension: function (filename) {
    return path.extname(filename).substr(1);
  },

  /**
   * Get current date/time
   * @return {string} Stringified date time
   */
  getDateTime: function () {
    var date = new Date(),
        year, month, day, hour, min, sec;

    year  = date.getFullYear();
    month = exports.pad(date.getMonth() + 1);
    day   = exports.pad(date.getDate());
    hour  = exports.pad(date.getHours());
    min   = exports.pad(date.getMinutes());
    sec   = exports.pad(date.getSeconds());

    return year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':' + sec;
  },

  /**
   * Pad a number with a leading 0 if inferior to 10
   * @param  {number} value - number to pad
   * @return {string|number}  padded number or initial number
   */
  pad: function (value) {
    return (value < 10 ? '0' : '') + value;
  },

  /**
   * Returns whether a value is set or not
   * @param {*} value - value to check
   * @return {Bool}
   */
  isset: function (value) {
    return typeof value !== 'undefined';
  },

  /**
   * Split a string on possible namespace delimiters
   * @param {String} value - value to split
   * @return {Array}
   */
  splitNamespace: function (value) {
    return value.split(namespaceDelimitersRegExp);
  }
};
<commit_msg>removed unused function<commit_after>'use strict';

var path = require('path');

var namespaceDelimiters = ['::', ':', '\\.', '/'];
var namespaceDelimitersRegExp = new RegExp(namespaceDelimiters.join('|'), 'g');

exports = module.exports = {

  /**
   * Get file extension
   * @param  {string} filename - filename to retrieve extension from
   * @return {string}            extension
   */
  getExtension: function (filename) {
    return path.extname(filename).substr(1);
  },

  /**
   * Get current date/time
   * @return {string} Stringified date time
   */
  getDateTime: function () {
    var date = new Date(),
        year, month, day, hour, min, sec;

    year  = date.getFullYear();
    month = exports.pad(date.getMonth() + 1);
    day   = exports.pad(date.getDate());
    hour  = exports.pad(date.getHours());
    min   = exports.pad(date.getMinutes());
    sec   = exports.pad(date.getSeconds());

    return year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':' + sec;
  },

  /**
   * Pad a number with a leading 0 if inferior to 10
   * @param  {number} value - number to pad
   * @return {string|number}  padded number or initial number
   */
  pad: function (value) {
    return (value < 10 ? '0' : '') + value;
  },

  /**
   * Returns whether a value is set or not
   * @param {*} value - value to check
   * @return {Bool}
   */
  isset: function (value) {
    return typeof value !== 'undefined';
  },

  /**
   * Split a string on possible namespace delimiters
   * @param {String} value - value to split
   * @return {Array}
   */
  splitNamespace: function (value) {
    return value.split(namespaceDelimitersRegExp);
  }
};
<|endoftext|>


<commit_before>'use babel';

/**
 * Tries to get a property from nested objects, but stops if
 * any property on the path isn't an object.
 *
 * You can use this for example if you want to get `foo.bar.baz`
 * but are not sure if foo.bar` allways exists.
 * In that case you could use `getDeepPropSave(foo, 'bar', 'baz')`.
 *
 * @param   {*}        obj
 * @param   {string[]} path
 * @returns *
 */
export function getDeepPropSave(obj, ...path) {
    let lastEL = obj;
    path.forEach(key => {
        if (typeof lastEL !== 'object') {
            return undefined;
        }
        lastEL = lastEL[key];
    });
    return lastEL;
}

export const attrRegExp = (() => {
    let cache = {};

    return function attrRegExp(name) {
        if (cache[name]) {
            return cache[name];
        } else {
            const regExp = new RegExp(`${name}="([^"]*)"`);
            cache[name] = regExp;
            return regExp;
        }
    };
})();

/**
 * Finds all attributes in a XML tag like text
 *
 * @param   {string}   text
 * @param   {string[]} attributesNames
 * @returns {Object} an object which that maps the attribute names to there values
 */
export function extractAttributes(text) {
    const attributes = {};
    const attrMatch = text.match(/[a-zA-Z0-9_\-]+="[^"]*"/g);
    if (attrMatch) {
        attrMatch.forEach(attrStr => {
            const [, name, value] = attrStr.match(/([a-zA-Z0-9_\-]+)="([^"]*)"/);
            attributes[name] = value;
        });
    }
    return attributes;
}
<commit_msg>Change some JSDoc comments<commit_after>'use babel';

/**
 * Tries to get a property from nested objects, but stops if
 * it encounters a property on the path that is something other
 * then an object.
 *
 * You can use this for example if you want to get `foo.bar.baz`
 * but are not sure if `foo.bar` allways exists.
 * In that case you could use `getDeepPropSave(foo, 'bar', 'baz')`.
 *
 * @param   {*}        obj
 * @param   {string[]} path
 * @returns *
 */
export function getDeepPropSave(obj, ...path) {
    let lastEL = obj;
    path.forEach(key => {
        if (typeof lastEL !== 'object') {
            return undefined;
        }
        lastEL = lastEL[key];
    });
    return lastEL;
}

export const attrRegExp = (() => {
    let cache = {};

    return function attrRegExp(name) {
        if (cache[name]) {
            return cache[name];
        } else {
            const regExp = new RegExp(`${name}="([^"]*)"`);
            cache[name] = regExp;
            return regExp;
        }
    };
})();

/**
 * Finds all attributes in a XML tag like string
 *
 * @param   {string}   text
 * @returns {Object} an object that maps the attribute names to there values
 */
export function extractAttributes(text) {
    const attributes = {};
    const attrMatch = text.match(/[a-zA-Z0-9_\-]+="[^"]*"/g);
    if (attrMatch) {
        attrMatch.forEach(attrStr => {
            const [, name, value] = attrStr.match(/([a-zA-Z0-9_\-]+)="([^"]*)"/);
            attributes[name] = value;
        });
    }
    return attributes;
}
<|endoftext|>


<commit_before>/*
 * These are functions that are useful in many common use
 * cases within Taskcluster projects. They should take an
 * monitor to operate on as their first argument and return
 * a function so that the real and fake classes can share
 * them.
 */
let debug = require('debug')('taskcluster-lib-monitor');
let usage = require('usage');
let Promise = require('promise');

/**
 * Given an express api method, this will time it
 * and report via the monitor.
 */
export function expressMiddleware(monitor, name) {
  return (req, res, next) => {
    let sent = false;
    let start = process.hrtime();
    let send = () => {
      try {
        // Avoid sending twice
        if (sent) {
          return;
        }
        sent = true;

        let d = process.hrtime(start);

        let success = 'success';
        if (res.statusCode >= 500) {
          success = 'server-error';
        } else if (res.statusCode >= 400) {
          success = 'client-error';
        }

        for (let stat of [success, 'all']) {
          let k = [name, stat].join('.');
          monitor.measure(k, d[0] * 1000 + d[1] / 1000000);
          monitor.count(k);
        }
      } catch (e) {
        debug('Error while compiling response times: %s, %j', err, err, err.stack);
      }
    };
    res.once('finish', send);
    res.once('close', send);
    next();
  };
}

/**
 * Given a function that operates on a
 * single message, this will time it and
 * report via the monitor.
 */
export function timedHandler(monitor, name, handler) {
  return async (message) => {
    let start = process.hrtime();
    let success = 'success';
    try {
      await handler(message);
    } catch (e) {
      success = 'error';
      throw e;
    } finally {
      let d = process.hrtime(start);
      for (let stat of [success, 'all']) {
        let k = [name, stat].join('.');
        monitor.measure(k, d[0] * 1000 + d[1] / 1000000);
        monitor.count(k);
      }
    }
  };
}

/**
 * Given a process name, this will report basic
 * OS-level usage statistics like CPU and Memory
 * on a minute-by-minute basis.
 *
 * Returns a function that can be used to stop monitoring.
 */
export function resources(monitor, proc, seconds) {
  if (monitor._resourceInterval) {
    clearInterval(monitor._resourceInterval);
  }

  let interval = setInterval(() => {
    usage.lookup(process.pid, {keepHistory: true}, (err, result) => {
      if (err) {
        debug('Failed to get usage statistics, err: %s, %j',  err, err, err.stack);
        return;
      }
      monitor.measure('process.' + proc + '.cpu', result.cpu);
      monitor.measure('process.' + proc + '.mem', result.memory);
    });
  }, seconds * 1000);

  monitor._resourceInterval = interval;
  return () => clearInterval(interval);
}

export function timer (monitor, prefix, funcOrPromise) {
  let start = process.hrtime();
  let done = () => {
    let d = process.hrtime(start);
    monitor.measure(prefix, d[0] * 1000 + d[1] / 1000000);
  };
  if (funcOrPromise instanceof Function) {
    try {
      funcOrPromise = funcOrPromise();
    } finally {
      // If this is a sync function that throws, we let it...
      // We just remember to call done() afterwards
      done();
    }
  }
  Promise.resolve(funcOrPromise).then(done, done);
  return funcOrPromise;
}
<commit_msg>fix linter<commit_after>/*
 * These are functions that are useful in many common use
 * cases within Taskcluster projects. They should take an
 * monitor to operate on as their first argument and return
 * a function so that the real and fake classes can share
 * them.
 */
let debug = require('debug')('taskcluster-lib-monitor');
let usage = require('usage');
let Promise = require('promise');

/**
 * Given an express api method, this will time it
 * and report via the monitor.
 */
export function expressMiddleware(monitor, name) {
  return (req, res, next) => {
    let sent = false;
    let start = process.hrtime();
    let send = () => {
      try {
        // Avoid sending twice
        if (sent) {
          return;
        }
        sent = true;

        let d = process.hrtime(start);

        let success = 'success';
        if (res.statusCode >= 500) {
          success = 'server-error';
        } else if (res.statusCode >= 400) {
          success = 'client-error';
        }

        for (let stat of [success, 'all']) {
          let k = [name, stat].join('.');
          monitor.measure(k, d[0] * 1000 + d[1] / 1000000);
          monitor.count(k);
        }
      } catch (e) {
        debug('Error while compiling response times: %s, %j', err, err, err.stack);
      }
    };
    res.once('finish', send);
    res.once('close', send);
    next();
  };
}

/**
 * Given a function that operates on a
 * single message, this will time it and
 * report via the monitor.
 */
export function timedHandler(monitor, name, handler) {
  return async (message) => {
    let start = process.hrtime();
    let success = 'success';
    try {
      await handler(message);
    } catch (e) {
      success = 'error';
      throw e;
    } finally {
      let d = process.hrtime(start);
      for (let stat of [success, 'all']) {
        let k = [name, stat].join('.');
        monitor.measure(k, d[0] * 1000 + d[1] / 1000000);
        monitor.count(k);
      }
    }
  };
}

/**
 * Given a process name, this will report basic
 * OS-level usage statistics like CPU and Memory
 * on a minute-by-minute basis.
 *
 * Returns a function that can be used to stop monitoring.
 */
export function resources(monitor, proc, seconds) {
  if (monitor._resourceInterval) {
    clearInterval(monitor._resourceInterval);
  }

  let interval = setInterval(() => {
    usage.lookup(process.pid, {keepHistory: true}, (err, result) => {
      if (err) {
        debug('Failed to get usage statistics, err: %s, %j',  err, err, err.stack);
        return;
      }
      monitor.measure('process.' + proc + '.cpu', result.cpu);
      monitor.measure('process.' + proc + '.mem', result.memory);
    });
  }, seconds * 1000);

  monitor._resourceInterval = interval;
  return () => clearInterval(interval);
}

export function timer(monitor, prefix, funcOrPromise) {
  let start = process.hrtime();
  let done = () => {
    let d = process.hrtime(start);
    monitor.measure(prefix, d[0] * 1000 + d[1] / 1000000);
  };
  if (funcOrPromise instanceof Function) {
    try {
      funcOrPromise = funcOrPromise();
    } finally {
      // If this is a sync function that throws, we let it...
      // We just remember to call done() afterwards
      done();
    }
  }
  Promise.resolve(funcOrPromise).then(done, done);
  return funcOrPromise;
}
<|endoftext|>


<commit_before>"use strict";

var axios = require("axios");
var isEqual = require("fast-deep-equal");
var isBuffer = require("is-buffer");
var isBlob = require("is-blob");
var toString = Object.prototype.toString;

// < 0.13.0 will not have default headers set on a custom instance
var rejectWithError = !!axios.create().defaults.headers;

function find(array, predicate) {
  var length = array.length;
  for (var i = 0; i < length; i++) {
    var value = array[i];
    if (predicate(value)) return value;
  }
}

function isFunction(val) {
  return toString.call(val) === "[object Function]";
}

function isObjectOrArray(val) {
  return val !== null && typeof val === "object";
}

function isStream(val) {
  return isObjectOrArray(val) && isFunction(val.pipe);
}

function isArrayBuffer(val) {
  return toString.call(val) === "[object ArrayBuffer]";
}

function combineUrls(baseURL, url) {
  if (baseURL) {
    return baseURL.replace(/\/+$/, "") + "/" + url.replace(/^\/+/, "");
  }

  return url;
}

function findHandler(
  handlers,
  method,
  url,
  body,
  parameters,
  headers,
  baseURL
) {
  return find(handlers[method.toLowerCase()], function (handler) {
    if (typeof handler[0] === "string") {
      return (
        (isUrlMatching(url, handler[0]) ||
          isUrlMatching(combineUrls(baseURL, url), handler[0])) &&
        isBodyOrParametersMatching(method, body, parameters, handler[1]) &&
        isObjectMatching(headers, handler[2])
      );
    } else if (handler[0] instanceof RegExp) {
      return (
        (handler[0].test(url) || handler[0].test(combineUrls(baseURL, url))) &&
        isBodyOrParametersMatching(method, body, parameters, handler[1]) &&
        isObjectMatching(headers, handler[2])
      );
    }
  });
}

function isUrlMatching(url, required) {
  var noSlashUrl = url[0] === "/" ? url.substr(1) : url;
  var noSlashRequired = required[0] === "/" ? required.substr(1) : required;
  return noSlashUrl === noSlashRequired;
}

function isBodyOrParametersMatching(method, body, parameters, required) {
  var allowedParamsMethods = ["delete", "get", "head", "options"];
  if (allowedParamsMethods.indexOf(method.toLowerCase()) >= 0) {
    var params = required ? required.params : undefined;
    return isObjectMatching(parameters, params);
  } else {
    return isBodyMatching(body, required);
  }
}

function isObjectMatching(actual, expected) {
  if (expected === undefined) return true;
  if (typeof expected.asymmetricMatch === "function") {
    return expected.asymmetricMatch(actual);
  }
  return isEqual(actual, expected);
}

function isBodyMatching(body, requiredBody) {
  if (requiredBody === undefined) {
    return true;
  }
  var parsedBody;
  try {
    parsedBody = JSON.parse(body);
  } catch (e) {}

  return isObjectMatching(parsedBody ? parsedBody : body, requiredBody);
}

function purgeIfReplyOnce(mock, handler) {
  Object.keys(mock.handlers).forEach(function (key) {
    var index = mock.handlers[key].indexOf(handler);
    if (index > -1) {
      mock.handlers[key].splice(index, 1);
    }
  });
}

function settle(resolve, reject, response, delay) {
  if (delay > 0) {
    setTimeout(settle, delay, resolve, reject, response);
    return;
  }

  // Support for axios < 0.13
  if (!rejectWithError && (!response.config || !response.config.validateStatus)) {
    if (response.status >= 200 && response.status < 300) {
      resolve(response);
    } else {
      reject(response);
    }
    return;
  }

  if (
    !response.config.validateStatus ||
    response.config.validateStatus(response.status)
  ) {
    resolve(response);
  } else {
    if (!rejectWithError) {
      return reject(response);
    }

    reject(createAxiosError(
      'Request failed with status code ' + response.status,
      response.config,
      response
    ));
  }
}

function createAxiosError(message, config, response, code) {
  var error = new Error(message);
  error.isAxiosError = true;
  error.config = config;
  if (response !== undefined) {
    error.response = response;
  }
  if (code !== undefined) {
    error.code = code;
  }

  error.toJSON = function toJSON() {
    return {
      // Standard
      message: this.message,
      name: this.name,
      // Microsoft
      description: this.description,
      number: this.number,
      // Mozilla
      fileName: this.fileName,
      lineNumber: this.lineNumber,
      columnNumber: this.columnNumber,
      stack: this.stack,
      // Axios
      config: this.config,
      code: this.code,
    };
  };
  return error;
}

function createCouldNotFindMockError(config) {
  var message =
    "Could not find mock for: \n" +
    JSON.stringify(config, ["method", "url"], 2);
  var error = new Error(message);
  error.isCouldNotFindMockError = true;
  error.url = config.url;
  error.method = config.method;
  return error;
}

module.exports = {
  find: find,
  findHandler: findHandler,
  purgeIfReplyOnce: purgeIfReplyOnce,
  settle: settle,
  isStream: isStream,
  isArrayBuffer: isArrayBuffer,
  isFunction: isFunction,
  isObjectOrArray: isObjectOrArray,
  isBuffer: isBuffer,
  isBlob: isBlob,
  isEqual: isEqual,
  createAxiosError: createAxiosError,
  createCouldNotFindMockError: createCouldNotFindMockError,
};
<commit_msg>Formatting<commit_after>"use strict";

var axios = require("axios");
var isEqual = require("fast-deep-equal");
var isBuffer = require("is-buffer");
var isBlob = require("is-blob");
var toString = Object.prototype.toString;

// < 0.13.0 will not have default headers set on a custom instance
var rejectWithError = !!axios.create().defaults.headers;

function find(array, predicate) {
  var length = array.length;
  for (var i = 0; i < length; i++) {
    var value = array[i];
    if (predicate(value)) return value;
  }
}

function isFunction(val) {
  return toString.call(val) === "[object Function]";
}

function isObjectOrArray(val) {
  return val !== null && typeof val === "object";
}

function isStream(val) {
  return isObjectOrArray(val) && isFunction(val.pipe);
}

function isArrayBuffer(val) {
  return toString.call(val) === "[object ArrayBuffer]";
}

function combineUrls(baseURL, url) {
  if (baseURL) {
    return baseURL.replace(/\/+$/, "") + "/" + url.replace(/^\/+/, "");
  }

  return url;
}

function findHandler(
  handlers,
  method,
  url,
  body,
  parameters,
  headers,
  baseURL
) {
  return find(handlers[method.toLowerCase()], function (handler) {
    if (typeof handler[0] === "string") {
      return (
        (isUrlMatching(url, handler[0]) ||
          isUrlMatching(combineUrls(baseURL, url), handler[0])) &&
        isBodyOrParametersMatching(method, body, parameters, handler[1]) &&
        isObjectMatching(headers, handler[2])
      );
    } else if (handler[0] instanceof RegExp) {
      return (
        (handler[0].test(url) || handler[0].test(combineUrls(baseURL, url))) &&
        isBodyOrParametersMatching(method, body, parameters, handler[1]) &&
        isObjectMatching(headers, handler[2])
      );
    }
  });
}

function isUrlMatching(url, required) {
  var noSlashUrl = url[0] === "/" ? url.substr(1) : url;
  var noSlashRequired = required[0] === "/" ? required.substr(1) : required;
  return noSlashUrl === noSlashRequired;
}

function isBodyOrParametersMatching(method, body, parameters, required) {
  var allowedParamsMethods = ["delete", "get", "head", "options"];
  if (allowedParamsMethods.indexOf(method.toLowerCase()) >= 0) {
    var params = required ? required.params : undefined;
    return isObjectMatching(parameters, params);
  } else {
    return isBodyMatching(body, required);
  }
}

function isObjectMatching(actual, expected) {
  if (expected === undefined) return true;
  if (typeof expected.asymmetricMatch === "function") {
    return expected.asymmetricMatch(actual);
  }
  return isEqual(actual, expected);
}

function isBodyMatching(body, requiredBody) {
  if (requiredBody === undefined) {
    return true;
  }
  var parsedBody;
  try {
    parsedBody = JSON.parse(body);
  } catch (e) {}

  return isObjectMatching(parsedBody ? parsedBody : body, requiredBody);
}

function purgeIfReplyOnce(mock, handler) {
  Object.keys(mock.handlers).forEach(function (key) {
    var index = mock.handlers[key].indexOf(handler);
    if (index > -1) {
      mock.handlers[key].splice(index, 1);
    }
  });
}

function settle(resolve, reject, response, delay) {
  if (delay > 0) {
    setTimeout(settle, delay, resolve, reject, response);
    return;
  }

  // Support for axios < 0.13
  if (
    !rejectWithError &&
    (!response.config || !response.config.validateStatus)
  ) {
    if (response.status >= 200 && response.status < 300) {
      resolve(response);
    } else {
      reject(response);
    }
    return;
  }

  if (
    !response.config.validateStatus ||
    response.config.validateStatus(response.status)
  ) {
    resolve(response);
  } else {
    if (!rejectWithError) {
      return reject(response);
    }

    reject(
      createAxiosError(
        "Request failed with status code " + response.status,
        response.config,
        response
      )
    );
  }
}

function createAxiosError(message, config, response, code) {
  var error = new Error(message);
  error.isAxiosError = true;
  error.config = config;
  if (response !== undefined) {
    error.response = response;
  }
  if (code !== undefined) {
    error.code = code;
  }

  error.toJSON = function toJSON() {
    return {
      // Standard
      message: this.message,
      name: this.name,
      // Microsoft
      description: this.description,
      number: this.number,
      // Mozilla
      fileName: this.fileName,
      lineNumber: this.lineNumber,
      columnNumber: this.columnNumber,
      stack: this.stack,
      // Axios
      config: this.config,
      code: this.code,
    };
  };
  return error;
}

function createCouldNotFindMockError(config) {
  var message =
    "Could not find mock for: \n" +
    JSON.stringify(config, ["method", "url"], 2);
  var error = new Error(message);
  error.isCouldNotFindMockError = true;
  error.url = config.url;
  error.method = config.method;
  return error;
}

module.exports = {
  find: find,
  findHandler: findHandler,
  purgeIfReplyOnce: purgeIfReplyOnce,
  settle: settle,
  isStream: isStream,
  isArrayBuffer: isArrayBuffer,
  isFunction: isFunction,
  isObjectOrArray: isObjectOrArray,
  isBuffer: isBuffer,
  isBlob: isBlob,
  isEqual: isEqual,
  createAxiosError: createAxiosError,
  createCouldNotFindMockError: createCouldNotFindMockError,
};
<|endoftext|>


<commit_before>var _doGetTrimRect = function (pixelBuffer, w, h, trimThreshold) {
    // A B C
    // D x F
    // G H I

    var tx = w, ty = h,
        tw = 0, th = 0,
        ditch = w * 4;

    var x, y, i;
    var index;  // alpha index in pixels

    // trim A B C
    for (y = 0; y < h; y++) {
        index = y * ditch + 3;  // (x + y * w) * 4 + 3
        for (x = 0; x < w; x++, index += 4) {
            if (pixelBuffer[index] >= trimThreshold) {
                ty = y;
                y = h;
                break;
            }
        }
    }
    // trim G H I
    for (y = h - 1; y >= ty; y--) {
        index = y * ditch + 3;
        for (x = 0; x < w; x++, index += 4) {
            if (pixelBuffer[index] >= trimThreshold) {
                th = y - ty + 1;
                y = 0;
                break;
            }
        }
    }
    var skipTrimmedY = ditch * ty;   // skip A B C
    // trim D
    for (x = 0; x < w; x++) {
        index = skipTrimmedY + x * 4 + 3;
        for (i = 0; i < th; i++, index += ditch) {
            if (pixelBuffer[index] >= trimThreshold) {
                tx = x;
                x = w;
                break;
            }
        }
    }
    // trim F
    for (x = w - 1; x >= tx; x--) {
        index = skipTrimmedY + x * 4 + 3;
        for (i = 0; i < th; i++, index += ditch) {
            if (pixelBuffer[index] >= trimThreshold) {
                tw = x - tx + 1;
                x = 0;
                break;
            }
        }
    }

    return new FIRE.Rect(tx, ty, tw, th);
};

//
FIRE.getEnumList = function (enumDef) {
    if ( enumDef.__enums__ !== undefined )
        return enumDef.__enums__;

    var enums = [];
    for ( var entry in enumDef ) {
        if ( enumDef.hasOwnProperty(entry) ) {
            var test = parseInt(entry);
            if ( isNaN(test) ) {
                enums.push( { name: enumDef[enumDef[entry]], value: enumDef[entry] } );
            }
        }
    }
    enums.sort( function ( a, b ) { return a.value - b.value; } );

    enumDef.__enums__ = enums;
    return enumDef.__enums__;
};

//
FIRE.getVarFrom = function ( obj, text ) {
    var res = text.split('.');
    var curObj = obj;
    for ( var i = 0; i < res.length; ++i ) {
        var name = res[i];
        curObj = curObj[name];
        if ( curObj === undefined || curObj === null )
            return null;
    }
    return curObj;
};

// r, g, b must be [0.0, 1.0]
FIRE.rgb2hsv = function ( r, g, b ) {
    var hsv = { h: 0, s: 0, v: 0 };
    var max = Math.max(r,g,b);
    var min = Math.min(r,g,b);
    var delta = 0;
    hsv.v = max;
    hsv.s = max ? (max - min) / max : 0;
    if (!hsv.s) hsv.h = 0;
    else {
        delta = max - min;
        if (r == max) hsv.h = (g - b) / delta;
        else if (g == max) hsv.h = 2 + (b - r) / delta;
        else hsv.h = 4 + (r - g) / delta;
        hsv.h /= 6;
        if (hsv.h < 0) hsv.h += 1.0;
    }
    return hsv;
};

// the return rgb will be in [0.0, 1.0]
FIRE.hsv2rgb = function ( h, s, v ) {
    var rgb = { r: 0, g: 0, b: 0 };
    if (s === 0) {
        rgb.r = rgb.g = rgb.b = v;
    }
    else {
        if (v === 0) {
            rgb.r = rgb.g = rgb.b = 0;
        }
        else {
            if (h === 1) h = 0;
            h *= 6;
            s = s;
            v = v;
            var i = Math.floor(h);
            var f = h - i;
            var p = v * (1 - s);
            var q = v * (1 - (s * f));
            var t = v * (1 - (s * (1 - f)));
            switch (i) {
                case 0:
                    rgb.r = v;
                    rgb.g = t;
                    rgb.b = p;
                    break;

                case 1:
                    rgb.r = q;
                    rgb.g = v;
                    rgb.b = p;
                    break;

                case 2:
                    rgb.r = p;
                    rgb.g = v;
                    rgb.b = t;
                    break;

                case 3:
                    rgb.r = p;
                    rgb.g = q;
                    rgb.b = v;
                    break;

                case 4:
                    rgb.r = t;
                    rgb.g = p;
                    rgb.b = v;
                    break;

                case 5:
                    rgb.r = v;
                    rgb.g = p;
                    rgb.b = q;
                    break;
            }
        }
    }
    return rgb;
};
<commit_msg>#15 add Nullable<commit_after>var _doGetTrimRect = function (pixelBuffer, w, h, trimThreshold) {
    // A B C
    // D x F
    // G H I

    var tx = w, ty = h,
        tw = 0, th = 0,
        ditch = w * 4;

    var x, y, i;
    var index;  // alpha index in pixels

    // trim A B C
    for (y = 0; y < h; y++) {
        index = y * ditch + 3;  // (x + y * w) * 4 + 3
        for (x = 0; x < w; x++, index += 4) {
            if (pixelBuffer[index] >= trimThreshold) {
                ty = y;
                y = h;
                break;
            }
        }
    }
    // trim G H I
    for (y = h - 1; y >= ty; y--) {
        index = y * ditch + 3;
        for (x = 0; x < w; x++, index += 4) {
            if (pixelBuffer[index] >= trimThreshold) {
                th = y - ty + 1;
                y = 0;
                break;
            }
        }
    }
    var skipTrimmedY = ditch * ty;   // skip A B C
    // trim D
    for (x = 0; x < w; x++) {
        index = skipTrimmedY + x * 4 + 3;
        for (i = 0; i < th; i++, index += ditch) {
            if (pixelBuffer[index] >= trimThreshold) {
                tx = x;
                x = w;
                break;
            }
        }
    }
    // trim F
    for (x = w - 1; x >= tx; x--) {
        index = skipTrimmedY + x * 4 + 3;
        for (i = 0; i < th; i++, index += ditch) {
            if (pixelBuffer[index] >= trimThreshold) {
                tw = x - tx + 1;
                x = 0;
                break;
            }
        }
    }

    return new FIRE.Rect(tx, ty, tw, th);
};

//
FIRE.getEnumList = function (enumDef) {
    if ( enumDef.__enums__ !== undefined )
        return enumDef.__enums__;

    var enums = [];
    for ( var entry in enumDef ) {
        if ( enumDef.hasOwnProperty(entry) ) {
            var test = parseInt(entry);
            if ( isNaN(test) ) {
                enums.push( { name: enumDef[enumDef[entry]], value: enumDef[entry] } );
            }
        }
    }
    enums.sort( function ( a, b ) { return a.value - b.value; } );

    enumDef.__enums__ = enums;
    return enumDef.__enums__;
};

//
FIRE.getVarFrom = function ( obj, text ) {
    var res = text.split('.');
    var curObj = obj;
    for ( var i = 0; i < res.length; ++i ) {
        var name = res[i];
        curObj = curObj[name];
        if ( curObj === undefined || curObj === null )
            return null;
    }
    return curObj;
};

// r, g, b must be [0.0, 1.0]
FIRE.rgb2hsv = function ( r, g, b ) {
    var hsv = { h: 0, s: 0, v: 0 };
    var max = Math.max(r,g,b);
    var min = Math.min(r,g,b);
    var delta = 0;
    hsv.v = max;
    hsv.s = max ? (max - min) / max : 0;
    if (!hsv.s) hsv.h = 0;
    else {
        delta = max - min;
        if (r == max) hsv.h = (g - b) / delta;
        else if (g == max) hsv.h = 2 + (b - r) / delta;
        else hsv.h = 4 + (r - g) / delta;
        hsv.h /= 6;
        if (hsv.h < 0) hsv.h += 1.0;
    }
    return hsv;
};

// the return rgb will be in [0.0, 1.0]
FIRE.hsv2rgb = function ( h, s, v ) {
    var rgb = { r: 0, g: 0, b: 0 };
    if (s === 0) {
        rgb.r = rgb.g = rgb.b = v;
    }
    else {
        if (v === 0) {
            rgb.r = rgb.g = rgb.b = 0;
        }
        else {
            if (h === 1) h = 0;
            h *= 6;
            s = s;
            v = v;
            var i = Math.floor(h);
            var f = h - i;
            var p = v * (1 - s);
            var q = v * (1 - (s * f));
            var t = v * (1 - (s * (1 - f)));
            switch (i) {
                case 0:
                    rgb.r = v;
                    rgb.g = t;
                    rgb.b = p;
                    break;

                case 1:
                    rgb.r = q;
                    rgb.g = v;
                    rgb.b = p;
                    break;

                case 2:
                    rgb.r = p;
                    rgb.g = v;
                    rgb.b = t;
                    break;

                case 3:
                    rgb.r = p;
                    rgb.g = q;
                    rgb.b = v;
                    break;

                case 4:
                    rgb.r = t;
                    rgb.g = p;
                    rgb.b = v;
                    break;

                case 5:
                    rgb.r = v;
                    rgb.g = p;
                    rgb.b = q;
                    break;
            }
        }
    }
    return rgb;
};

// Support can be assigned a null value type
FIRE.Nullable = (function () {
    function Nullable(hasValue, value) {
        this.hasValue = haValue;
        this.value = value;
    }
    return Nullable;
})();<|endoftext|>


<commit_before>import {
  pendingActionCreator,
  doneActionCreator,
  failureActionCreator,
} from './actionCreators';
import createAsyncActionsStateChecker from './createAsyncActionsStateChecker';

export const hasDone = (state, ...checkFor) =>
createAsyncActionsStateChecker(state, ...checkFor).hasDone();

export function createActionCreatorFromPromise(
  manageAsyncStateFor,
  getPromise,
  actionCreator,
  lockIfAlreadyInPending = true,
  debounce = false
) {
  if (!manageAsyncStateFor) {
    throw new Error(`createActionCreatorFromPromise: manageAsyncStateFor is required,${
    ''}it can be a function or a string`);
  }

  if (!getPromise) {
    throw new Error('createActionCreatorFromPromise: getPromise is required');
  }

  let lastRequestKey;

  return (...args) => (dispatch, getState) => {
    let key;
    let group;
    let asyncStateFor;

    if (typeof manageAsyncStateFor === 'function') {
      const manageAsyncStateForArgs = args.slice(0);
      manageAsyncStateForArgs.push(getState);
      asyncStateFor = manageAsyncStateFor(...manageAsyncStateForArgs);
    } else {
      asyncStateFor = manageAsyncStateFor;
    }

    if (typeof asyncStateFor === 'object') {
      key = asyncStateFor.key;
      group = asyncStateFor.group;
    } else if (typeof asyncStateFor === 'string') {
      key = asyncStateFor;
    }

    // use a bool or a string property
    if (lockIfAlreadyInPending !== false) {
      if (
        typeof lockIfAlreadyInPending === 'boolean' &&
        !hasDone(getState(), key)
      ) {
        return Promise.resolve();
      }

      if (
        typeof lockIfAlreadyInPending === 'string' &&
        !hasDone(getState(), lockIfAlreadyInPending)
      ) {
        return Promise.resolve();
      }

      if (
        typeof lockIfAlreadyInPending === 'object' &&
        lockIfAlreadyInPending.length &&
        !hasDone(getState(), ...lockIfAlreadyInPending)
      ) {
        return Promise.resolve();
      }

      if (
        typeof lockIfAlreadyInPending === 'object' &&
        typeof lockIfAlreadyInPending.length === 'undefined' &&
        !hasDone(getState(), lockIfAlreadyInPending)
      ) {
        return Promise.resolve();
      }
    }

    const _lastRequestKey = (new Date()).getTime() + (Math.random() + 1000);
    lastRequestKey = _lastRequestKey;

    dispatch(pendingActionCreator(key, group));

    const promiseArgs = args.slice(0);
    promiseArgs.push(dispatch, getState);

    return getPromise(...promiseArgs)
      .then((d) => {
        if (debounce) {
          if (lastRequestKey !== _lastRequestKey) {
            return;
          }
        }

        const doneActionCreatorArgs = args.slice(0);
        doneActionCreatorArgs.push(d, getState);

        dispatch(doneActionCreator(
          key,
          actionCreator(...doneActionCreatorArgs)
        ));
      })
      .catch((e) => {
        if (debounce) {
          if (lastRequestKey !== _lastRequestKey) {
            return;
          }
        }

        dispatch(failureActionCreator(key, e));
      })
    ;
  };
}
<commit_msg>refactor(util): createActionCreatorFromPromise return promise chainable values<commit_after>import {
  pendingActionCreator,
  doneActionCreator,
  failureActionCreator,
} from './actionCreators';
import createAsyncActionsStateChecker from './createAsyncActionsStateChecker';

export const hasDone = (state, ...checkFor) =>
createAsyncActionsStateChecker(state, ...checkFor).hasDone();

export function createActionCreatorFromPromise(
  manageAsyncStateFor,
  getPromise,
  actionCreator,
  lockIfAlreadyInPending = true,
  debounce = false
) {
  if (!manageAsyncStateFor) {
    throw new Error(`createActionCreatorFromPromise: manageAsyncStateFor is required,${
    ''}it can be a function or a string`);
  }

  if (!getPromise) {
    throw new Error('createActionCreatorFromPromise: getPromise is required');
  }

  let lastRequestKey;

  return (...args) => (dispatch, getState) => {
    let key;
    let group;
    let asyncStateFor;

    if (typeof manageAsyncStateFor === 'function') {
      const manageAsyncStateForArgs = args.slice(0);
      manageAsyncStateForArgs.push(getState);
      asyncStateFor = manageAsyncStateFor(...manageAsyncStateForArgs);
    } else {
      asyncStateFor = manageAsyncStateFor;
    }

    if (typeof asyncStateFor === 'object') {
      key = asyncStateFor.key;
      group = asyncStateFor.group;
    } else if (typeof asyncStateFor === 'string') {
      key = asyncStateFor;
    }

    // use a bool or a string property
    if (lockIfAlreadyInPending !== false) {
      if (
        typeof lockIfAlreadyInPending === 'boolean' &&
        !hasDone(getState(), key)
      ) {
        return Promise.resolve();
      }

      if (
        typeof lockIfAlreadyInPending === 'string' &&
        !hasDone(getState(), lockIfAlreadyInPending)
      ) {
        return Promise.resolve();
      }

      if (
        typeof lockIfAlreadyInPending === 'object' &&
        lockIfAlreadyInPending.length &&
        !hasDone(getState(), ...lockIfAlreadyInPending)
      ) {
        return Promise.resolve();
      }

      if (
        typeof lockIfAlreadyInPending === 'object' &&
        typeof lockIfAlreadyInPending.length === 'undefined' &&
        !hasDone(getState(), lockIfAlreadyInPending)
      ) {
        return Promise.resolve();
      }
    }

    const _lastRequestKey = (new Date()).getTime() + (Math.random() + 1000);
    lastRequestKey = _lastRequestKey;

    dispatch(pendingActionCreator(key, group));

    const promiseArgs = args.slice(0);
    promiseArgs.push(dispatch, getState);

    return getPromise(...promiseArgs)
      .then((d) => {
        if (debounce) {
          if (lastRequestKey !== _lastRequestKey) {
            return void 0;
          }
        }

        const doneActionCreatorArgs = args.slice(0);
        doneActionCreatorArgs.push(d, getState);

        dispatch(doneActionCreator(
          key,
          actionCreator(...doneActionCreatorArgs)
        ));

        return d;
      })
      .catch((e) => {
        if (debounce) {
          if (lastRequestKey !== _lastRequestKey) {
            return void 0;
          }
        }

        dispatch(failureActionCreator(key, e));

        return e;
      })
    ;
  };
}
<|endoftext|>


<commit_before>"use strict";

/**
 * May be run as:
 * plain script (from <script> tag or whatever),
 * plain worker script (calling importScripts from worker),
 * multipart crypto-operation worker (calling new Worker and passing options via url-fragment).
 *
 * The last option is detected here.
 */
var _is_crypto_worker = ( global.document === undefined && global.location.hash.length > 0 );

function string_to_bytes ( str ) {
    // TODO
}

function hex_to_bytes ( str ) {
    // TODO
}

function base64_to_bytes ( str ) {
    // TODO
}

function bytes_to_string ( arr ) {
    var str = '';
    for ( var i = 0; i < arr.length; i++ ) str += String.fromCharCode( arr[i] );
    return str;
}

function bytes_to_hex ( arr ) {
    var sz = ( arr.byteLength || arr.length ) / arr.length,
        str = '';
    for ( var i = 0; i < arr.length; i++ ) {
        var h = arr[i].toString(16);
        if ( h.length < 2*sz ) str += '00000000000000'.substr( 0, 2*sz-h.length );
        str += h;
    }
    return str;
}

function bytes_to_base64 ( arr ) {
    return btoa( bytes_to_string(arr) );
}
<commit_msg>Implemented missing tools functions<commit_after>"use strict";

/**
 * May be run as:
 * plain script (from <script> tag or whatever),
 * plain worker script (calling importScripts from worker),
 * multipart crypto-operation worker (calling new Worker and passing options via url-fragment).
 *
 * The last option is detected here.
 */
var _is_crypto_worker = ( global.document === undefined && global.location.hash.length > 0 );

function string_to_bytes ( str ) {
    var i,
        len=str.length,
        arr = new Uint8Array( len );
    for ( i=0; i<len; i+=1 ) {
        arr[i] = str.charCodeAt(i);
    }
    return arr;
}

function hex_to_bytes ( str ) {
    var arr = [],
        len = str.length,
        i;
    for( i=0; i<len; i+=2 ) {
        arr.push( parseInt( str.substr( i, 2), 16 ) );
    }
    return arr;
}

function base64_to_bytes ( str ) {
    return string_to_bytes( atob( str ) );
}

function bytes_to_string ( arr ) {
    var str = '';
    for ( var i = 0; i < arr.length; i++ ) str += String.fromCharCode( arr[i] );
    return str;
}

function bytes_to_hex ( arr ) {
    var sz = ( arr.byteLength || arr.length ) / arr.length,
        str = '';
    for ( var i = 0; i < arr.length; i++ ) {
        var h = arr[i].toString(16);
        if ( h.length < 2*sz ) str += '00000000000000'.substr( 0, 2*sz-h.length );
        str += h;
    }
    return str;
}

function bytes_to_base64 ( arr ) {
    return btoa( bytes_to_string(arr) );
}
<|endoftext|>


<commit_before>'use strict';

var Http = require('http');

var Connect = /** @type Connect */ require('./track/Connect');
var Router = /** @type Router */ require('finger/Router');
var Tracker = /** @type Tracker */ require('./Tracker');

var _ = require('lodash-node');
var inherit = require('inherit');
var vow = require('vow');

/**
 * @class Framework
 * @extends Tracker
 * */
var Framework = inherit(Tracker, /** @lends Framework.prototype */ {

    /**
     * @private
     * @memberOf {Framework}
     * @method
     *
     * @param {Object} [params]
     *
     * @constructs
     * */
    __constructor: function (params) {
        this.__base(params);

        /**
         * Тут откладываются запросы поступившие во время инициализации
         *
         * @protected
         * @memberOf {Framework}
         * @property
         * @type {Array<Track>}
         * */
        this._pends = [];

        /**
         * Плагины, задачи на инициализацию
         *
         * @protected
         * @memberOf {Framework}
         * @property
         * @type {Array<Function>}
         * */
        this._plugs = [];

        /**
         * Шаблоны для track.render()
         *
         * @public
         * @memberOf {Framework}
         * @property
         * @type {Object<Function>}
         * */
        this.renderers = {};

        /**
         * @public
         * @memberOf {Framework}
         * @property
         * @type {Router}
         * */
        this.router = this._createRouter(this.params.router);
    },

    /**
     * Возвращает коллбэк для запросов на сервер
     *
     * @public
     * @memberOf {Framework}
     * @method
     *
     * @returns {Function}
     * */
    getHandler: function () {

        var self = this;

        return function (req, res) {

            var date = new Date();
            var track = self._createTrack(req, res);

            res.once('finish', function () {
                track.time = new Date() - date;
                self.emit('sys:response', track);
            });

            self.emit('sys:request', track);

            self._handle(track);
        };
    },

    /**
     * Запускает сервер и инициализацию приложения
     *
     * @public
     * @memberOf {Framework}
     * @method
     * */
    listen: function () {

        var server = Http.createServer(this.getHandler());

        server.listen.apply(server, arguments);

        //  автоматически запускаю инициализацию
        this.ready(true);

        return server;
    },

    /**
     * Добавляет плагин[ы]
     *
     * @public
     * @memberOf {Framework}
     * @method
     * */
    plug: function () {
        Array.prototype.push.apply(this._plugs, arguments);
    },

    /**
     * Запускает операцию разрешения узла.
     * Если один из узлов, участвующих в операции
     * разрешения выполнил ответ приложения самостоятельно,
     * то коллбэк вызван не будет
     *
     * @public
     * @memberOf {Tracker}
     * @method
     *
     * @param {Connect} track
     * @param {String} path
     * @param {*} [params]
     *
     * @returns {vow.Promise}
     * */
    resolve: function (track, path, params) {

        var defer = vow.defer();

        this.__base(track, path, params).
            always(function (res) {

                if ( track.sent() ) {

                    return;
                }

                defer.resolve(res);
            });

        return defer.promise();
    },

    /**
     * Определяет маршрут встроенного роутера
     *
     * @public
     * @memberOf {Framework}
     * @method
     *
     * @param {String} pattern
     * @param {{unit?:String, name?:String}|String} [data]
     *
     * @returns {Framework}
     * */
    route: function (pattern, data) {

        var route;

        if ( !_.isObject(data) ) {
            data = {name: data};
        }

        route = this.router.addRoute(pattern, data);

        if ( _.isUndefined(route.data.unit) || _.isNull(route.data.unit) ) {
            route.data.unit = route.data.name;
        }

        return this;
    },

    /**
     * @protected
     * @memberOf {Framework}
     * @method
     *
     * @param {*} [params]
     *
     * @returns {Router}
     * */
    _createRouter: function (params) {

        return new Router(params);
    },

    /**
     * @protected
     * @memberOf {Framework}
     * @method
     *
     * @returns {Connect}
     * */
    _createTrack: function (req, res) {

        return new Connect(this, req, res);
    },

    /**
     * @protected
     * @memberOf {Framework}
     * @method
     *
     * @returns {vow.Promise}
     * */
    _getReady: function () {

        var promise = this.__base().then(function () {

            return vow.all(_.map(this._plugs, callPlugin, this));
        }, this);

        promise.always(function () {

            while ( _.size(this._pends) ) {
                this._handle(this._pends.shift());
            }

        }, this).done();

        return promise;
    },

    /**
     * @protected
     * @memberOf {Framework}
     * @method
     *
     * @param {Connect} track
     * */
    _handle: function (track) {

        //  был сделан send() где-то в обработчке события sys:request
        if ( track.sent() ) {

            return;
        }

        //  При инициализации произошла ошибка
        if ( this.ready().isRejected() ) {
            track.send(500);

            return;
        }

        //  еще не проинициализирован
        if ( !this.ready().isResolved() ) {
            //  отложить запрос
            this._pends.push(track);

            return;
        }

        (function next () {
            //  выбирается маршрут
            var route = this.router.
                find(track.method, track.url.pathname, track.route);

            //  однозначно нет такого маршрута
            if ( null === route ) {
                this.emit('sys:ematch', track);
                track.send(404);

                return;
            }

            //  возвращен массив
            if ( _.isArray(route) ) {
                //  это тоже значит что нет такого роута
                this.emit('sys:ematch', track);

                //  если массив пустой, то на сервере совсем нет ни одного
                //  маршрута отвечающего по такому методу запроса
                if ( 0 === route.length ) {
                    //  Not Implemented
                    track.send(501);

                    return;
                }

                //  Иначе есть такие маршруты, но для них не
                // поддерживается такой метод
                track.header('Allow', route.join(', '));

                //  Method Not Allowed
                track.send(405);

                return;
            }

            track.match = route.match;
            route = route.route;
            track.route = route.data.name;

            this.emit('sys:match', track);

            this.resolve(track, route.data.unit).done(next, function (err) {
                track.send(500, err);
            }, this);

        }.call(this));
    }

});

function callPlugin (plug) {

    var defer = vow.defer();

    plug.call(this, function (err) {

        if ( 0 === arguments.length ) {
            defer.resolve();

            return;
        }

        defer.reject(err);
    });

    return defer.promise();
}

module.exports = Framework;
<commit_msg>При инициализаци значала инициализирую плагины и только потом узлы<commit_after>'use strict';

var Http = require('http');

var Connect = /** @type Connect */ require('./track/Connect');
var Router = /** @type Router */ require('finger/Router');
var Tracker = /** @type Tracker */ require('./Tracker');

var _ = require('lodash-node');
var inherit = require('inherit');
var vow = require('vow');

/**
 * @class Framework
 * @extends Tracker
 * */
var Framework = inherit(Tracker, /** @lends Framework.prototype */ {

    /**
     * @private
     * @memberOf {Framework}
     * @method
     *
     * @param {Object} [params]
     *
     * @constructs
     * */
    __constructor: function (params) {
        this.__base(params);

        /**
         * Тут откладываются запросы поступившие во время инициализации
         *
         * @protected
         * @memberOf {Framework}
         * @property
         * @type {Array<Track>}
         * */
        this._pends = [];

        /**
         * Плагины, задачи на инициализацию
         *
         * @protected
         * @memberOf {Framework}
         * @property
         * @type {Array<Function>}
         * */
        this._plugs = [];

        /**
         * Шаблоны для track.render()
         *
         * @public
         * @memberOf {Framework}
         * @property
         * @type {Object<Function>}
         * */
        this.renderers = {};

        /**
         * @public
         * @memberOf {Framework}
         * @property
         * @type {Router}
         * */
        this.router = this._createRouter(this.params.router);
    },

    /**
     * Возвращает коллбэк для запросов на сервер
     *
     * @public
     * @memberOf {Framework}
     * @method
     *
     * @returns {Function}
     * */
    getHandler: function () {

        var self = this;

        return function (req, res) {

            var date = new Date();
            var track = self._createTrack(req, res);

            res.once('finish', function () {
                track.time = new Date() - date;
                self.emit('sys:response', track);
            });

            self.emit('sys:request', track);

            self._handle(track);
        };
    },

    /**
     * Запускает сервер и инициализацию приложения
     *
     * @public
     * @memberOf {Framework}
     * @method
     * */
    listen: function () {

        var server = Http.createServer(this.getHandler());

        server.listen.apply(server, arguments);

        //  автоматически запускаю инициализацию
        this.ready(true);

        return server;
    },

    /**
     * Добавляет плагин[ы]
     *
     * @public
     * @memberOf {Framework}
     * @method
     * */
    plug: function () {
        Array.prototype.push.apply(this._plugs, arguments);
    },

    /**
     * Запускает операцию разрешения узла.
     * Если один из узлов, участвующих в операции
     * разрешения выполнил ответ приложения самостоятельно,
     * то коллбэк вызван не будет
     *
     * @public
     * @memberOf {Tracker}
     * @method
     *
     * @param {Connect} track
     * @param {String} path
     * @param {*} [params]
     *
     * @returns {vow.Promise}
     * */
    resolve: function (track, path, params) {

        var defer = vow.defer();

        this.__base(track, path, params).
            always(function (res) {

                if ( track.sent() ) {

                    return;
                }

                defer.resolve(res);
            });

        return defer.promise();
    },

    /**
     * Определяет маршрут встроенного роутера
     *
     * @public
     * @memberOf {Framework}
     * @method
     *
     * @param {String} pattern
     * @param {{unit?:String, name?:String}|String} [data]
     *
     * @returns {Framework}
     * */
    route: function (pattern, data) {

        var route;

        if ( !_.isObject(data) ) {
            data = {name: data};
        }

        route = this.router.addRoute(pattern, data);

        if ( _.isUndefined(route.data.unit) || _.isNull(route.data.unit) ) {
            route.data.unit = route.data.name;
        }

        return this;
    },

    /**
     * @protected
     * @memberOf {Framework}
     * @method
     *
     * @param {*} [params]
     *
     * @returns {Router}
     * */
    _createRouter: function (params) {

        return new Router(params);
    },

    /**
     * @protected
     * @memberOf {Framework}
     * @method
     *
     * @returns {Connect}
     * */
    _createTrack: function (req, res) {

        return new Connect(this, req, res);
    },

    /**
     * @protected
     * @memberOf {Framework}
     * @method
     *
     * @returns {vow.Promise}
     * */
    _getReady: function () {

        var promise = vow.
            //  сначала свой и только потом базовый
            all(_.map(this._plugs, callPlugin, this)).
            then(this.__base, this);

        promise.always(function () {

            while ( _.size(this._pends) ) {
                this._handle(this._pends.shift());
            }

        }, this).done();

        return promise;
    },

    /**
     * @protected
     * @memberOf {Framework}
     * @method
     *
     * @param {Connect} track
     * */
    _handle: function (track) {

        //  был сделан send() где-то в обработчке события sys:request
        if ( track.sent() ) {

            return;
        }

        //  При инициализации произошла ошибка
        if ( this.ready().isRejected() ) {
            track.send(500);

            return;
        }

        //  еще не проинициализирован
        if ( !this.ready().isResolved() ) {
            //  отложить запрос
            this._pends.push(track);

            return;
        }

        (function next () {
            //  выбирается маршрут
            var route = this.router.
                find(track.method, track.url.pathname, track.route);

            //  однозначно нет такого маршрута
            if ( null === route ) {
                this.emit('sys:ematch', track);
                track.send(404);

                return;
            }

            //  возвращен массив
            if ( _.isArray(route) ) {
                //  это тоже значит что нет такого роута
                this.emit('sys:ematch', track);

                //  если массив пустой, то на сервере совсем нет ни одного
                //  маршрута отвечающего по такому методу запроса
                if ( 0 === route.length ) {
                    //  Not Implemented
                    track.send(501);

                    return;
                }

                //  Иначе есть такие маршруты, но для них не
                // поддерживается такой метод
                track.header('Allow', route.join(', '));

                //  Method Not Allowed
                track.send(405);

                return;
            }

            track.match = route.match;
            route = route.route;
            track.route = route.data.name;

            this.emit('sys:match', track);

            this.resolve(track, route.data.unit).done(next, function (err) {
                track.send(500, err);
            }, this);

        }.call(this));
    }

});

function callPlugin (plug) {

    var defer = vow.defer();

    plug.call(this, function (err) {

        if ( 0 === arguments.length ) {
            defer.resolve();

            return;
        }

        defer.reject(err);
    });

    return defer.promise();
}

module.exports = Framework;
<|endoftext|>


<commit_before>export default function mkobj(obj, ...props) {
  if (Array.isArray(obj)) {
    props.unshift(obj);

    // eslint-disable-next-line no-param-reassign
    obj = {};
  }

  props.forEach((prop) => {
    if (prop[0]) {
      // eslint-disable-next-line no-param-reassign
      obj[prop[1]] = prop[2];
    }
  });
}
<commit_msg>Return obj<commit_after>export default function mkobj(obj, ...props) {
  if (Array.isArray(obj)) {
    props.unshift(obj);

    // eslint-disable-next-line no-param-reassign
    obj = {};
  }

  props.forEach((prop) => {
    if (prop[0]) {
      // eslint-disable-next-line no-param-reassign
      obj[prop[1]] = prop[2];
    }
  });

  return obj;
}
<|endoftext|>