Skip to content

Instantly share code, notes, and snippets.

@Macrofig
Last active February 16, 2016 22:17
Show Gist options
  • Select an option

  • Save Macrofig/4cfb5159afc5544a5a39 to your computer and use it in GitHub Desktop.

Select an option

Save Macrofig/4cfb5159afc5544a5a39 to your computer and use it in GitHub Desktop.
Parse string into array of maps using callback
/**
* @author Juan Orozco
*/
var can = require('can');
require('can/map/define/define');
// The default map for the character item
// The type can be anything, it should be used to mark what the item is
// The value is the character
var DefaultMap = can.Map.extend({
define: {
type: {
value: '',
type: 'string'
},
value: {
value: '',
type: 'string'
}
}
});
var ParseOpts = can.Map.extend({
define: {
raw: {
value: '',
type: 'string'
},
callback: {
value: can.noop
},
ItemMap: {
Value: DefaultMap
}
}
});
var Parsed = can.List.extend({});
var ParseString = can.Construct.extend({
parsed: null,
opts: new ParseOpts({}),
init: function (strToParse, opts) {
this.opts = new ParseOpts({
raw: strToParse,
callback: opts.callback || can.noop,
ItemMap: opts.Map || DefaultMap
});
Parsed.Map = opts.Map || DefaultMap;
this.parsed = new Parsed([]);
},
parse: function () {
var opts = this.opts;
var strToParse = opts.attr('raw');
var Map = opts.attr('ItemMap');
// Set up empty map
var previous = new Map({});
// Loop through item and process it
for (var i = 0; i < strToParse.length; i++) {
// Set up initial map for parser
var current = new Map({value: strToParse[i]});
// Call the passed in callback for parsing
// The previous object is passed as sugar but the context
// will always be the main object which has the parsed array
var resp = this.opts.callback.call(this.parsed, previous, current, i, strToParse);
// Don't keep the current item if parser returns false
if (resp !== false) {
this.parsed.push(current);
}
previous = current;
}
return this.parsed;
}
});
module.exports = ParseString;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment