]> gerrit.simantics Code Review - simantics/district.git/blob - _iterate.js
1ccbaf2742eb163aea390326a917159ecd3dc276
[simantics/district.git] / _iterate.js
1 // Internal method, used by iteration functions.
2 // Calls a function for each key-value pair found in object
3 // Optionally takes compareFn to iterate object in specific order
4
5 'use strict';
6
7 var callable = require('./valid-callable')
8   , value    = require('./valid-value')
9
10   , bind = Function.prototype.bind, call = Function.prototype.call, keys = Object.keys
11   , propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
12
13 module.exports = function (method, defVal) {
14         return function (obj, cb/*, thisArg, compareFn*/) {
15                 var list, thisArg = arguments[2], compareFn = arguments[3];
16                 obj = Object(value(obj));
17                 callable(cb);
18
19                 list = keys(obj);
20                 if (compareFn) {
21                         list.sort((typeof compareFn === 'function') ? bind.call(compareFn, obj) : undefined);
22                 }
23                 if (typeof method !== 'function') method = list[method];
24                 return call.call(method, list, function (key, index) {
25                         if (!propertyIsEnumerable.call(obj, key)) return defVal;
26                         return call.call(cb, thisArg, obj[key], key, obj, index);
27                 });
28         };
29 };