for-of.js 1.3 KB

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