react / react-0.13.3 / examples / basic-commonjs / node_modules / reactify / node_modules / react-tools / src / vendor / core / toArray.js
81158 views/**1* Copyright 2014, Facebook, Inc.2* All rights reserved.3*4* This source code is licensed under the BSD-style license found in the5* LICENSE file in the root directory of this source tree. An additional grant6* of patent rights can be found in the PATENTS file in the same directory.7*8* @providesModule toArray9* @typechecks10*/1112var invariant = require('invariant');1314/**15* Convert array-like objects to arrays.16*17* This API assumes the caller knows the contents of the data type. For less18* well defined inputs use createArrayFrom.19*20* @param {object|function|filelist} obj21* @return {array}22*/23function toArray(obj) {24var length = obj.length;2526// Some browse builtin objects can report typeof 'function' (e.g. NodeList in27// old versions of Safari).28invariant(29!Array.isArray(obj) &&30(typeof obj === 'object' || typeof obj === 'function'),31'toArray: Array-like object expected'32);3334invariant(35typeof length === 'number',36'toArray: Object needs a length property'37);3839invariant(40length === 0 ||41(length - 1) in obj,42'toArray: Object should have keys for indices'43);4445// Old IE doesn't give collections access to hasOwnProperty. Assume inputs46// without method will throw during the slice call and skip straight to the47// fallback.48if (obj.hasOwnProperty) {49try {50return Array.prototype.slice.call(obj);51} catch (e) {52// IE < 9 does not support Array#slice on collections objects53}54}5556// Fall back to copying key by key. This assumes all keys have a value,57// so will not preserve sparsely populated inputs.58var ret = Array(length);59for (var ii = 0; ii < length; ii++) {60ret[ii] = obj[ii];61}62return ret;63}6465module.exports = toArray;666768