1 import {appendContextPath, blockParams, createFrame, isArray, isFunction} from '../utils';
2 import Exception from '../exception';
4 export default function(instance) {
5 instance.registerHelper('each', function(context, options) {
7 throw new Exception('Must pass iterator to #each');
11 inverse = options.inverse,
17 if (options.data && options.ids) {
18 contextPath = appendContextPath(options.data.contextPath, options.ids[0]) + '.';
21 if (isFunction(context)) { context = context.call(this); }
24 data = createFrame(options.data);
27 function execIteration(field, index, last) {
31 data.first = index === 0;
35 data.contextPath = contextPath + field;
39 ret = ret + fn(context[field], {
41 blockParams: blockParams([context[field], field], [contextPath + field, null])
45 if (context && typeof context === 'object') {
46 if (isArray(context)) {
47 for (let j = context.length; i < j; i++) {
49 execIteration(i, i, i === context.length - 1);
55 for (let key in context) {
56 if (context.hasOwnProperty(key)) {
57 // We're running the iterations one step out of sync so we can detect
58 // the last iteration without have to scan the object twice and create
59 // an itermediate keys array.
60 if (priorKey !== undefined) {
61 execIteration(priorKey, i - 1);
67 if (priorKey !== undefined) {
68 execIteration(priorKey, i - 1, true);