Version 1
[yaffs-website] / node_modules / for-each / index.js
1 var isFunction = require('is-function')
2
3 module.exports = forEach
4
5 var toString = Object.prototype.toString
6 var hasOwnProperty = Object.prototype.hasOwnProperty
7
8 function forEach(list, iterator, context) {
9     if (!isFunction(iterator)) {
10         throw new TypeError('iterator must be a function')
11     }
12
13     if (arguments.length < 3) {
14         context = this
15     }
16     
17     if (toString.call(list) === '[object Array]')
18         forEachArray(list, iterator, context)
19     else if (typeof list === 'string')
20         forEachString(list, iterator, context)
21     else
22         forEachObject(list, iterator, context)
23 }
24
25 function forEachArray(array, iterator, context) {
26     for (var i = 0, len = array.length; i < len; i++) {
27         if (hasOwnProperty.call(array, i)) {
28             iterator.call(context, array[i], i, array)
29         }
30     }
31 }
32
33 function forEachString(string, iterator, context) {
34     for (var i = 0, len = string.length; i < len; i++) {
35         // no such thing as a sparse string.
36         iterator.call(context, string.charAt(i), i, string)
37     }
38 }
39
40 function forEachObject(object, iterator, context) {
41     for (var k in object) {
42         if (hasOwnProperty.call(object, k)) {
43             iterator.call(context, object[k], k, object)
44         }
45     }
46 }