1
0

for-of.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. 'use strict';
  2. var callable = require('es5-ext/object/valid-callable')
  3. , isString = require('es5-ext/string/is-string')
  4. , get = require('./get')
  5. , isArray = Array.isArray, call = Function.prototype.call;
  6. module.exports = function (iterable, cb/*, thisArg*/) {
  7. var mode, thisArg = arguments[2], result, doBreak, broken, i, l, char, code;
  8. if (isArray(iterable)) mode = 'array';
  9. else if (isString(iterable)) mode = 'string';
  10. else iterable = get(iterable);
  11. callable(cb);
  12. doBreak = function () { broken = true; };
  13. if (mode === 'array') {
  14. iterable.some(function (value) {
  15. call.call(cb, thisArg, value, doBreak);
  16. if (broken) return true;
  17. });
  18. return;
  19. }
  20. if (mode === 'string') {
  21. l = iterable.length;
  22. for (i = 0; i < l; ++i) {
  23. char = iterable[i];
  24. if ((i + 1) < l) {
  25. code = char.charCodeAt(0);
  26. if ((code >= 0xD800) && (code <= 0xDBFF)) char += iterable[++i];
  27. }
  28. call.call(cb, thisArg, char, doBreak);
  29. if (broken) break;
  30. }
  31. return;
  32. }
  33. result = iterable.next();
  34. while (!result.done) {
  35. call.call(cb, thisArg, result.value, doBreak);
  36. if (broken) return;
  37. result = iterable.next();
  38. }
  39. };